lang
stringclasses
2 values
license
stringclasses
13 values
stderr
stringlengths
0
343
commit
stringlengths
40
40
returncode
int64
0
128
repos
stringlengths
6
87.7k
new_contents
stringlengths
0
6.23M
new_file
stringlengths
3
311
old_contents
stringlengths
0
6.23M
message
stringlengths
6
9.1k
old_file
stringlengths
3
311
subject
stringlengths
0
4k
git_diff
stringlengths
0
6.31M
JavaScript
bsd-3-clause
b826cbd3ac9fc4d0e3139432509a4189f1b591f4
0
vsoch/Papaya,vsoch/Papaya,okrad/Papaya,okrad/Papaya,okrad/Papaya,vsoch/Papaya,anarkhede/Papaya,anarkhede/Papaya,anarkhede/Papaya
/*! * Copyright (c) 2012-2013, RII-UTHSCSA * All rights reserved. * * THIS PRODUCT IS NOT FOR CLINICAL USE. * * 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 RII-UTHSCSA 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 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. */ /*jslint browser: true, node: true */ /*global require, module */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Dictionary = daikon.Dictionary || {}; daikon.Utils = daikon.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null); /*** Static Pseudo-constants ***/ daikon.Dictionary.dictPrivate = { "0207" : { "101F" : ["FE", "ElscintDataScale"] // uses special Elscint double type (see Tag class) } }; daikon.Dictionary.dict = { "0002" : { "0000" : ["UL", "Group0002Length"], "0001" : ["OB", "FileMetaInformationVersion"], "0002" : ["UI", "MediaStoredSOPClassUID"], "0003" : ["UI", "MediaStoredSOPInstanceUID"], "0010" : ["UI", "TransferSyntaxUID"], "0012" : ["UI", "ImplementationClassUID"], "0013" : ["SH", "ImplementationVersionName"], "0016" : ["AE", "SourceApplicationEntityTitle"], "0100" : ["UI", "PrivateInformationCreatorUID"], "0102" : ["OB", "PrivateInformation"] }, "0004" : { "0000" : ["UL", "Group0004Length"], "1130" : ["CS", "FilesetID"], "1141" : ["CS", "FilesetDescriptorFileFileID"], "1142" : ["CS", "FilesetDescriptorFileFormat"], "1200" : ["UL", "RootDirectoryEntitysFirstDirectoryRecordOffset"], "1202" : ["UL", "RootDirectoryEntitysLastDirectoryRecordOffset"], "1212" : ["US", "File-setConsistenceFlag"], "1220" : ["SQ", "DirectoryRecordSequence"], "1400" : ["UL", "NextDirectoryRecordOffset"], "1410" : ["US", "RecordInuseFlag"], "1420" : ["UL", "ReferencedLowerlevelDirectoryEntityOffset"], "1430" : ["CS", "DirectoryRecordType"], "1432" : ["UI", "PrivateRecordUID"], "1500" : ["CS", "ReferencedFileID"], "1510" : ["UI", "ReferencedSOPClassUIDInFile"], "1511" : ["UI", "ReferencedSOPInstanceUIDInFile"], "1600" : ["UL", "NumberOfReferences"] }, "0008" : { "0001" : ["UL", "LengthToEnd"], "0005" : ["CS", "SpecificCharacterSet"], "0006" : ["SQ", "LanguageCodeSequence"], "0008" : ["CS", "ImageType"], "0010" : ["SH", "RecognitionCode"], "0012" : ["DA", "InstanceCreationDate"], "0013" : ["TM", "InstanceCreationTime"], "0014" : ["UI", "InstanceCreatorUID"], "0016" : ["UI", "SOPClassUID"], "0018" : ["UI", "SOPInstanceUID"], "001A" : ["UI", "RelatedGeneralSOPClassUID"], "001B" : ["UI", "OriginalSpecializedSOPClassUID"], "0020" : ["DA", "StudyDate"], "0021" : ["DA", "SeriesDate"], "0022" : ["DA", "AcquisitionDate"], "0023" : ["DA", "ContentDate"], "0024" : ["DA", "OverlayDate"], "0025" : ["DA", "CurveDate"], "002A" : ["DT", "AcquisitionDateTime"], "0030" : ["TM", "StudyTime"], "0031" : ["TM", "SeriesTime"], "0032" : ["TM", "AcquisitionTime"], "0033" : ["TM", "ContentTime"], "0034" : ["TM", "OverlayTime"], "0035" : ["TM", "CurveTime"], "0040" : ["US", "DataSetType"], "0041" : ["LO", "DataSetSubtype"], "0042" : ["CS", "NuclearMedicineSeriesType"], "0050" : ["SH", "AccessionNumber"], "0051" : ["SQ", "IssuerOfAccessionNumberSequence"], "0052" : ["CS", "QueryRetrieveLevel"], "0054" : ["AE", "RetrieveAETitle"], "0056" : ["CS", "InstanceAvailability"], "0058" : ["UI", "FailedSOPInstanceUIDList"], "0060" : ["CS", "Modality"], "0061" : ["CS", "ModalitiesInStudy"], "0062" : ["UI", "SOPClassesInStudy"], "0064" : ["CS", "ConversionType"], "0068" : ["CS", "PresentationIntentType"], "0070" : ["LO", "Manufacturer"], "0080" : ["LO", "InstitutionName"], "0081" : ["ST", "InstitutionAddress"], "0082" : ["SQ", "InstitutionCodeSequence"], "0090" : ["PN", "ReferringPhysicianName"], "0092" : ["ST", "ReferringPhysicianAddress"], "0094" : ["SH", "ReferringPhysicianTelephoneNumbers"], "0096" : ["SQ", "ReferringPhysicianIdentificationSequence"], "0100" : ["SH", "CodeValue"], "0102" : ["SH", "CodingSchemeDesignator"], "0103" : ["SH", "CodingSchemeVersion"], "0104" : ["LO", "CodeMeaning"], "0105" : ["CS", "MappingResource"], "0106" : ["DT", "ContextGroupVersion"], "0107" : ["DT", "ContextGroupLocalVersion"], "010B" : ["CS", "ContextGroupExtensionFlag"], "010C" : ["UI", "CodingSchemeUID"], "010D" : ["UI", "ContextGroupExtensionCreatorUID"], "010F" : ["CS", "ContextIdentifier"], "0110" : ["SQ", "CodingSchemeIdentificationSequence"], "0112" : ["LO", "CodingSchemeRegistry"], "0114" : ["ST", "CodingSchemeExternalID"], "0115" : ["ST", "CodingSchemeName"], "0116" : ["ST", "CodingSchemeResponsibleOrganization"], "0117" : ["UI", "ContextUID"], "0201" : ["SH", "TimezoneOffsetFromUTC"], "1000" : ["AE", "NetworkID"], "1010" : ["SH", "StationName"], "1030" : ["LO", "StudyDescription"], "1032" : ["SQ", "ProcedureCodeSequence"], "103E" : ["LO", "SeriesDescription"], "103F" : ["SQ", "SeriesDescriptionCodeSequence"], "1040" : ["LO", "InstitutionalDepartmentName"], "1048" : ["PN", "PhysiciansOfRecord"], "1049" : ["SQ", "PhysiciansOfRecordIdentificationSequence"], "1050" : ["PN", "PerformingPhysicianName"], "1052" : ["SQ", "PerformingPhysicianIdentificationSequence"], "1060" : ["PN", "NameOfPhysiciansReadingStudy"], "1062" : ["SQ", "PhysiciansReadingStudyIdentificationSequence"], "1070" : ["PN", "OperatorsName"], "1072" : ["SQ", "OperatorIdentificationSequence"], "1080" : ["LO", "AdmittingDiagnosesDescription"], "1084" : ["SQ", "AdmittingDiagnosesCodeSequence"], "1090" : ["LO", "ManufacturerModelName"], "1100" : ["SQ", "ReferencedResultsSequence"], "1110" : ["SQ", "ReferencedStudySequence"], "1111" : ["SQ", "ReferencedPerformedProcedureStepSequence"], "1115" : ["SQ", "ReferencedSeriesSequence"], "1120" : ["SQ", "ReferencedPatientSequence"], "1125" : ["SQ", "ReferencedVisitSequence"], "1130" : ["SQ", "ReferencedOverlaySequence"], "1134" : ["SQ", "ReferencedStereometricInstanceSequence"], "113A" : ["SQ", "ReferencedWaveformSequence"], "1140" : ["SQ", "ReferencedImageSequence"], "1145" : ["SQ", "ReferencedCurveSequence"], "114A" : ["SQ", "ReferencedInstanceSequence"], "114B" : ["SQ", "ReferencedRealWorldValueMappingInstanceSequence"], "1150" : ["UI", "ReferencedSOPClassUID"], "1155" : ["UI", "ReferencedSOPInstanceUID"], "115A" : ["UI", "SOPClassesSupported"], "1160" : ["IS", "ReferencedFrameNumber"], "1161" : ["UL", "SimpleFrameList"], "1162" : ["UL", "CalculatedFrameList"], "1163" : ["FD", "TimeRange"], "1164" : ["SQ", "FrameExtractionSequence"], "1167" : ["UI", "MultiFrameSourceSOPInstanceUID"], "1195" : ["UI", "TransactionUID"], "1197" : ["US", "FailureReason"], "1198" : ["SQ", "FailedSOPSequence"], "1199" : ["SQ", "ReferencedSOPSequence"], "1200" : ["SQ", "StudiesContainingOtherReferencedInstancesSequence"], "1250" : ["SQ", "RelatedSeriesSequence"], "2110" : ["CS", "LossyImageCompressionRetired"], "2111" : ["ST", "DerivationDescription"], "2112" : ["SQ", "SourceImageSequence"], "2120" : ["SH", "StageName"], "2122" : ["IS", "StageNumber"], "2124" : ["IS", "NumberOfStages"], "2127" : ["SH", "ViewName"], "2128" : ["IS", "ViewNumber"], "2129" : ["IS", "NumberOfEventTimers"], "212A" : ["IS", "NumberOfViewsInStage"], "2130" : ["DS", "EventElapsedTimes"], "2132" : ["LO", "EventTimerNames"], "2133" : ["SQ", "EventTimerSequence"], "2134" : ["FD", "EventTimeOffset"], "2135" : ["SQ", "EventCodeSequence"], "2142" : ["IS", "StartTrim"], "2143" : ["IS", "StopTrim"], "2144" : ["IS", "RecommendedDisplayFrameRate"], "2200" : ["CS", "TransducerPosition"], "2204" : ["CS", "TransducerOrientation"], "2208" : ["CS", "AnatomicStructure"], "2218" : ["SQ", "AnatomicRegionSequence"], "2220" : ["SQ", "AnatomicRegionModifierSequence"], "2228" : ["SQ", "PrimaryAnatomicStructureSequence"], "2229" : ["SQ", "AnatomicStructureSpaceOrRegionSequence"], "2230" : ["SQ", "PrimaryAnatomicStructureModifierSequence"], "2240" : ["SQ", "TransducerPositionSequence"], "2242" : ["SQ", "TransducerPositionModifierSequence"], "2244" : ["SQ", "TransducerOrientationSequence"], "2246" : ["SQ", "TransducerOrientationModifierSequence"], "2251" : ["SQ", "AnatomicStructureSpaceOrRegionCodeSequenceTrial"], "2253" : ["SQ", "AnatomicPortalOfEntranceCodeSequenceTrial"], "2255" : ["SQ", "AnatomicApproachDirectionCodeSequenceTrial"], "2256" : ["ST", "AnatomicPerspectiveDescriptionTrial"], "2257" : ["SQ", "AnatomicPerspectiveCodeSequenceTrial"], "2258" : ["ST", "AnatomicLocationOfExaminingInstrumentDescriptionTrial"], "2259" : ["SQ", "AnatomicLocationOfExaminingInstrumentCodeSequenceTrial"], "225A" : ["SQ", "AnatomicStructureSpaceOrRegionModifierCodeSequenceTrial"], "225C" : ["SQ", "OnAxisBackgroundAnatomicStructureCodeSequenceTrial"], "3001" : ["SQ", "AlternateRepresentationSequence"], "3010" : ["UI", "IrradiationEventUID"], "4000" : ["LT", "IdentifyingComments"], "9007" : ["CS", "FrameType"], "9092" : ["SQ", "ReferencedImageEvidenceSequence"], "9121" : ["SQ", "ReferencedRawDataSequence"], "9123" : ["UI", "CreatorVersionUID"], "9124" : ["SQ", "DerivationImageSequence"], "9154" : ["SQ", "SourceImageEvidenceSequence"], "9205" : ["CS", "PixelPresentation"], "9206" : ["CS", "VolumetricProperties"], "9207" : ["CS", "VolumeBasedCalculationTechnique"], "9208" : ["CS", "ComplexImageComponent"], "9209" : ["CS", "AcquisitionContrast"], "9215" : ["SQ", "DerivationCodeSequence"], "9237" : ["SQ", "ReferencedPresentationStateSequence"], "9410" : ["SQ", "ReferencedOtherPlaneSequence"], "9458" : ["SQ", "FrameDisplaySequence"], "9459" : ["FL", "RecommendedDisplayFrameRateInFloat"], "9460" : ["CS", "SkipFrameRangeFlag"] }, "0010" : { "0010" : ["PN", "PatientName"], "0020" : ["LO", "PatientID"], "0021" : ["LO", "IssuerOfPatientID"], "0022" : ["CS", "TypeOfPatientID"], "0024" : ["SQ", "IssuerOfPatientIDQualifiersSequence"], "0030" : ["DA", "PatientBirthDate"], "0032" : ["TM", "PatientBirthTime"], "0040" : ["CS", "PatientSex"], "0050" : ["SQ", "PatientInsurancePlanCodeSequence"], "0101" : ["SQ", "PatientPrimaryLanguageCodeSequence"], "0102" : ["SQ", "PatientPrimaryLanguageModifierCodeSequence"], "1000" : ["LO", "OtherPatientIDs"], "1001" : ["PN", "OtherPatientNames"], "1002" : ["SQ", "OtherPatientIDsSequence"], "1005" : ["PN", "PatientBirthName"], "1010" : ["AS", "PatientAge"], "1020" : ["DS", "PatientSize"], "1021" : ["SQ", "PatientSizeCodeSequence"], "1030" : ["DS", "PatientWeight"], "1040" : ["LO", "PatientAddress"], "1050" : ["LO", "InsurancePlanIdentification"], "1060" : ["PN", "PatientMotherBirthName"], "1080" : ["LO", "MilitaryRank"], "1081" : ["LO", "BranchOfService"], "1090" : ["LO", "MedicalRecordLocator"], "2000" : ["LO", "MedicalAlerts"], "2110" : ["LO", "Allergies"], "2150" : ["LO", "CountryOfResidence"], "2152" : ["LO", "RegionOfResidence"], "2154" : ["SH", "PatientTelephoneNumbers"], "2160" : ["SH", "EthnicGroup"], "2180" : ["SH", "Occupation"], "21A0" : ["CS", "SmokingStatus"], "21B0" : ["LT", "AdditionalPatientHistory"], "21C0" : ["US", "PregnancyStatus"], "21D0" : ["DA", "LastMenstrualDate"], "21F0" : ["LO", "PatientReligiousPreference"], "2201" : ["LO", "PatientSpeciesDescription"], "2202" : ["SQ", "PatientSpeciesCodeSequence"], "2203" : ["CS", "PatientSexNeutered"], "2210" : ["CS", "AnatomicalOrientationType"], "2292" : ["LO", "PatientBreedDescription"], "2293" : ["SQ", "PatientBreedCodeSequence"], "2294" : ["SQ", "BreedRegistrationSequence"], "2295" : ["LO", "BreedRegistrationNumber"], "2296" : ["SQ", "BreedRegistryCodeSequence"], "2297" : ["PN", "ResponsiblePerson"], "2298" : ["CS", "ResponsiblePersonRole"], "2299" : ["LO", "ResponsibleOrganization"], "4000" : ["LT", "PatientComments"], "9431" : ["FL", "ExaminedBodyThickness"] }, "0012" : { "0010" : ["LO", "ClinicalTrialSponsorName"], "0020" : ["LO", "ClinicalTrialProtocolID"], "0021" : ["LO", "ClinicalTrialProtocolName"], "0030" : ["LO", "ClinicalTrialSiteID"], "0031" : ["LO", "ClinicalTrialSiteName"], "0040" : ["LO", "ClinicalTrialSubjectID"], "0042" : ["LO", "ClinicalTrialSubjectReadingID"], "0050" : ["LO", "ClinicalTrialTimePointID"], "0051" : ["ST", "ClinicalTrialTimePointDescription"], "0060" : ["LO", "ClinicalTrialCoordinatingCenterName"], "0062" : ["CS", "PatientIdentityRemoved"], "0063" : ["LO", "DeidentificationMethod"], "0064" : ["SQ", "DeidentificationMethodCodeSequence"], "0071" : ["LO", "ClinicalTrialSeriesID"], "0072" : ["LO", "ClinicalTrialSeriesDescription"], "0081" : ["LO", "ClinicalTrialProtocolEthicsCommitteeName"], "0082" : ["LO", "ClinicalTrialProtocolEthicsCommitteeApprovalNumber"], "0083" : ["SQ", "ConsentForClinicalTrialUseSequence"], "0084" : ["CS", "DistributionType"], "0085" : ["CS", "ConsentForDistributionFlag"] }, "0014" : { "0023" : ["ST", "CADFileFormat"], "0024" : ["ST", "ComponentReferenceSystem"], "0025" : ["ST", "ComponentManufacturingProcedure"], "0028" : ["ST", "ComponentManufacturer"], "0030" : ["DS", "MaterialThickness"], "0032" : ["DS", "MaterialPipeDiameter"], "0034" : ["DS", "MaterialIsolationDiameter"], "0042" : ["ST", "MaterialGrade"], "0044" : ["ST", "MaterialPropertiesFileID"], "0045" : ["ST", "MaterialPropertiesFileFormat"], "0046" : ["LT", "MaterialNotes"], "0050" : ["CS", "ComponentShape"], "0052" : ["CS", "CurvatureType"], "0054" : ["DS", "OuterDiameter"], "0056" : ["DS", "InnerDiameter"], "1010" : ["ST", "ActualEnvironmentalConditions"], "1020" : ["DA", "ExpiryDate"], "1040" : ["ST", "EnvironmentalConditions"], "2002" : ["SQ", "EvaluatorSequence"], "2004" : ["IS", "EvaluatorNumber"], "2006" : ["PN", "EvaluatorName"], "2008" : ["IS", "EvaluationAttempt"], "2012" : ["SQ", "IndicationSequence"], "2014" : ["IS", "IndicationNumber "], "2016" : ["SH", "IndicationLabel"], "2018" : ["ST", "IndicationDescription"], "201A" : ["CS", "IndicationType"], "201C" : ["CS", "IndicationDisposition"], "201E" : ["SQ", "IndicationROISequence"], "2030" : ["SQ", "IndicationPhysicalPropertySequence"], "2032" : ["SH", "PropertyLabel"], "2202" : ["IS", "CoordinateSystemNumberOfAxes "], "2204" : ["SQ", "CoordinateSystemAxesSequence"], "2206" : ["ST", "CoordinateSystemAxisDescription"], "2208" : ["CS", "CoordinateSystemDataSetMapping"], "220A" : ["IS", "CoordinateSystemAxisNumber"], "220C" : ["CS", "CoordinateSystemAxisType"], "220E" : ["CS", "CoordinateSystemAxisUnits"], "2210" : ["OB", "CoordinateSystemAxisValues"], "2220" : ["SQ", "CoordinateSystemTransformSequence"], "2222" : ["ST", "TransformDescription"], "2224" : ["IS", "TransformNumberOfAxes"], "2226" : ["IS", "TransformOrderOfAxes"], "2228" : ["CS", "TransformedAxisUnits"], "222A" : ["DS", "CoordinateSystemTransformRotationAndScaleMatrix"], "222C" : ["DS", "CoordinateSystemTransformTranslationMatrix"], "3011" : ["DS", "InternalDetectorFrameTime"], "3012" : ["DS", "NumberOfFramesIntegrated"], "3020" : ["SQ", "DetectorTemperatureSequence"], "3022" : ["DS", "SensorName"], "3024" : ["DS", "HorizontalOffsetOfSensor"], "3026" : ["DS", "VerticalOffsetOfSensor"], "3028" : ["DS", "SensorTemperature"], "3040" : ["SQ", "DarkCurrentSequence"], "3050" : ["OB", "DarkCurrentCounts"], "3060" : ["SQ", "GainCorrectionReferenceSequence"], "3070" : ["OB", "AirCounts"], "3071" : ["DS", "KVUsedInGainCalibration"], "3072" : ["DS", "MAUsedInGainCalibration"], "3073" : ["DS", "NumberOfFramesUsedForIntegration"], "3074" : ["LO", "FilterMaterialUsedInGainCalibration"], "3075" : ["DS", "FilterThicknessUsedInGainCalibration"], "3076" : ["DA", "DateOfGainCalibration"], "3077" : ["TM", "TimeOfGainCalibration"], "3080" : ["OB", "BadPixelImage"], "3099" : ["LT", "CalibrationNotes"], "4002" : ["SQ", "PulserEquipmentSequence"], "4004" : ["CS", "PulserType"], "4006" : ["LT", "PulserNotes"], "4008" : ["SQ", "ReceiverEquipmentSequence"], "400A" : ["CS", "AmplifierType"], "400C" : ["LT", "ReceiverNotes"], "400E" : ["SQ", "PreAmplifierEquipmentSequence"], "400F" : ["LT", "PreAmplifierNotes"], "4010" : ["SQ", "TransmitTransducerSequence"], "4011" : ["SQ", "ReceiveTransducerSequence"], "4012" : ["US", "NumberOfElements"], "4013" : ["CS", "ElementShape"], "4014" : ["DS", "ElementDimensionA"], "4015" : ["DS", "ElementDimensionB"], "4016" : ["DS", "ElementPitch"], "4017" : ["DS", "MeasuredBeamDimensionA"], "4018" : ["DS", "MeasuredBeamDimensionB"], "4019" : ["DS", "LocationOfMeasuredBeamDiameter"], "401A" : ["DS", "NominalFrequency"], "401B" : ["DS", "MeasuredCenterFrequency"], "401C" : ["DS", "MeasuredBandwidth"], "4020" : ["SQ", "PulserSettingsSequence"], "4022" : ["DS", "PulseWidth"], "4024" : ["DS", "ExcitationFrequency"], "4026" : ["CS", "ModulationType"], "4028" : ["DS", "Damping"], "4030" : ["SQ", "ReceiverSettingsSequence"], "4031" : ["DS", "AcquiredSoundpathLength"], "4032" : ["CS", "AcquisitionCompressionType"], "4033" : ["IS", "AcquisitionSampleSize"], "4034" : ["DS", "RectifierSmoothing"], "4035" : ["SQ", "DACSequence"], "4036" : ["CS", "DACType"], "4038" : ["DS", "DACGainPoints"], "403A" : ["DS", "DACTimePoints"], "403C" : ["DS", "DACAmplitude"], "4040" : ["SQ", "PreAmplifierSettingsSequence"], "4050" : ["SQ", "TransmitTransducerSettingsSequence"], "4051" : ["SQ", "ReceiveTransducerSettingsSequence"], "4052" : ["DS", "IncidentAngle"], "4054" : ["ST", "CouplingTechnique"], "4056" : ["ST", "CouplingMedium"], "4057" : ["DS", "CouplingVelocity"], "4058" : ["DS", "CrystalCenterLocationX"], "4059" : ["DS", "CrystalCenterLocationZ"], "405A" : ["DS", "SoundPathLength"], "405C" : ["ST", "DelayLawIdentifier"], "4060" : ["SQ", "GateSettingsSequence"], "4062" : ["DS", "GateThreshold"], "4064" : ["DS", "VelocityOfSound"], "4070" : ["SQ", "CalibrationSettingsSequence"], "4072" : ["ST", "CalibrationProcedure"], "4074" : ["SH", "ProcedureVersion"], "4076" : ["DA", "ProcedureCreationDate"], "4078" : ["DA", "ProcedureExpirationDate"], "407A" : ["DA", "ProcedureLastModifiedDate"], "407C" : ["TM", "CalibrationTime"], "407E" : ["DA", "CalibrationDate"], "5002" : ["IS", "LINACEnergy"], "5004" : ["IS", "LINACOutput"] }, "0018" : { "0010" : ["LO", "ContrastBolusAgent"], "0012" : ["SQ", "ContrastBolusAgentSequence"], "0014" : ["SQ", "ContrastBolusAdministrationRouteSequence"], "0015" : ["CS", "BodyPartExamined"], "0020" : ["CS", "ScanningSequence"], "0021" : ["CS", "SequenceVariant"], "0022" : ["CS", "ScanOptions"], "0023" : ["CS", "MRAcquisitionType"], "0024" : ["SH", "SequenceName"], "0025" : ["CS", "AngioFlag"], "0026" : ["SQ", "InterventionDrugInformationSequence"], "0027" : ["TM", "InterventionDrugStopTime"], "0028" : ["DS", "InterventionDrugDose"], "0029" : ["SQ", "InterventionDrugCodeSequence"], "002A" : ["SQ", "AdditionalDrugSequence"], "0030" : ["LO", "Radionuclide"], "0031" : ["LO", "Radiopharmaceutical"], "0032" : ["DS", "EnergyWindowCenterline"], "0033" : ["DS", "EnergyWindowTotalWidth"], "0034" : ["LO", "InterventionDrugName"], "0035" : ["TM", "InterventionDrugStartTime"], "0036" : ["SQ", "InterventionSequence"], "0037" : ["CS", "TherapyType"], "0038" : ["CS", "InterventionStatus"], "0039" : ["CS", "TherapyDescription"], "003A" : ["ST", "InterventionDescription"], "0040" : ["IS", "CineRate"], "0042" : ["CS", "InitialCineRunState"], "0050" : ["DS", "SliceThickness"], "0060" : ["DS", "KVP"], "0070" : ["IS", "CountsAccumulated"], "0071" : ["CS", "AcquisitionTerminationCondition"], "0072" : ["DS", "EffectiveDuration"], "0073" : ["CS", "AcquisitionStartCondition"], "0074" : ["IS", "AcquisitionStartConditionData"], "0075" : ["IS", "AcquisitionTerminationConditionData"], "0080" : ["DS", "RepetitionTime"], "0081" : ["DS", "EchoTime"], "0082" : ["DS", "InversionTime"], "0083" : ["DS", "NumberOfAverages"], "0084" : ["DS", "ImagingFrequency"], "0085" : ["SH", "ImagedNucleus"], "0086" : ["IS", "EchoNumbers"], "0087" : ["DS", "MagneticFieldStrength"], "0088" : ["DS", "SpacingBetweenSlices"], "0089" : ["IS", "NumberOfPhaseEncodingSteps"], "0090" : ["DS", "DataCollectionDiameter"], "0091" : ["IS", "EchoTrainLength"], "0093" : ["DS", "PercentSampling"], "0094" : ["DS", "PercentPhaseFieldOfView"], "0095" : ["DS", "PixelBandwidth"], "1000" : ["LO", "DeviceSerialNumber"], "1002" : ["UI", "DeviceUID"], "1003" : ["LO", "DeviceID"], "1004" : ["LO", "PlateID"], "1005" : ["LO", "GeneratorID"], "1006" : ["LO", "GridID"], "1007" : ["LO", "CassetteID"], "1008" : ["LO", "GantryID"], "1010" : ["LO", "SecondaryCaptureDeviceID"], "1011" : ["LO", "HardcopyCreationDeviceID"], "1012" : ["DA", "DateOfSecondaryCapture"], "1014" : ["TM", "TimeOfSecondaryCapture"], "1016" : ["LO", "SecondaryCaptureDeviceManufacturer"], "1017" : ["LO", "HardcopyDeviceManufacturer"], "1018" : ["LO", "SecondaryCaptureDeviceManufacturerModelName"], "1019" : ["LO", "SecondaryCaptureDeviceSoftwareVersions"], "101A" : ["LO", "HardcopyDeviceSoftwareVersion"], "101B" : ["LO", "HardcopyDeviceManufacturerModelName"], "1020" : ["LO", "SoftwareVersions"], "1022" : ["SH", "VideoImageFormatAcquired"], "1023" : ["LO", "DigitalImageFormatAcquired"], "1030" : ["LO", "ProtocolName"], "1040" : ["LO", "ContrastBolusRoute"], "1041" : ["DS", "ContrastBolusVolume"], "1042" : ["TM", "ContrastBolusStartTime"], "1043" : ["TM", "ContrastBolusStopTime"], "1044" : ["DS", "ContrastBolusTotalDose"], "1045" : ["IS", "SyringeCounts"], "1046" : ["DS", "ContrastFlowRate"], "1047" : ["DS", "ContrastFlowDuration"], "1048" : ["CS", "ContrastBolusIngredient"], "1049" : ["DS", "ContrastBolusIngredientConcentration"], "1050" : ["DS", "SpatialResolution"], "1060" : ["DS", "TriggerTime"], "1061" : ["LO", "TriggerSourceOrType"], "1062" : ["IS", "NominalInterval"], "1063" : ["DS", "FrameTime"], "1064" : ["LO", "CardiacFramingType"], "1065" : ["DS", "FrameTimeVector"], "1066" : ["DS", "FrameDelay"], "1067" : ["DS", "ImageTriggerDelay"], "1068" : ["DS", "MultiplexGroupTimeOffset"], "1069" : ["DS", "TriggerTimeOffset"], "106A" : ["CS", "SynchronizationTrigger"], "106C" : ["US", "SynchronizationChannel"], "106E" : ["UL", "TriggerSamplePosition"], "1070" : ["LO", "RadiopharmaceuticalRoute"], "1071" : ["DS", "RadiopharmaceuticalVolume"], "1072" : ["TM", "RadiopharmaceuticalStartTime"], "1073" : ["TM", "RadiopharmaceuticalStopTime"], "1074" : ["DS", "RadionuclideTotalDose"], "1075" : ["DS", "RadionuclideHalfLife"], "1076" : ["DS", "RadionuclidePositronFraction"], "1077" : ["DS", "RadiopharmaceuticalSpecificActivity"], "1078" : ["DT", "RadiopharmaceuticalStartDateTime"], "1079" : ["DT", "RadiopharmaceuticalStopDateTime"], "1080" : ["CS", "BeatRejectionFlag"], "1081" : ["IS", "LowRRValue"], "1082" : ["IS", "HighRRValue"], "1083" : ["IS", "IntervalsAcquired"], "1084" : ["IS", "IntervalsRejected"], "1085" : ["LO", "PVCRejection"], "1086" : ["IS", "SkipBeats"], "1088" : ["IS", "HeartRate"], "1090" : ["IS", "CardiacNumberOfImages"], "1094" : ["IS", "TriggerWindow"], "1100" : ["DS", "ReconstructionDiameter"], "1110" : ["DS", "DistanceSourceToDetector"], "1111" : ["DS", "DistanceSourceToPatient"], "1114" : ["DS", "EstimatedRadiographicMagnificationFactor"], "1120" : ["DS", "GantryDetectorTilt"], "1121" : ["DS", "GantryDetectorSlew"], "1130" : ["DS", "TableHeight"], "1131" : ["DS", "TableTraverse"], "1134" : ["CS", "TableMotion"], "1135" : ["DS", "TableVerticalIncrement"], "1136" : ["DS", "TableLateralIncrement"], "1137" : ["DS", "TableLongitudinalIncrement"], "1138" : ["DS", "TableAngle"], "113A" : ["CS", "TableType"], "1140" : ["CS", "RotationDirection"], "1141" : ["DS", "AngularPosition"], "1142" : ["DS", "RadialPosition"], "1143" : ["DS", "ScanArc"], "1144" : ["DS", "AngularStep"], "1145" : ["DS", "CenterOfRotationOffset"], "1146" : ["DS", "RotationOffset"], "1147" : ["CS", "FieldOfViewShape"], "1149" : ["IS", "FieldOfViewDimensions"], "1150" : ["IS", "ExposureTime"], "1151" : ["IS", "XRayTubeCurrent"], "1152" : ["IS", "Exposure"], "1153" : ["IS", "ExposureInuAs"], "1154" : ["DS", "AveragePulseWidth"], "1155" : ["CS", "RadiationSetting"], "1156" : ["CS", "RectificationType"], "115A" : ["CS", "RadiationMode"], "115E" : ["DS", "ImageAndFluoroscopyAreaDoseProduct"], "1160" : ["SH", "FilterType"], "1161" : ["LO", "TypeOfFilters"], "1162" : ["DS", "IntensifierSize"], "1164" : ["DS", "ImagerPixelSpacing"], "1166" : ["CS", "Grid"], "1170" : ["IS", "GeneratorPower"], "1180" : ["SH", "CollimatorGridName"], "1181" : ["CS", "CollimatorType"], "1182" : ["IS", "FocalDistance"], "1183" : ["DS", "XFocusCenter"], "1184" : ["DS", "YFocusCenter"], "1190" : ["DS", "FocalSpots"], "1191" : ["CS", "AnodeTargetMaterial"], "11A0" : ["DS", "BodyPartThickness"], "11A2" : ["DS", "CompressionForce"], "1200" : ["DA", "DateOfLastCalibration"], "1201" : ["TM", "TimeOfLastCalibration"], "1210" : ["SH", "ConvolutionKernel"], "1240" : ["IS", "UpperLowerPixelValues"], "1242" : ["IS", "ActualFrameDuration"], "1243" : ["IS", "CountRate"], "1244" : ["US", "PreferredPlaybackSequencing"], "1250" : ["SH", "ReceiveCoilName"], "1251" : ["SH", "TransmitCoilName"], "1260" : ["SH", "PlateType"], "1261" : ["LO", "PhosphorType"], "1300" : ["DS", "ScanVelocity"], "1301" : ["CS", "WholeBodyTechnique"], "1302" : ["IS", "ScanLength"], "1310" : ["US", "AcquisitionMatrix"], "1312" : ["CS", "InPlanePhaseEncodingDirection"], "1314" : ["DS", "FlipAngle"], "1315" : ["CS", "VariableFlipAngleFlag"], "1316" : ["DS", "SAR"], "1318" : ["DS", "dBdt"], "1400" : ["LO", "AcquisitionDeviceProcessingDescription"], "1401" : ["LO", "AcquisitionDeviceProcessingCode"], "1402" : ["CS", "CassetteOrientation"], "1403" : ["CS", "CassetteSize"], "1404" : ["US", "ExposuresOnPlate"], "1405" : ["IS", "RelativeXRayExposure"], "1411" : ["DS", "ExposureIndex"], "1412" : ["DS", "TargetExposureIndex"], "1413" : ["DS", "DeviationIndex"], "1450" : ["DS", "ColumnAngulation"], "1460" : ["DS", "TomoLayerHeight"], "1470" : ["DS", "TomoAngle"], "1480" : ["DS", "TomoTime"], "1490" : ["CS", "TomoType"], "1491" : ["CS", "TomoClass"], "1495" : ["IS", "NumberOfTomosynthesisSourceImages"], "1500" : ["CS", "PositionerMotion"], "1508" : ["CS", "PositionerType"], "1510" : ["DS", "PositionerPrimaryAngle"], "1511" : ["DS", "PositionerSecondaryAngle"], "1520" : ["DS", "PositionerPrimaryAngleIncrement"], "1521" : ["DS", "PositionerSecondaryAngleIncrement"], "1530" : ["DS", "DetectorPrimaryAngle"], "1531" : ["DS", "DetectorSecondaryAngle"], "1600" : ["CS", "ShutterShape"], "1602" : ["IS", "ShutterLeftVerticalEdge"], "1604" : ["IS", "ShutterRightVerticalEdge"], "1606" : ["IS", "ShutterUpperHorizontalEdge"], "1608" : ["IS", "ShutterLowerHorizontalEdge"], "1610" : ["IS", "CenterOfCircularShutter"], "1612" : ["IS", "RadiusOfCircularShutter"], "1620" : ["IS", "VerticesOfThePolygonalShutter"], "1622" : ["US", "ShutterPresentationValue"], "1623" : ["US", "ShutterOverlayGroup"], "1624" : ["US", "ShutterPresentationColorCIELabValue"], "1700" : ["CS", "CollimatorShape"], "1702" : ["IS", "CollimatorLeftVerticalEdge"], "1704" : ["IS", "CollimatorRightVerticalEdge"], "1706" : ["IS", "CollimatorUpperHorizontalEdge"], "1708" : ["IS", "CollimatorLowerHorizontalEdge"], "1710" : ["IS", "CenterOfCircularCollimator"], "1712" : ["IS", "RadiusOfCircularCollimator"], "1720" : ["IS", "VerticesOfThePolygonalCollimator"], "1800" : ["CS", "AcquisitionTimeSynchronized"], "1801" : ["SH", "TimeSource"], "1802" : ["CS", "TimeDistributionProtocol"], "1803" : ["LO", "NTPSourceAddress"], "2001" : ["IS", "PageNumberVector"], "2002" : ["SH", "FrameLabelVector"], "2003" : ["DS", "FramePrimaryAngleVector"], "2004" : ["DS", "FrameSecondaryAngleVector"], "2005" : ["DS", "SliceLocationVector"], "2006" : ["SH", "DisplayWindowLabelVector"], "2010" : ["DS", "NominalScannedPixelSpacing"], "2020" : ["CS", "DigitizingDeviceTransportDirection"], "2030" : ["DS", "RotationOfScannedFilm"], "3100" : ["CS", "IVUSAcquisition"], "3101" : ["DS", "IVUSPullbackRate"], "3102" : ["DS", "IVUSGatedRate"], "3103" : ["IS", "IVUSPullbackStartFrameNumber"], "3104" : ["IS", "IVUSPullbackStopFrameNumber"], "3105" : ["IS", "LesionNumber"], "4000" : ["LT", "AcquisitionComments"], "5000" : ["SH", "OutputPower"], "5010" : ["LO", "TransducerData"], "5012" : ["DS", "FocusDepth"], "5020" : ["LO", "ProcessingFunction"], "5021" : ["LO", "PostprocessingFunction"], "5022" : ["DS", "MechanicalIndex"], "5024" : ["DS", "BoneThermalIndex"], "5026" : ["DS", "CranialThermalIndex"], "5027" : ["DS", "SoftTissueThermalIndex"], "5028" : ["DS", "SoftTissueFocusThermalIndex"], "5029" : ["DS", "SoftTissueSurfaceThermalIndex"], "5030" : ["DS", "DynamicRange"], "5040" : ["DS", "TotalGain"], "5050" : ["IS", "DepthOfScanField"], "5100" : ["CS", "PatientPosition"], "5101" : ["CS", "ViewPosition"], "5104" : ["SQ", "ProjectionEponymousNameCodeSequence"], "5210" : ["DS", "ImageTransformationMatrix"], "5212" : ["DS", "ImageTranslationVector"], "6000" : ["DS", "Sensitivity"], "6011" : ["SQ", "SequenceOfUltrasoundRegions"], "6012" : ["US", "RegionSpatialFormat"], "6014" : ["US", "RegionDataType"], "6016" : ["UL", "RegionFlags"], "6018" : ["UL", "RegionLocationMinX0"], "601A" : ["UL", "RegionLocationMinY0"], "601C" : ["UL", "RegionLocationMaxX1"], "601E" : ["UL", "RegionLocationMaxY1"], "6020" : ["SL", "ReferencePixelX0"], "6022" : ["SL", "ReferencePixelY0"], "6024" : ["US", "PhysicalUnitsXDirection"], "6026" : ["US", "PhysicalUnitsYDirection"], "6028" : ["FD", "ReferencePixelPhysicalValueX"], "602A" : ["FD", "ReferencePixelPhysicalValueY"], "602C" : ["FD", "PhysicalDeltaX"], "602E" : ["FD", "PhysicalDeltaY"], "6030" : ["UL", "TransducerFrequency"], "6031" : ["CS", "TransducerType"], "6032" : ["UL", "PulseRepetitionFrequency"], "6034" : ["FD", "DopplerCorrectionAngle"], "6036" : ["FD", "SteeringAngle"], "6038" : ["UL", "DopplerSampleVolumeXPositionRetired"], "6039" : ["SL", "DopplerSampleVolumeXPosition"], "603A" : ["UL", "DopplerSampleVolumeYPositionRetired"], "603B" : ["SL", "DopplerSampleVolumeYPosition"], "603C" : ["UL", "TMLinePositionX0Retired"], "603D" : ["SL", "TMLinePositionX0"], "603E" : ["UL", "TMLinePositionY0Retired"], "603F" : ["SL", "TMLinePositionY0"], "6040" : ["UL", "TMLinePositionX1Retired"], "6041" : ["SL", "TMLinePositionX1"], "6042" : ["UL", "TMLinePositionY1Retired"], "6043" : ["SL", "TMLinePositionY1"], "6044" : ["US", "PixelComponentOrganization"], "6046" : ["UL", "PixelComponentMask"], "6048" : ["UL", "PixelComponentRangeStart"], "604A" : ["UL", "PixelComponentRangeStop"], "604C" : ["US", "PixelComponentPhysicalUnits"], "604E" : ["US", "PixelComponentDataType"], "6050" : ["UL", "NumberOfTableBreakPoints"], "6052" : ["UL", "TableOfXBreakPoints"], "6054" : ["FD", "TableOfYBreakPoints"], "6056" : ["UL", "NumberOfTableEntries"], "6058" : ["UL", "TableOfPixelValues"], "605A" : ["FL", "TableOfParameterValues"], "6060" : ["FL", "RWaveTimeVector"], "7000" : ["CS", "DetectorConditionsNominalFlag"], "7001" : ["DS", "DetectorTemperature"], "7004" : ["CS", "DetectorType"], "7005" : ["CS", "DetectorConfiguration"], "7006" : ["LT", "DetectorDescription"], "7008" : ["LT", "DetectorMode"], "700A" : ["SH", "DetectorID"], "700C" : ["DA", "DateOfLastDetectorCalibration"], "700E" : ["TM", "TimeOfLastDetectorCalibration"], "7010" : ["IS", "ExposuresOnDetectorSinceLastCalibration"], "7011" : ["IS", "ExposuresOnDetectorSinceManufactured"], "7012" : ["DS", "DetectorTimeSinceLastExposure"], "7014" : ["DS", "DetectorActiveTime"], "7016" : ["DS", "DetectorActivationOffsetFromExposure"], "701A" : ["DS", "DetectorBinning"], "7020" : ["DS", "DetectorElementPhysicalSize"], "7022" : ["DS", "DetectorElementSpacing"], "7024" : ["CS", "DetectorActiveShape"], "7026" : ["DS", "DetectorActiveDimensions"], "7028" : ["DS", "DetectorActiveOrigin"], "702A" : ["LO", "DetectorManufacturerName"], "702B" : ["LO", "DetectorManufacturerModelName"], "7030" : ["DS", "FieldOfViewOrigin"], "7032" : ["DS", "FieldOfViewRotation"], "7034" : ["CS", "FieldOfViewHorizontalFlip"], "7036" : ["FL", "PixelDataAreaOriginRelativeToFOV"], "7038" : ["FL", "PixelDataAreaRotationAngleRelativeToFOV"], "7040" : ["LT", "GridAbsorbingMaterial"], "7041" : ["LT", "GridSpacingMaterial"], "7042" : ["DS", "GridThickness"], "7044" : ["DS", "GridPitch"], "7046" : ["IS", "GridAspectRatio"], "7048" : ["DS", "GridPeriod"], "704C" : ["DS", "GridFocalDistance"], "7050" : ["CS", "FilterMaterial"], "7052" : ["DS", "FilterThicknessMinimum"], "7054" : ["DS", "FilterThicknessMaximum"], "7056" : ["FL", "FilterBeamPathLengthMinimum"], "7058" : ["FL", "FilterBeamPathLengthMaximum"], "7060" : ["CS", "ExposureControlMode"], "7062" : ["LT", "ExposureControlModeDescription"], "7064" : ["CS", "ExposureStatus"], "7065" : ["DS", "PhototimerSetting"], "8150" : ["DS", "ExposureTimeInuS"], "8151" : ["DS", "XRayTubeCurrentInuA"], "9004" : ["CS", "ContentQualification"], "9005" : ["SH", "PulseSequenceName"], "9006" : ["SQ", "MRImagingModifierSequence"], "9008" : ["CS", "EchoPulseSequence"], "9009" : ["CS", "InversionRecovery"], "9010" : ["CS", "FlowCompensation"], "9011" : ["CS", "MultipleSpinEcho"], "9012" : ["CS", "MultiPlanarExcitation"], "9014" : ["CS", "PhaseContrast"], "9015" : ["CS", "TimeOfFlightContrast"], "9016" : ["CS", "Spoiling"], "9017" : ["CS", "SteadyStatePulseSequence"], "9018" : ["CS", "EchoPlanarPulseSequence"], "9019" : ["FD", "TagAngleFirstAxis"], "9020" : ["CS", "MagnetizationTransfer"], "9021" : ["CS", "T2Preparation"], "9022" : ["CS", "BloodSignalNulling"], "9024" : ["CS", "SaturationRecovery"], "9025" : ["CS", "SpectrallySelectedSuppression"], "9026" : ["CS", "SpectrallySelectedExcitation"], "9027" : ["CS", "SpatialPresaturation"], "9028" : ["CS", "Tagging"], "9029" : ["CS", "OversamplingPhase"], "9030" : ["FD", "TagSpacingFirstDimension"], "9032" : ["CS", "GeometryOfKSpaceTraversal"], "9033" : ["CS", "SegmentedKSpaceTraversal"], "9034" : ["CS", "RectilinearPhaseEncodeReordering"], "9035" : ["FD", "TagThickness"], "9036" : ["CS", "PartialFourierDirection"], "9037" : ["CS", "CardiacSynchronizationTechnique"], "9041" : ["LO", "ReceiveCoilManufacturerName"], "9042" : ["SQ", "MRReceiveCoilSequence"], "9043" : ["CS", "ReceiveCoilType"], "9044" : ["CS", "QuadratureReceiveCoil"], "9045" : ["SQ", "MultiCoilDefinitionSequence"], "9046" : ["LO", "MultiCoilConfiguration"], "9047" : ["SH", "MultiCoilElementName"], "9048" : ["CS", "MultiCoilElementUsed"], "9049" : ["SQ", "MRTransmitCoilSequence"], "9050" : ["LO", "TransmitCoilManufacturerName"], "9051" : ["CS", "TransmitCoilType"], "9052" : ["FD", "SpectralWidth"], "9053" : ["FD", "ChemicalShiftReference"], "9054" : ["CS", "VolumeLocalizationTechnique"], "9058" : ["US", "MRAcquisitionFrequencyEncodingSteps"], "9059" : ["CS", "Decoupling"], "9060" : ["CS", "DecoupledNucleus"], "9061" : ["FD", "DecouplingFrequency"], "9062" : ["CS", "DecouplingMethod"], "9063" : ["FD", "DecouplingChemicalShiftReference"], "9064" : ["CS", "KSpaceFiltering"], "9065" : ["CS", "TimeDomainFiltering"], "9066" : ["US", "NumberOfZeroFills"], "9067" : ["CS", "BaselineCorrection"], "9069" : ["FD", "ParallelReductionFactorInPlane"], "9070" : ["FD", "CardiacRRIntervalSpecified"], "9073" : ["FD", "AcquisitionDuration"], "9074" : ["DT", "FrameAcquisitionDateTime"], "9075" : ["CS", "DiffusionDirectionality"], "9076" : ["SQ", "DiffusionGradientDirectionSequence"], "9077" : ["CS", "ParallelAcquisition"], "9078" : ["CS", "ParallelAcquisitionTechnique"], "9079" : ["FD", "InversionTimes"], "9080" : ["ST", "MetaboliteMapDescription"], "9081" : ["CS", "PartialFourier"], "9082" : ["FD", "EffectiveEchoTime"], "9083" : ["SQ", "MetaboliteMapCodeSequence"], "9084" : ["SQ", "ChemicalShiftSequence"], "9085" : ["CS", "CardiacSignalSource"], "9087" : ["FD", "DiffusionBValue"], "9089" : ["FD", "DiffusionGradientOrientation"], "9090" : ["FD", "VelocityEncodingDirection"], "9091" : ["FD", "VelocityEncodingMinimumValue"], "9092" : ["SQ", "VelocityEncodingAcquisitionSequence"], "9093" : ["US", "NumberOfKSpaceTrajectories"], "9094" : ["CS", "CoverageOfKSpace"], "9095" : ["UL", "SpectroscopyAcquisitionPhaseRows"], "9096" : ["FD", "ParallelReductionFactorInPlaneRetired"], "9098" : ["FD", "TransmitterFrequency"], "9100" : ["CS", "ResonantNucleus"], "9101" : ["CS", "FrequencyCorrection"], "9103" : ["SQ", "MRSpectroscopyFOVGeometrySequence"], "9104" : ["FD", "SlabThickness"], "9105" : ["FD", "SlabOrientation"], "9106" : ["FD", "MidSlabPosition"], "9107" : ["SQ", "MRSpatialSaturationSequence"], "9112" : ["SQ", "MRTimingAndRelatedParametersSequence"], "9114" : ["SQ", "MREchoSequence"], "9115" : ["SQ", "MRModifierSequence"], "9117" : ["SQ", "MRDiffusionSequence"], "9118" : ["SQ", "CardiacSynchronizationSequence"], "9119" : ["SQ", "MRAveragesSequence"], "9125" : ["SQ", "MRFOVGeometrySequence"], "9126" : ["SQ", "VolumeLocalizationSequence"], "9127" : ["UL", "SpectroscopyAcquisitionDataColumns"], "9147" : ["CS", "DiffusionAnisotropyType"], "9151" : ["DT", "FrameReferenceDateTime"], "9152" : ["SQ", "MRMetaboliteMapSequence"], "9155" : ["FD", "ParallelReductionFactorOutOfPlane"], "9159" : ["UL", "SpectroscopyAcquisitionOutOfPlanePhaseSteps"], "9166" : ["CS", "BulkMotionStatus"], "9168" : ["FD", "ParallelReductionFactorSecondInPlane"], "9169" : ["CS", "CardiacBeatRejectionTechnique"], "9170" : ["CS", "RespiratoryMotionCompensationTechnique"], "9171" : ["CS", "RespiratorySignalSource"], "9172" : ["CS", "BulkMotionCompensationTechnique"], "9173" : ["CS", "BulkMotionSignalSource"], "9174" : ["CS", "ApplicableSafetyStandardAgency"], "9175" : ["LO", "ApplicableSafetyStandardDescription"], "9176" : ["SQ", "OperatingModeSequence"], "9177" : ["CS", "OperatingModeType"], "9178" : ["CS", "OperatingMode"], "9179" : ["CS", "SpecificAbsorptionRateDefinition"], "9180" : ["CS", "GradientOutputType"], "9181" : ["FD", "SpecificAbsorptionRateValue"], "9182" : ["FD", "GradientOutput"], "9183" : ["CS", "FlowCompensationDirection"], "9184" : ["FD", "TaggingDelay"], "9185" : ["ST", "RespiratoryMotionCompensationTechniqueDescription"], "9186" : ["SH", "RespiratorySignalSourceID"], "9195" : ["FD", "ChemicalShiftMinimumIntegrationLimitInHz"], "9196" : ["FD", "ChemicalShiftMaximumIntegrationLimitInHz"], "9197" : ["SQ", "MRVelocityEncodingSequence"], "9198" : ["CS", "FirstOrderPhaseCorrection"], "9199" : ["CS", "WaterReferencedPhaseCorrection"], "9200" : ["CS", "MRSpectroscopyAcquisitionType"], "9214" : ["CS", "RespiratoryCyclePosition"], "9217" : ["FD", "VelocityEncodingMaximumValue"], "9218" : ["FD", "TagSpacingSecondDimension"], "9219" : ["SS", "TagAngleSecondAxis"], "9220" : ["FD", "FrameAcquisitionDuration"], "9226" : ["SQ", "MRImageFrameTypeSequence"], "9227" : ["SQ", "MRSpectroscopyFrameTypeSequence"], "9231" : ["US", "MRAcquisitionPhaseEncodingStepsInPlane"], "9232" : ["US", "MRAcquisitionPhaseEncodingStepsOutOfPlane"], "9234" : ["UL", "SpectroscopyAcquisitionPhaseColumns"], "9236" : ["CS", "CardiacCyclePosition"], "9239" : ["SQ", "SpecificAbsorptionRateSequence"], "9240" : ["US", "RFEchoTrainLength"], "9241" : ["US", "GradientEchoTrainLength"], "9250" : ["CS", "ArterialSpinLabelingContrast"], "9251" : ["SQ", "MRArterialSpinLabelingSequence"], "9252" : ["LO", "ASLTechniqueDescription"], "9253" : ["US", "ASLSlabNumber"], "9254" : ["FD ", "ASLSlabThickness"], "9255" : ["FD ", "ASLSlabOrientation"], "9256" : ["FD ", "ASLMidSlabPosition"], "9257" : ["CS", "ASLContext"], "9258" : ["UL", "ASLPulseTrainDuration"], "9259" : ["CS", "ASLCrusherFlag"], "925A" : ["FD", "ASLCrusherFlow"], "925B" : ["LO", "ASLCrusherDescription"], "925C" : ["CS", "ASLBolusCutoffFlag"], "925D" : ["SQ", "ASLBolusCutoffTimingSequence"], "925E" : ["LO", "ASLBolusCutoffTechnique"], "925F" : ["UL", "ASLBolusCutoffDelayTime"], "9260" : ["SQ", "ASLSlabSequence"], "9295" : ["FD", "ChemicalShiftMinimumIntegrationLimitInppm"], "9296" : ["FD", "ChemicalShiftMaximumIntegrationLimitInppm"], "9301" : ["SQ", "CTAcquisitionTypeSequence"], "9302" : ["CS", "AcquisitionType"], "9303" : ["FD", "TubeAngle"], "9304" : ["SQ", "CTAcquisitionDetailsSequence"], "9305" : ["FD", "RevolutionTime"], "9306" : ["FD", "SingleCollimationWidth"], "9307" : ["FD", "TotalCollimationWidth"], "9308" : ["SQ", "CTTableDynamicsSequence"], "9309" : ["FD", "TableSpeed"], "9310" : ["FD", "TableFeedPerRotation"], "9311" : ["FD", "SpiralPitchFactor"], "9312" : ["SQ", "CTGeometrySequence"], "9313" : ["FD", "DataCollectionCenterPatient"], "9314" : ["SQ", "CTReconstructionSequence"], "9315" : ["CS", "ReconstructionAlgorithm"], "9316" : ["CS", "ConvolutionKernelGroup"], "9317" : ["FD", "ReconstructionFieldOfView"], "9318" : ["FD", "ReconstructionTargetCenterPatient"], "9319" : ["FD", "ReconstructionAngle"], "9320" : ["SH", "ImageFilter"], "9321" : ["SQ", "CTExposureSequence"], "9322" : ["FD", "ReconstructionPixelSpacing"], "9323" : ["CS", "ExposureModulationType"], "9324" : ["FD", "EstimatedDoseSaving"], "9325" : ["SQ", "CTXRayDetailsSequence"], "9326" : ["SQ", "CTPositionSequence"], "9327" : ["FD", "TablePosition"], "9328" : ["FD", "ExposureTimeInms"], "9329" : ["SQ", "CTImageFrameTypeSequence"], "9330" : ["FD", "XRayTubeCurrentInmA"], "9332" : ["FD", "ExposureInmAs"], "9333" : ["CS", "ConstantVolumeFlag"], "9334" : ["CS", "FluoroscopyFlag"], "9335" : ["FD", "DistanceSourceToDataCollectionCenter"], "9337" : ["US", "ContrastBolusAgentNumber"], "9338" : ["SQ", "ContrastBolusIngredientCodeSequence"], "9340" : ["SQ", "ContrastAdministrationProfileSequence"], "9341" : ["SQ", "ContrastBolusUsageSequence"], "9342" : ["CS", "ContrastBolusAgentAdministered"], "9343" : ["CS", "ContrastBolusAgentDetected"], "9344" : ["CS", "ContrastBolusAgentPhase"], "9345" : ["FD", "CTDIvol"], "9346" : ["SQ", "CTDIPhantomTypeCodeSequence"], "9351" : ["FL", "CalciumScoringMassFactorPatient"], "9352" : ["FL", "CalciumScoringMassFactorDevice"], "9353" : ["FL", "EnergyWeightingFactor"], "9360" : ["SQ", "CTAdditionalXRaySourceSequence"], "9401" : ["SQ", "ProjectionPixelCalibrationSequence"], "9402" : ["FL", "DistanceSourceToIsocenter"], "9403" : ["FL", "DistanceObjectToTableTop"], "9404" : ["FL", "ObjectPixelSpacingInCenterOfBeam"], "9405" : ["SQ", "PositionerPositionSequence"], "9406" : ["SQ", "TablePositionSequence"], "9407" : ["SQ", "CollimatorShapeSequence"], "9410" : ["CS", "PlanesInAcquisition"], "9412" : ["SQ", "XAXRFFrameCharacteristicsSequence"], "9417" : ["SQ", "FrameAcquisitionSequence"], "9420" : ["CS", "XRayReceptorType"], "9423" : ["LO", "AcquisitionProtocolName"], "9424" : ["LT", "AcquisitionProtocolDescription"], "9425" : ["CS", "ContrastBolusIngredientOpaque"], "9426" : ["FL", "DistanceReceptorPlaneToDetectorHousing"], "9427" : ["CS", "IntensifierActiveShape"], "9428" : ["FL", "IntensifierActiveDimensions"], "9429" : ["FL", "PhysicalDetectorSize"], "9430" : ["FL", "PositionOfIsocenterProjection"], "9432" : ["SQ", "FieldOfViewSequence"], "9433" : ["LO", "FieldOfViewDescription"], "9434" : ["SQ", "ExposureControlSensingRegionsSequence"], "9435" : ["CS", "ExposureControlSensingRegionShape"], "9436" : ["SS", "ExposureControlSensingRegionLeftVerticalEdge"], "9437" : ["SS", "ExposureControlSensingRegionRightVerticalEdge"], "9438" : ["SS", "ExposureControlSensingRegionUpperHorizontalEdge"], "9439" : ["SS", "ExposureControlSensingRegionLowerHorizontalEdge"], "9440" : ["SS", "CenterOfCircularExposureControlSensingRegion"], "9441" : ["US", "RadiusOfCircularExposureControlSensingRegion"], "9442" : ["SS", "VerticesOfThePolygonalExposureControlSensingRegion"], "9447" : ["FL", "ColumnAngulationPatient"], "9449" : ["FL", "BeamAngle"], "9451" : ["SQ", "FrameDetectorParametersSequence"], "9452" : ["FL", "CalculatedAnatomyThickness"], "9455" : ["SQ", "CalibrationSequence"], "9456" : ["SQ", "ObjectThicknessSequence"], "9457" : ["CS", "PlaneIdentification"], "9461" : ["FL", "FieldOfViewDimensionsInFloat"], "9462" : ["SQ", "IsocenterReferenceSystemSequence"], "9463" : ["FL", "PositionerIsocenterPrimaryAngle"], "9464" : ["FL", "PositionerIsocenterSecondaryAngle"], "9465" : ["FL", "PositionerIsocenterDetectorRotationAngle"], "9466" : ["FL", "TableXPositionToIsocenter"], "9467" : ["FL", "TableYPositionToIsocenter"], "9468" : ["FL", "TableZPositionToIsocenter"], "9469" : ["FL", "TableHorizontalRotationAngle"], "9470" : ["FL", "TableHeadTiltAngle"], "9471" : ["FL", "TableCradleTiltAngle"], "9472" : ["SQ", "FrameDisplayShutterSequence"], "9473" : ["FL", "AcquiredImageAreaDoseProduct"], "9474" : ["CS", "CArmPositionerTabletopRelationship"], "9476" : ["SQ", "XRayGeometrySequence"], "9477" : ["SQ", "IrradiationEventIdentificationSequence"], "9504" : ["SQ", "XRay3DFrameTypeSequence"], "9506" : ["SQ", "ContributingSourcesSequence"], "9507" : ["SQ", "XRay3DAcquisitionSequence"], "9508" : ["FL", "PrimaryPositionerScanArc"], "9509" : ["FL", "SecondaryPositionerScanArc"], "9510" : ["FL ", "PrimaryPositionerScanStartAngle"], "9511" : ["FL", "SecondaryPositionerScanStartAngle"], "9514" : ["FL", "PrimaryPositionerIncrement"], "9515" : ["FL", "SecondaryPositionerIncrement"], "9516" : ["DT", "StartAcquisitionDateTime"], "9517" : ["DT", "EndAcquisitionDateTime"], "9524" : ["LO", "ApplicationName"], "9525" : ["LO", "ApplicationVersion"], "9526" : ["LO", "ApplicationManufacturer"], "9527" : ["CS", "AlgorithmType"], "9528" : ["LO", "AlgorithmDescription"], "9530" : ["SQ", "XRay3DReconstructionSequence"], "9531" : ["LO", "ReconstructionDescription"], "9538" : ["SQ", "PerProjectionAcquisitionSequence"], "9601" : ["SQ", "DiffusionBMatrixSequence"], "9602" : ["FD", "DiffusionBValueXX"], "9603" : ["FD", "DiffusionBValueXY"], "9604" : ["FD", "DiffusionBValueXZ"], "9605" : ["FD", "DiffusionBValueYY"], "9606" : ["FD", "DiffusionBValueYZ"], "9607" : ["FD", "DiffusionBValueZZ"], "9701" : ["DT", "DecayCorrectionDateTime"], "9715" : ["FD", "StartDensityThreshold"], "9716" : ["FD", "StartRelativeDensityDifferenceThreshold"], "9717" : ["FD", "StartCardiacTriggerCountThreshold"], "9718" : ["FD", "StartRespiratoryTriggerCountThreshold"], "9719" : ["FD", "TerminationCountsThreshold"], "9720" : ["FD", "TerminationDensityThreshold"], "9721" : ["FD", "TerminationRelativeDensityThreshold"], "9722" : ["FD", "TerminationTimeThreshold"], "9723" : ["FD", "TerminationCardiacTriggerCountThreshold"], "9724" : ["FD", "TerminationRespiratoryTriggerCountThreshold"], "9725" : ["CS", "DetectorGeometry"], "9726" : ["FD", "TransverseDetectorSeparation"], "9727" : ["FD", "AxialDetectorDimension"], "9729" : ["US", "RadiopharmaceuticalAgentNumber"], "9732" : ["SQ", "PETFrameAcquisitionSequence"], "9733" : ["SQ", "PETDetectorMotionDetailsSequence"], "9734" : ["SQ", "PETTableDynamicsSequence"], "9735" : ["SQ", "PETPositionSequence"], "9736" : ["SQ", "PETFrameCorrectionFactorsSequence"], "9737" : ["SQ", "RadiopharmaceuticalUsageSequence"], "9738" : ["CS", "AttenuationCorrectionSource"], "9739" : ["US", "NumberOfIterations"], "9740" : ["US", "NumberOfSubsets"], "9749" : ["SQ", "PETReconstructionSequence"], "9751" : ["SQ", "PETFrameTypeSequence"], "9755" : ["CS", "TimeOfFlightInformationUsed"], "9756" : ["CS", "ReconstructionType"], "9758" : ["CS", "DecayCorrected"], "9759" : ["CS", "AttenuationCorrected"], "9760" : ["CS", "ScatterCorrected"], "9761" : ["CS", "DeadTimeCorrected"], "9762" : ["CS", "GantryMotionCorrected"], "9763" : ["CS", "PatientMotionCorrected"], "9764" : ["CS", "CountLossNormalizationCorrected"], "9765" : ["CS", "RandomsCorrected"], "9766" : ["CS", "NonUniformRadialSamplingCorrected"], "9767" : ["CS", "SensitivityCalibrated"], "9768" : ["CS", "DetectorNormalizationCorrection"], "9769" : ["CS", "IterativeReconstructionMethod"], "9770" : ["CS", "AttenuationCorrectionTemporalRelationship"], "9771" : ["SQ", "PatientPhysiologicalStateSequence"], "9772" : ["SQ", "PatientPhysiologicalStateCodeSequence"], "9801" : ["FD", "DepthsOfFocus"], "9803" : ["SQ", "ExcludedIntervalsSequence"], "9804" : ["DT", "ExclusionStartDatetime"], "9805" : ["FD", "ExclusionDuration"], "9806" : ["SQ", "USImageDescriptionSequence"], "9807" : ["SQ", "ImageDataTypeSequence"], "9808" : ["CS", "DataType"], "9809" : ["SQ", "TransducerScanPatternCodeSequence"], "980B" : ["CS", "AliasedDataType"], "980C" : ["CS", "PositionMeasuringDeviceUsed"], "980D" : ["SQ", "TransducerGeometryCodeSequence"], "980E" : ["SQ", "TransducerBeamSteeringCodeSequence"], "980F" : ["SQ", "TransducerApplicationCodeSequence"], "A001" : ["SQ", "ContributingEquipmentSequence"], "A002" : ["DT", "ContributionDateTime"], "A003" : ["ST", "ContributionDescription"] }, "0020" : { "000D" : ["UI", "StudyInstanceUID"], "000E" : ["UI", "SeriesInstanceUID"], "0010" : ["SH", "StudyID"], "0011" : ["IS", "SeriesNumber"], "0012" : ["IS", "AcquisitionNumber"], "0013" : ["IS", "InstanceNumber"], "0014" : ["IS", "IsotopeNumber"], "0015" : ["IS", "PhaseNumber"], "0016" : ["IS", "IntervalNumber"], "0017" : ["IS", "TimeSlotNumber"], "0018" : ["IS", "AngleNumber"], "0019" : ["IS", "ItemNumber"], "0020" : ["CS", "PatientOrientation"], "0022" : ["IS", "OverlayNumber"], "0024" : ["IS", "CurveNumber"], "0026" : ["IS", "LUTNumber"], "0030" : ["DS", "ImagePosition"], "0032" : ["DS", "ImagePositionPatient"], "0035" : ["DS", "ImageOrientation"], "0037" : ["DS", "ImageOrientationPatient"], "0050" : ["DS", "Location"], "0052" : ["UI", "FrameOfReferenceUID"], "0060" : ["CS", "Laterality"], "0062" : ["CS", "ImageLaterality"], "0070" : ["LO", "ImageGeometryType"], "0080" : ["CS", "MaskingImage"], "00AA" : ["IS", "ReportNumber"], "0100" : ["IS", "TemporalPositionIdentifier"], "0105" : ["IS", "NumberOfTemporalPositions"], "0110" : ["DS", "TemporalResolution"], "0200" : ["UI", "SynchronizationFrameOfReferenceUID"], "0242" : ["UI", "SOPInstanceUIDOfConcatenationSource"], "1000" : ["IS", "SeriesInStudy"], "1001" : ["IS", "AcquisitionsInSeries"], "1002" : ["IS", "ImagesInAcquisition"], "1003" : ["IS", "ImagesInSeries"], "1004" : ["IS", "AcquisitionsInStudy"], "1005" : ["IS", "ImagesInStudy"], "1020" : ["LO", "Reference"], "1040" : ["LO", "PositionReferenceIndicator"], "1041" : ["DS", "SliceLocation"], "1070" : ["IS", "OtherStudyNumbers"], "1200" : ["IS", "NumberOfPatientRelatedStudies"], "1202" : ["IS", "NumberOfPatientRelatedSeries"], "1204" : ["IS", "NumberOfPatientRelatedInstances"], "1206" : ["IS", "NumberOfStudyRelatedSeries"], "1208" : ["IS", "NumberOfStudyRelatedInstances"], "1209" : ["IS", "NumberOfSeriesRelatedInstances"], "3401" : ["CS", "ModifyingDeviceID"], "3402" : ["CS", "ModifiedImageID"], "3403" : ["DA", "ModifiedImageDate"], "3404" : ["LO", "ModifyingDeviceManufacturer"], "3405" : ["TM", "ModifiedImageTime"], "3406" : ["LO", "ModifiedImageDescription"], "4000" : ["LT", "ImageComments"], "5000" : ["AT", "OriginalImageIdentification"], "5002" : ["LO", "OriginalImageIdentificationNomenclature"], "9056" : ["SH", "StackID"], "9057" : ["UL", "InStackPositionNumber"], "9071" : ["SQ", "FrameAnatomySequence"], "9072" : ["CS", "FrameLaterality"], "9111" : ["SQ", "FrameContentSequence"], "9113" : ["SQ", "PlanePositionSequence"], "9116" : ["SQ", "PlaneOrientationSequence"], "9128" : ["UL", "TemporalPositionIndex"], "9153" : ["FD", "NominalCardiacTriggerDelayTime"], "9154" : ["FL", "NominalCardiacTriggerTimePriorToRPeak"], "9155" : ["FL", "ActualCardiacTriggerTimePriorToRPeak"], "9156" : ["US", "FrameAcquisitionNumber"], "9157" : ["UL", "DimensionIndexValues"], "9158" : ["LT", "FrameComments"], "9161" : ["UI", "ConcatenationUID"], "9162" : ["US", "InConcatenationNumber"], "9163" : ["US", "InConcatenationTotalNumber"], "9164" : ["UI", "DimensionOrganizationUID"], "9165" : ["AT", "DimensionIndexPointer"], "9167" : ["AT", "FunctionalGroupPointer"], "9213" : ["LO", "DimensionIndexPrivateCreator"], "9221" : ["SQ", "DimensionOrganizationSequence"], "9222" : ["SQ", "DimensionIndexSequence"], "9228" : ["UL", "ConcatenationFrameOffsetNumber"], "9238" : ["LO", "FunctionalGroupPrivateCreator"], "9241" : ["FL", "NominalPercentageOfCardiacPhase"], "9245" : ["FL", "NominalPercentageOfRespiratoryPhase"], "9246" : ["FL", "StartingRespiratoryAmplitude"], "9247" : ["CS", "StartingRespiratoryPhase"], "9248" : ["FL", "EndingRespiratoryAmplitude"], "9249" : ["CS", "EndingRespiratoryPhase"], "9250" : ["CS", "RespiratoryTriggerType"], "9251" : ["FD", "RRIntervalTimeNominal"], "9252" : ["FD", "ActualCardiacTriggerDelayTime"], "9253" : ["SQ", "RespiratorySynchronizationSequence"], "9254" : ["FD", "RespiratoryIntervalTime"], "9255" : ["FD", "NominalRespiratoryTriggerDelayTime"], "9256" : ["FD", "RespiratoryTriggerDelayThreshold"], "9257" : ["FD", "ActualRespiratoryTriggerDelayTime"], "9301" : ["FD", "ImagePositionVolume"], "9302" : ["FD", "ImageOrientationVolume"], "9307" : ["CS", "UltrasoundAcquisitionGeometry"], "9308" : ["FD", "ApexPosition"], "9309" : ["FD", "VolumeToTransducerMappingMatrix"], "930A" : ["FD", "VolumeToTableMappingMatrix"], "930C" : ["CS", "PatientFrameOfReferenceSource"], "930D" : ["FD", "TemporalPositionTimeOffset"], "930E" : ["SQ", "PlanePositionVolumeSequence"], "930F" : ["SQ", "PlaneOrientationVolumeSequence"], "9310" : ["SQ", "TemporalPositionSequence"], "9311" : ["CS", "DimensionOrganizationType"], "9312" : ["UI", "VolumeFrameOfReferenceUID"], "9313" : ["UI", "TableFrameOfReferenceUID"], "9421" : ["LO", "DimensionDescriptionLabel"], "9450" : ["SQ", "PatientOrientationInFrameSequence"], "9453" : ["LO", "FrameLabel"], "9518" : ["US", "AcquisitionIndex"], "9529" : ["SQ", "ContributingSOPInstancesReferenceSequence"], "9536" : ["US", "ReconstructionIndex"] }, "0022" : { "0001" : ["US", "LightPathFilterPassThroughWavelength"], "0002" : ["US", "LightPathFilterPassBand"], "0003" : ["US", "ImagePathFilterPassThroughWavelength"], "0004" : ["US", "ImagePathFilterPassBand"], "0005" : ["CS", "PatientEyeMovementCommanded"], "0006" : ["SQ", "PatientEyeMovementCommandCodeSequence"], "0007" : ["FL", "SphericalLensPower"], "0008" : ["FL", "CylinderLensPower"], "0009" : ["FL", "CylinderAxis"], "000A" : ["FL", "EmmetropicMagnification"], "000B" : ["FL", "IntraOcularPressure"], "000C" : ["FL", "HorizontalFieldOfView"], "000D" : ["CS", "PupilDilated"], "000E" : ["FL", "DegreeOfDilation"], "0010" : ["FL", "StereoBaselineAngle"], "0011" : ["FL", "StereoBaselineDisplacement"], "0012" : ["FL", "StereoHorizontalPixelOffset"], "0013" : ["FL", "StereoVerticalPixelOffset"], "0014" : ["FL", "StereoRotation"], "0015" : ["SQ", "AcquisitionDeviceTypeCodeSequence"], "0016" : ["SQ", "IlluminationTypeCodeSequence"], "0017" : ["SQ", "LightPathFilterTypeStackCodeSequence"], "0018" : ["SQ", "ImagePathFilterTypeStackCodeSequence"], "0019" : ["SQ", "LensesCodeSequence"], "001A" : ["SQ", "ChannelDescriptionCodeSequence"], "001B" : ["SQ", "RefractiveStateSequence"], "001C" : ["SQ", "MydriaticAgentCodeSequence"], "001D" : ["SQ", "RelativeImagePositionCodeSequence"], "001E" : ["FL", "CameraAngleOfView"], "0020" : ["SQ", "StereoPairsSequence"], "0021" : ["SQ", "LeftImageSequence"], "0022" : ["SQ", "RightImageSequence"], "0030" : ["FL", "AxialLengthOfTheEye"], "0031" : ["SQ", "OphthalmicFrameLocationSequence"], "0032" : ["FL", "ReferenceCoordinates"], "0035" : ["FL", "DepthSpatialResolution"], "0036" : ["FL", "MaximumDepthDistortion"], "0037" : ["FL", "AlongScanSpatialResolution"], "0038" : ["FL", "MaximumAlongScanDistortion"], "0039" : ["CS", "OphthalmicImageOrientation"], "0041" : ["FL", "DepthOfTransverseImage"], "0042" : ["SQ", "MydriaticAgentConcentrationUnitsSequence"], "0048" : ["FL", "AcrossScanSpatialResolution"], "0049" : ["FL", "MaximumAcrossScanDistortion"], "004E" : ["DS", "MydriaticAgentConcentration"], "0055" : ["FL", "IlluminationWaveLength"], "0056" : ["FL", "IlluminationPower"], "0057" : ["FL", "IlluminationBandwidth"], "0058" : ["SQ", "MydriaticAgentSequence"], "1007" : ["SQ", "OphthalmicAxialMeasurementsRightEyeSequence"], "1008" : ["SQ", "OphthalmicAxialMeasurementsLeftEyeSequence"], "1010" : ["CS", "OphthalmicAxialLengthMeasurementsType"], "1019" : ["FL", "OphthalmicAxialLength"], "1024" : ["SQ", "LensStatusCodeSequence"], "1025" : ["SQ", "VitreousStatusCodeSequence"], "1028" : ["SQ", "IOLFormulaCodeSequence"], "1029" : ["LO", "IOLFormulaDetail"], "1033" : ["FL", "KeratometerIndex"], "1035" : ["SQ", "SourceOfOphthalmicAxialLengthCodeSequence"], "1037" : ["FL", "TargetRefraction"], "1039" : ["CS", "RefractiveProcedureOccurred"], "1040" : ["SQ", "RefractiveSurgeryTypeCodeSequence"], "1044" : ["SQ", "OphthalmicUltrasoundAxialMeasurementsTypeCodeSequence"], "1050" : ["SQ", "OphthalmicAxialLengthMeasurementsSequence"], "1053" : ["FL", "IOLPower"], "1054" : ["FL", "PredictedRefractiveError"], "1059" : ["FL", "OphthalmicAxialLengthVelocity"], "1065" : ["LO", "LensStatusDescription"], "1066" : ["LO", "VitreousStatusDescription"], "1090" : ["SQ", "IOLPowerSequence"], "1092" : ["SQ", "LensConstantSequence"], "1093" : ["LO", "IOLManufacturer"], "1094" : ["LO", "LensConstantDescription"], "1096" : ["SQ", "KeratometryMeasurementTypeCodeSequence"], "1100" : ["SQ", "ReferencedOphthalmicAxialMeasurementsSequence"], "1101" : ["SQ", "OphthalmicAxialLengthMeasurementsSegmentNameCodeSequence"], "1103" : ["SQ", "RefractiveErrorBeforeRefractiveSurgeryCodeSequence"], "1121" : ["FL", "IOLPowerForExactEmmetropia"], "1122" : ["FL", "IOLPowerForExactTargetRefraction"], "1125" : ["SQ", "AnteriorChamberDepthDefinitionCodeSequence"], "1130" : ["FL", "LensThickness"], "1131" : ["FL", "AnteriorChamberDepth"], "1132" : ["SQ", "SourceOfLensThicknessDataCodeSequence"], "1133" : ["SQ", "SourceOfAnteriorChamberDepthDataCodeSequence"], "1135" : ["SQ", "SourceOfRefractiveErrorDataCodeSequence"], "1140" : ["CS", "OphthalmicAxialLengthMeasurementModified"], "1150" : ["SQ", "OphthalmicAxialLengthDataSourceCodeSequence"], "1153" : ["SQ", "OphthalmicAxialLengthAcquisitionMethodCodeSequence"], "1155" : ["FL", "SignalToNoiseRatio"], "1159" : ["LO", "OphthalmicAxialLengthDataSourceDescription"], "1210" : ["SQ", "OphthalmicAxialLengthMeasurementsTotalLengthSequence"], "1211" : ["SQ", "OphthalmicAxialLengthMeasurementsSegmentalLengthSequence"], "1212" : ["SQ", "OphthalmicAxialLengthMeasurementsLengthSummationSequence"], "1220" : ["SQ", "UltrasoundOphthalmicAxialLengthMeasurementsSequence"], "1225" : ["SQ", "OpticalOphthalmicAxialLengthMeasurementsSequence"], "1230" : ["SQ", "UltrasoundSelectedOphthalmicAxialLengthSequence"], "1250" : ["SQ", "OphthalmicAxialLengthSelectionMethodCodeSequence"], "1255" : ["SQ", "OpticalSelectedOphthalmicAxialLengthSequence"], "1257" : ["SQ", "SelectedSegmentalOphthalmicAxialLengthSequence"], "1260" : ["SQ", "SelectedTotalOphthalmicAxialLengthSequence"], "1262" : ["SQ", "OphthalmicAxialLengthQualityMetricSequence"], "1273" : ["LO", "OphthalmicAxialLengthQualityMetricTypeDescription"], "1300" : ["SQ", "IntraocularLensCalculationsRightEyeSequence"], "1310" : ["SQ", "IntraocularLensCalculationsLeftEyeSequence"], "1330" : ["SQ", "ReferencedOphthalmicAxialLengthMeasurementQCImageSequence"] }, "0024" : { "0010" : ["FL", "VisualFieldHorizontalExtent"], "0011" : ["FL", "VisualFieldVerticalExtent"], "0012" : ["CS", "VisualFieldShape"], "0016" : ["SQ", "ScreeningTestModeCodeSequence"], "0018" : ["FL", "MaximumStimulusLuminance"], "0020" : ["FL", "BackgroundLuminance"], "0021" : ["SQ", "StimulusColorCodeSequence"], "0024" : ["SQ", "BackgroundIlluminationColorCodeSequence"], "0025" : ["FL", "StimulusArea"], "0028" : ["FL", "StimulusPresentationTime"], "0032" : ["SQ", "FixationSequence"], "0033" : ["SQ", "FixationMonitoringCodeSequence"], "0034" : ["SQ", "VisualFieldCatchTrialSequence"], "0035" : ["US", "FixationCheckedQuantity"], "0036" : ["US", "PatientNotProperlyFixatedQuantity"], "0037" : ["CS", "PresentedVisualStimuliDataFlag"], "0038" : ["US", "NumberOfVisualStimuli"], "0039" : ["CS", "ExcessiveFixationLossesDataFlag"], "0040" : ["CS", "ExcessiveFixationLosses"], "0042" : ["US", "StimuliRetestingQuantity"], "0044" : ["LT", "CommentsOnPatientPerformanceOfVisualField"], "0045" : ["CS", "FalseNegativesEstimateFlag"], "0046" : ["FL", "FalseNegativesEstimate"], "0048" : ["US", "NegativeCatchTrialsQuantity"], "0050" : ["US", "FalseNegativesQuantity"], "0051" : ["CS", "ExcessiveFalseNegativesDataFlag"], "0052" : ["CS", "ExcessiveFalseNegatives"], "0053" : ["CS", "FalsePositivesEstimateFlag"], "0054" : ["FL", "FalsePositivesEstimate"], "0055" : ["CS", "CatchTrialsDataFlag"], "0056" : ["US", "PositiveCatchTrialsQuantity"], "0057" : ["CS", "TestPointNormalsDataFlag"], "0058" : ["SQ", "TestPointNormalsSequence"], "0059" : ["CS", "GlobalDeviationProbabilityNormalsFlag"], "0060" : ["US", "FalsePositivesQuantity"], "0061" : ["CS", "ExcessiveFalsePositivesDataFlag"], "0062" : ["CS", "ExcessiveFalsePositives"], "0063" : ["CS", "VisualFieldTestNormalsFlag"], "0064" : ["SQ", "ResultsNormalsSequence"], "0065" : ["SQ", "AgeCorrectedSensitivityDeviationAlgorithmSequence"], "0066" : ["FL", "GlobalDeviationFromNormal"], "0067" : ["SQ", "GeneralizedDefectSensitivityDeviationAlgorithmSequence"], "0068" : ["FL", "LocalizedDeviationfromNormal"], "0069" : ["LO", "PatientReliabilityIndicator"], "0070" : ["FL", "VisualFieldMeanSensitivity"], "0071" : ["FL", "GlobalDeviationProbability"], "0072" : ["CS", "LocalDeviationProbabilityNormalsFlag"], "0073" : ["FL", "LocalizedDeviationProbability"], "0074" : ["CS", "ShortTermFluctuationCalculated"], "0075" : ["FL", "ShortTermFluctuation"], "0076" : ["CS", "ShortTermFluctuationProbabilityCalculated"], "0077" : ["FL", "ShortTermFluctuationProbability"], "0078" : ["CS", "CorrectedLocalizedDeviationFromNormalCalculated"], "0079" : ["FL", "CorrectedLocalizedDeviationFromNormal"], "0080" : ["CS", "CorrectedLocalizedDeviationFromNormalProbabilityCalculated"], "0081" : ["FL", "CorrectedLocalizedDeviationFromNormalProbability"], "0083" : ["SQ", "GlobalDeviationProbabilitySequence"], "0085" : ["SQ", "LocalizedDeviationProbabilitySequence"], "0086" : ["CS", "FovealSensitivityMeasured"], "0087" : ["FL", "FovealSensitivity"], "0088" : ["FL", "VisualFieldTestDuration"], "0089" : ["SQ", "VisualFieldTestPointSequence"], "0090" : ["FL", "VisualFieldTestPointXCoordinate"], "0091" : ["FL", "VisualFieldTestPointYCoordinate"], "0092" : ["FL", "AgeCorrectedSensitivityDeviationValue"], "0093" : ["CS", "StimulusResults"], "0094" : ["FL", "SensitivityValue"], "0095" : ["CS", "RetestStimulusSeen"], "0096" : ["FL", "RetestSensitivityValue"], "0097" : ["SQ", "VisualFieldTestPointNormalsSequence"], "0098" : ["FL", "QuantifiedDefect"], "0100" : ["FL", "AgeCorrectedSensitivityDeviationProbabilityValue"], "0102" : ["CS", "GeneralizedDefectCorrectedSensitivityDeviationFlag "], "0103" : ["FL", "GeneralizedDefectCorrectedSensitivityDeviationValue "], "0104" : ["FL", "GeneralizedDefectCorrectedSensitivityDeviationProbabilityValue"], "0105" : ["FL ", "MinimumSensitivityValue"], "0106" : ["CS", "BlindSpotLocalized"], "0107" : ["FL", "BlindSpotXCoordinate"], "0108" : ["FL", "BlindSpotYCoordinate "], "0110" : ["SQ", "VisualAcuityMeasurementSequence"], "0112" : ["SQ", "RefractiveParametersUsedOnPatientSequence"], "0113" : ["CS", "MeasurementLaterality"], "0114" : ["SQ", "OphthalmicPatientClinicalInformationLeftEyeSequence"], "0115" : ["SQ", "OphthalmicPatientClinicalInformationRightEyeSequence"], "0117" : ["CS", "FovealPointNormativeDataFlag"], "0118" : ["FL", "FovealPointProbabilityValue"], "0120" : ["CS", "ScreeningBaselineMeasured"], "0122" : ["SQ", "ScreeningBaselineMeasuredSequence"], "0124" : ["CS", "ScreeningBaselineType"], "0126" : ["FL", "ScreeningBaselineValue"], "0202" : ["LO", "AlgorithmSource"], "0306" : ["LO", "DataSetName"], "0307" : ["LO", "DataSetVersion"], "0308" : ["LO", "DataSetSource"], "0309" : ["LO", "DataSetDescription"], "0317" : ["SQ", "VisualFieldTestReliabilityGlobalIndexSequence"], "0320" : ["SQ", "VisualFieldGlobalResultsIndexSequence"], "0325" : ["SQ", "DataObservationSequence"], "0338" : ["CS", "IndexNormalsFlag"], "0341" : ["FL", "IndexProbability"], "0344" : ["SQ", "IndexProbabilitySequence"] }, "0028" : { "0002" : ["US", "SamplesPerPixel"], "0003" : ["US", "SamplesPerPixelUsed"], "0004" : ["CS", "PhotometricInterpretation"], "0005" : ["US", "ImageDimensions"], "0006" : ["US", "PlanarConfiguration"], "0008" : ["IS", "NumberOfFrames"], "0009" : ["AT", "FrameIncrementPointer"], "000A" : ["AT", "FrameDimensionPointer"], "0010" : ["US", "Rows"], "0011" : ["US", "Columns"], "0012" : ["US", "Planes"], "0014" : ["US", "UltrasoundColorDataPresent"], "0030" : ["DS", "PixelSpacing"], "0031" : ["DS", "ZoomFactor"], "0032" : ["DS", "ZoomCenter"], "0034" : ["IS", "PixelAspectRatio"], "0040" : ["CS", "ImageFormat"], "0050" : ["LO", "ManipulatedImage"], "0051" : ["CS", "CorrectedImage"], "005F" : ["LO", "CompressionRecognitionCode"], "0060" : ["CS", "CompressionCode"], "0061" : ["SH", "CompressionOriginator"], "0062" : ["LO", "CompressionLabel"], "0063" : ["SH", "CompressionDescription"], "0065" : ["CS", "CompressionSequence"], "0066" : ["AT", "CompressionStepPointers"], "0068" : ["US", "RepeatInterval"], "0069" : ["US", "BitsGrouped"], "0070" : ["US", "PerimeterTable"], "0071" : ["SS", "PerimeterValue"], "0080" : ["US", "PredictorRows"], "0081" : ["US", "PredictorColumns"], "0082" : ["US", "PredictorConstants"], "0090" : ["CS", "BlockedPixels"], "0091" : ["US", "BlockRows"], "0092" : ["US", "BlockColumns"], "0093" : ["US", "RowOverlap"], "0094" : ["US", "ColumnOverlap"], "0100" : ["US", "BitsAllocated"], "0101" : ["US", "BitsStored"], "0102" : ["US", "HighBit"], "0103" : ["US", "PixelRepresentation"], "0104" : ["SS", "SmallestValidPixelValue"], "0105" : ["SS", "LargestValidPixelValue"], "0106" : ["SS", "SmallestImagePixelValue"], "0107" : ["SS", "LargestImagePixelValue"], "0108" : ["SS", "SmallestPixelValueInSeries"], "0109" : ["SS", "LargestPixelValueInSeries"], "0110" : ["SS", "SmallestImagePixelValueInPlane"], "0111" : ["SS", "LargestImagePixelValueInPlane"], "0120" : ["SS", "PixelPaddingValue"], "0121" : ["SS", "PixelPaddingRangeLimit"], "0200" : ["US", "ImageLocation"], "0300" : ["CS", "QualityControlImage"], "0301" : ["CS", "BurnedInAnnotation"], "0302" : ["CS", "RecognizableVisualFeatures"], "0303" : ["CS", "LongitudinalTemporalInformationModified"], "0400" : ["LO", "TransformLabel"], "0401" : ["LO", "TransformVersionNumber"], "0402" : ["US", "NumberOfTransformSteps"], "0403" : ["LO", "SequenceOfCompressedData"], "0404" : ["AT", "DetailsOfCoefficients"], "0700" : ["LO", "DCTLabel"], "0701" : ["CS", "DataBlockDescription"], "0702" : ["AT", "DataBlock"], "0710" : ["US", "NormalizationFactorFormat"], "0720" : ["US", "ZonalMapNumberFormat"], "0721" : ["AT", "ZonalMapLocation"], "0722" : ["US", "ZonalMapFormat"], "0730" : ["US", "AdaptiveMapFormat"], "0740" : ["US", "CodeNumberFormat"], "0A02" : ["CS", "PixelSpacingCalibrationType"], "0A04" : ["LO", "PixelSpacingCalibrationDescription"], "1040" : ["CS", "PixelIntensityRelationship"], "1041" : ["SS", "PixelIntensityRelationshipSign"], "1050" : ["DS", "WindowCenter"], "1051" : ["DS", "WindowWidth"], "1052" : ["DS", "RescaleIntercept"], "1053" : ["DS", "RescaleSlope"], "1054" : ["LO", "RescaleType"], "1055" : ["LO", "WindowCenterWidthExplanation"], "1056" : ["CS", "VOILUTFunction"], "1080" : ["CS", "GrayScale"], "1090" : ["CS", "RecommendedViewingMode"], "1100" : ["SS", "GrayLookupTableDescriptor"], "1101" : ["SS", "RedPaletteColorLookupTableDescriptor"], "1102" : ["SS", "GreenPaletteColorLookupTableDescriptor"], "1103" : ["SS", "BluePaletteColorLookupTableDescriptor"], "1104" : ["US", "AlphaPaletteColorLookupTableDescriptor"], "1111" : ["SS", "LargeRedPaletteColorLookupTableDescriptor"], "1112" : ["SS", "LargeGreenPaletteColorLookupTableDescriptor"], "1113" : ["SS", "LargeBluePaletteColorLookupTableDescriptor"], "1199" : ["UI", "PaletteColorLookupTableUID"], "1200" : ["OW", "GrayLookupTableData"], "1201" : ["OW", "RedPaletteColorLookupTableData"], "1202" : ["OW", "GreenPaletteColorLookupTableData"], "1203" : ["OW", "BluePaletteColorLookupTableData"], "1204" : ["OW", "AlphaPaletteColorLookupTableData"], "1211" : ["OW", "LargeRedPaletteColorLookupTableData"], "1212" : ["OW", "LargeGreenPaletteColorLookupTableData"], "1213" : ["OW", "LargeBluePaletteColorLookupTableData"], "1214" : ["UI", "LargePaletteColorLookupTableUID"], "1221" : ["OW", "SegmentedRedPaletteColorLookupTableData"], "1222" : ["OW", "SegmentedGreenPaletteColorLookupTableData"], "1223" : ["OW", "SegmentedBluePaletteColorLookupTableData"], "1300" : ["CS", "BreastImplantPresent"], "1350" : ["CS", "PartialView"], "1351" : ["ST", "PartialViewDescription"], "1352" : ["SQ", "PartialViewCodeSequence"], "135A" : ["CS", "SpatialLocationsPreserved"], "1401" : ["SQ", "DataFrameAssignmentSequence"], "1402" : ["CS", "DataPathAssignment"], "1403" : ["US", "BitsMappedToColorLookupTable"], "1404" : ["SQ", "BlendingLUT1Sequence"], "1405" : ["CS", "BlendingLUT1TransferFunction"], "1406" : ["FD", "BlendingWeightConstant"], "1407" : ["US", "BlendingLookupTableDescriptor"], "1408" : ["OW", "BlendingLookupTableData"], "140B" : ["SQ", "EnhancedPaletteColorLookupTableSequence"], "140C" : ["SQ", "BlendingLUT2Sequence"], "140D" : ["CS", "BlendingLUT2TransferFunction"], "140E" : ["CS", "DataPathID"], "140F" : ["CS", "RGBLUTTransferFunction"], "1410" : ["CS", "AlphaLUTTransferFunction"], "2000" : ["OB", "ICCProfile"], "2110" : ["CS", "LossyImageCompression"], "2112" : ["DS", "LossyImageCompressionRatio"], "2114" : ["CS", "LossyImageCompressionMethod"], "3000" : ["SQ", "ModalityLUTSequence"], "3002" : ["SS", "LUTDescriptor"], "3003" : ["LO", "LUTExplanation"], "3004" : ["LO", "ModalityLUTType"], "3006" : ["OW", "LUTData"], "3010" : ["SQ", "VOILUTSequence"], "3110" : ["SQ", "SoftcopyVOILUTSequence"], "4000" : ["LT", "ImagePresentationComments"], "5000" : ["SQ", "BiPlaneAcquisitionSequence"], "6010" : ["US", "RepresentativeFrameNumber"], "6020" : ["US", "FrameNumbersOfInterest"], "6022" : ["LO", "FrameOfInterestDescription"], "6023" : ["CS", "FrameOfInterestType"], "6030" : ["US", "MaskPointers"], "6040" : ["US", "RWavePointer"], "6100" : ["SQ", "MaskSubtractionSequence"], "6101" : ["CS", "MaskOperation"], "6102" : ["US", "ApplicableFrameRange"], "6110" : ["US", "MaskFrameNumbers"], "6112" : ["US", "ContrastFrameAveraging"], "6114" : ["FL", "MaskSubPixelShift"], "6120" : ["SS", "TIDOffset"], "6190" : ["ST", "MaskOperationExplanation"], "7FE0" : ["UT", "PixelDataProviderURL"], "9001" : ["UL", "DataPointRows"], "9002" : ["UL", "DataPointColumns"], "9003" : ["CS", "SignalDomainColumns"], "9099" : ["US", "LargestMonochromePixelValue"], "9108" : ["CS", "DataRepresentation"], "9110" : ["SQ", "PixelMeasuresSequence"], "9132" : ["SQ", "FrameVOILUTSequence"], "9145" : ["SQ", "PixelValueTransformationSequence"], "9235" : ["CS", "SignalDomainRows"], "9411" : ["FL", "DisplayFilterPercentage"], "9415" : ["SQ", "FramePixelShiftSequence"], "9416" : ["US", "SubtractionItemID"], "9422" : ["SQ", "PixelIntensityRelationshipLUTSequence"], "9443" : ["SQ", "FramePixelDataPropertiesSequence"], "9444" : ["CS", "GeometricalProperties"], "9445" : ["FL", "GeometricMaximumDistortion"], "9446" : ["CS", "ImageProcessingApplied"], "9454" : ["CS", "MaskSelectionMode"], "9474" : ["CS", "LUTFunction"], "9478" : ["FL", "MaskVisibilityPercentage"], "9501" : ["SQ", "PixelShiftSequence"], "9502" : ["SQ", "RegionPixelShiftSequence"], "9503" : ["SS", "VerticesOfTheRegion"], "9505" : ["SQ", "MultiFramePresentationSequence"], "9506" : ["US", "PixelShiftFrameRange"], "9507" : ["US", "LUTFrameRange"], "9520" : ["DS", "ImageToEquipmentMappingMatrix"], "9537" : ["CS", "EquipmentCoordinateSystemIdentification"] }, "0032" : { "000A" : ["CS", "StudyStatusID"], "000C" : ["CS", "StudyPriorityID"], "0012" : ["LO", "StudyIDIssuer"], "0032" : ["DA", "StudyVerifiedDate"], "0033" : ["TM", "StudyVerifiedTime"], "0034" : ["DA", "StudyReadDate"], "0035" : ["TM", "StudyReadTime"], "1000" : ["DA", "ScheduledStudyStartDate"], "1001" : ["TM", "ScheduledStudyStartTime"], "1010" : ["DA", "ScheduledStudyStopDate"], "1011" : ["TM", "ScheduledStudyStopTime"], "1020" : ["LO", "ScheduledStudyLocation"], "1021" : ["AE", "ScheduledStudyLocationAETitle"], "1030" : ["LO", "ReasonForStudy"], "1031" : ["SQ", "RequestingPhysicianIdentificationSequence"], "1032" : ["PN", "RequestingPhysician"], "1033" : ["LO", "RequestingService"], "1034" : ["SQ", "RequestingServiceCodeSequence"], "1040" : ["DA", "StudyArrivalDate"], "1041" : ["TM", "StudyArrivalTime"], "1050" : ["DA", "StudyCompletionDate"], "1051" : ["TM", "StudyCompletionTime"], "1055" : ["CS", "StudyComponentStatusID"], "1060" : ["LO", "RequestedProcedureDescription"], "1064" : ["SQ", "RequestedProcedureCodeSequence"], "1070" : ["LO", "RequestedContrastAgent"], "4000" : ["LT", "StudyComments"] }, "0038" : { "0004" : ["SQ", "ReferencedPatientAliasSequence"], "0008" : ["CS", "VisitStatusID"], "0010" : ["LO", "AdmissionID"], "0011" : ["LO", "IssuerOfAdmissionID"], "0014" : ["SQ", "IssuerOfAdmissionIDSequence"], "0016" : ["LO", "RouteOfAdmissions"], "001A" : ["DA", "ScheduledAdmissionDate"], "001B" : ["TM", "ScheduledAdmissionTime"], "001C" : ["DA", "ScheduledDischargeDate"], "001D" : ["TM", "ScheduledDischargeTime"], "001E" : ["LO", "ScheduledPatientInstitutionResidence"], "0020" : ["DA", "AdmittingDate"], "0021" : ["TM", "AdmittingTime"], "0030" : ["DA", "DischargeDate"], "0032" : ["TM", "DischargeTime"], "0040" : ["LO", "DischargeDiagnosisDescription"], "0044" : ["SQ", "DischargeDiagnosisCodeSequence"], "0050" : ["LO", "SpecialNeeds"], "0060" : ["LO", "ServiceEpisodeID"], "0061" : ["LO", "IssuerOfServiceEpisodeID"], "0062" : ["LO", "ServiceEpisodeDescription"], "0064" : ["SQ", "IssuerOfServiceEpisodeIDSequence"], "0100" : ["SQ", "PertinentDocumentsSequence"], "0300" : ["LO", "CurrentPatientLocation"], "0400" : ["LO", "PatientInstitutionResidence"], "0500" : ["LO", "PatientState"], "0502" : ["SQ", "PatientClinicalTrialParticipationSequence"], "4000" : ["LT", "VisitComments"] }, "003A" : { "0004" : ["CS", "WaveformOriginality"], "0005" : ["US", "NumberOfWaveformChannels"], "0010" : ["UL", "NumberOfWaveformSamples"], "001A" : ["DS", "SamplingFrequency"], "0020" : ["SH", "MultiplexGroupLabel"], "0200" : ["SQ", "ChannelDefinitionSequence"], "0202" : ["IS", "WaveformChannelNumber"], "0203" : ["SH", "ChannelLabel"], "0205" : ["CS", "ChannelStatus"], "0208" : ["SQ", "ChannelSourceSequence"], "0209" : ["SQ", "ChannelSourceModifiersSequence"], "020A" : ["SQ", "SourceWaveformSequence"], "020C" : ["LO", "ChannelDerivationDescription"], "0210" : ["DS", "ChannelSensitivity"], "0211" : ["SQ", "ChannelSensitivityUnitsSequence"], "0212" : ["DS", "ChannelSensitivityCorrectionFactor"], "0213" : ["DS", "ChannelBaseline"], "0214" : ["DS", "ChannelTimeSkew"], "0215" : ["DS", "ChannelSampleSkew"], "0218" : ["DS", "ChannelOffset"], "021A" : ["US", "WaveformBitsStored"], "0220" : ["DS", "FilterLowFrequency"], "0221" : ["DS", "FilterHighFrequency"], "0222" : ["DS", "NotchFilterFrequency"], "0223" : ["DS", "NotchFilterBandwidth"], "0230" : ["FL", "WaveformDataDisplayScale"], "0231" : ["US", "WaveformDisplayBackgroundCIELabValue"], "0240" : ["SQ", "WaveformPresentationGroupSequence"], "0241" : ["US", "PresentationGroupNumber"], "0242" : ["SQ", "ChannelDisplaySequence"], "0244" : ["US", "ChannelRecommendedDisplayCIELabValue"], "0245" : ["FL", "ChannelPosition"], "0246" : ["CS", "DisplayShadingFlag"], "0247" : ["FL", "FractionalChannelDisplayScale"], "0248" : ["FL", "AbsoluteChannelDisplayScale"], "0300" : ["SQ", "MultiplexedAudioChannelsDescriptionCodeSequence"], "0301" : ["IS", "ChannelIdentificationCode"], "0302" : ["CS", "ChannelMode"] }, "0040" : { "0001" : ["AE", "ScheduledStationAETitle"], "0002" : ["DA", "ScheduledProcedureStepStartDate"], "0003" : ["TM", "ScheduledProcedureStepStartTime"], "0004" : ["DA", "ScheduledProcedureStepEndDate"], "0005" : ["TM", "ScheduledProcedureStepEndTime"], "0006" : ["PN", "ScheduledPerformingPhysicianName"], "0007" : ["LO", "ScheduledProcedureStepDescription"], "0008" : ["SQ", "ScheduledProtocolCodeSequence"], "0009" : ["SH", "ScheduledProcedureStepID"], "000A" : ["SQ", "StageCodeSequence"], "000B" : ["SQ", "ScheduledPerformingPhysicianIdentificationSequence"], "0010" : ["SH", "ScheduledStationName"], "0011" : ["SH", "ScheduledProcedureStepLocation"], "0012" : ["LO", "PreMedication"], "0020" : ["CS", "ScheduledProcedureStepStatus"], "0026" : ["SQ", "OrderPlacerIdentifierSequence"], "0027" : ["SQ", "OrderFillerIdentifierSequence"], "0031" : ["UT", "LocalNamespaceEntityID"], "0032" : ["UT", "UniversalEntityID"], "0033" : ["CS", "UniversalEntityIDType"], "0035" : ["CS", "IdentifierTypeCode"], "0036" : ["SQ", "AssigningFacilitySequence"], "0039" : ["SQ", "AssigningJurisdictionCodeSequence"], "003A" : ["SQ", "AssigningAgencyOrDepartmentCodeSequence"], "0100" : ["SQ", "ScheduledProcedureStepSequence"], "0220" : ["SQ", "ReferencedNonImageCompositeSOPInstanceSequence"], "0241" : ["AE", "PerformedStationAETitle"], "0242" : ["SH", "PerformedStationName"], "0243" : ["SH", "PerformedLocation"], "0244" : ["DA", "PerformedProcedureStepStartDate"], "0245" : ["TM", "PerformedProcedureStepStartTime"], "0250" : ["DA", "PerformedProcedureStepEndDate"], "0251" : ["TM", "PerformedProcedureStepEndTime"], "0252" : ["CS", "PerformedProcedureStepStatus"], "0253" : ["SH", "PerformedProcedureStepID"], "0254" : ["LO", "PerformedProcedureStepDescription"], "0255" : ["LO", "PerformedProcedureTypeDescription"], "0260" : ["SQ", "PerformedProtocolCodeSequence"], "0261" : ["CS", "PerformedProtocolType"], "0270" : ["SQ", "ScheduledStepAttributesSequence"], "0275" : ["SQ", "RequestAttributesSequence"], "0280" : ["ST", "CommentsOnThePerformedProcedureStep"], "0281" : ["SQ", "PerformedProcedureStepDiscontinuationReasonCodeSequence"], "0293" : ["SQ", "QuantitySequence"], "0294" : ["DS", "Quantity"], "0295" : ["SQ", "MeasuringUnitsSequence"], "0296" : ["SQ", "BillingItemSequence"], "0300" : ["US", "TotalTimeOfFluoroscopy"], "0301" : ["US", "TotalNumberOfExposures"], "0302" : ["US", "EntranceDose"], "0303" : ["US", "ExposedArea"], "0306" : ["DS", "DistanceSourceToEntrance"], "0307" : ["DS", "DistanceSourceToSupport"], "030E" : ["SQ", "ExposureDoseSequence"], "0310" : ["ST", "CommentsOnRadiationDose"], "0312" : ["DS", "XRayOutput"], "0314" : ["DS", "HalfValueLayer"], "0316" : ["DS", "OrganDose"], "0318" : ["CS", "OrganExposed"], "0320" : ["SQ", "BillingProcedureStepSequence"], "0321" : ["SQ", "FilmConsumptionSequence"], "0324" : ["SQ", "BillingSuppliesAndDevicesSequence"], "0330" : ["SQ", "ReferencedProcedureStepSequence"], "0340" : ["SQ", "PerformedSeriesSequence"], "0400" : ["LT", "CommentsOnTheScheduledProcedureStep"], "0440" : ["SQ", "ProtocolContextSequence"], "0441" : ["SQ", "ContentItemModifierSequence"], "0500" : ["SQ", "ScheduledSpecimenSequence"], "050A" : ["LO", "SpecimenAccessionNumber"], "0512" : ["LO", "ContainerIdentifier"], "0513" : ["SQ", "IssuerOfTheContainerIdentifierSequence"], "0515" : ["SQ", "AlternateContainerIdentifierSequence"], "0518" : ["SQ", "ContainerTypeCodeSequence"], "051A" : ["LO", "ContainerDescription"], "0520" : ["SQ", "ContainerComponentSequence"], "0550" : ["SQ", "SpecimenSequence"], "0551" : ["LO", "SpecimenIdentifier"], "0552" : ["SQ", "SpecimenDescriptionSequenceTrial"], "0553" : ["ST", "SpecimenDescriptionTrial"], "0554" : ["UI", "SpecimenUID"], "0555" : ["SQ", "AcquisitionContextSequence"], "0556" : ["ST", "AcquisitionContextDescription"], "059A" : ["SQ", "SpecimenTypeCodeSequence"], "0560" : ["SQ", "SpecimenDescriptionSequence"], "0562" : ["SQ", "IssuerOfTheSpecimenIdentifierSequence"], "0600" : ["LO", "SpecimenShortDescription"], "0602" : ["UT", "SpecimenDetailedDescription"], "0610" : ["SQ", "SpecimenPreparationSequence"], "0612" : ["SQ", "SpecimenPreparationStepContentItemSequence"], "0620" : ["SQ", "SpecimenLocalizationContentItemSequence"], "06FA" : ["LO", "SlideIdentifier"], "071A" : ["SQ", "ImageCenterPointCoordinatesSequence"], "072A" : ["DS", "XOffsetInSlideCoordinateSystem"], "073A" : ["DS", "YOffsetInSlideCoordinateSystem"], "074A" : ["DS", "ZOffsetInSlideCoordinateSystem"], "08D8" : ["SQ", "PixelSpacingSequence"], "08DA" : ["SQ", "CoordinateSystemAxisCodeSequence"], "08EA" : ["SQ", "MeasurementUnitsCodeSequence"], "09F8" : ["SQ", "VitalStainCodeSequenceTrial"], "1001" : ["SH", "RequestedProcedureID"], "1002" : ["LO", "ReasonForTheRequestedProcedure"], "1003" : ["SH", "RequestedProcedurePriority"], "1004" : ["LO", "PatientTransportArrangements"], "1005" : ["LO", "RequestedProcedureLocation"], "1006" : ["SH", "PlacerOrderNumberProcedure"], "1007" : ["SH", "FillerOrderNumberProcedure"], "1008" : ["LO", "ConfidentialityCode"], "1009" : ["SH", "ReportingPriority"], "100A" : ["SQ", "ReasonForRequestedProcedureCodeSequence"], "1010" : ["PN", "NamesOfIntendedRecipientsOfResults"], "1011" : ["SQ", "IntendedRecipientsOfResultsIdentificationSequence"], "1012" : ["SQ", "ReasonForPerformedProcedureCodeSequence"], "1060" : ["LO", "RequestedProcedureDescriptionTrial"], "1101" : ["SQ", "PersonIdentificationCodeSequence"], "1102" : ["ST", "PersonAddress"], "1103" : ["LO", "PersonTelephoneNumbers"], "1400" : ["LT", "RequestedProcedureComments"], "2001" : ["LO", "ReasonForTheImagingServiceRequest"], "2004" : ["DA", "IssueDateOfImagingServiceRequest"], "2005" : ["TM", "IssueTimeOfImagingServiceRequest"], "2006" : ["SH", "PlacerOrderNumberImagingServiceRequestRetired"], "2007" : ["SH", "FillerOrderNumberImagingServiceRequestRetired"], "2008" : ["PN", "OrderEnteredBy"], "2009" : ["SH", "OrderEntererLocation"], "2010" : ["SH", "OrderCallbackPhoneNumber"], "2016" : ["LO", "PlacerOrderNumberImagingServiceRequest"], "2017" : ["LO", "FillerOrderNumberImagingServiceRequest"], "2400" : ["LT", "ImagingServiceRequestComments"], "3001" : ["LO", "ConfidentialityConstraintOnPatientDataDescription"], "4001" : ["CS", "GeneralPurposeScheduledProcedureStepStatus"], "4002" : ["CS", "GeneralPurposePerformedProcedureStepStatus"], "4003" : ["CS", "GeneralPurposeScheduledProcedureStepPriority"], "4004" : ["SQ", "ScheduledProcessingApplicationsCodeSequence"], "4005" : ["DT", "ScheduledProcedureStepStartDateTime"], "4006" : ["CS", "MultipleCopiesFlag"], "4007" : ["SQ", "PerformedProcessingApplicationsCodeSequence"], "4009" : ["SQ", "HumanPerformerCodeSequence"], "4010" : ["DT", "ScheduledProcedureStepModificationDateTime"], "4011" : ["DT", "ExpectedCompletionDateTime"], "4015" : ["SQ", "ResultingGeneralPurposePerformedProcedureStepsSequence"], "4016" : ["SQ", "ReferencedGeneralPurposeScheduledProcedureStepSequence"], "4018" : ["SQ", "ScheduledWorkitemCodeSequence"], "4019" : ["SQ", "PerformedWorkitemCodeSequence"], "4020" : ["CS", "InputAvailabilityFlag"], "4021" : ["SQ", "InputInformationSequence"], "4022" : ["SQ", "RelevantInformationSequence"], "4023" : ["UI", "ReferencedGeneralPurposeScheduledProcedureStepTransactionUID"], "4025" : ["SQ", "ScheduledStationNameCodeSequence"], "4026" : ["SQ", "ScheduledStationClassCodeSequence"], "4027" : ["SQ", "ScheduledStationGeographicLocationCodeSequence"], "4028" : ["SQ", "PerformedStationNameCodeSequence"], "4029" : ["SQ", "PerformedStationClassCodeSequence"], "4030" : ["SQ", "PerformedStationGeographicLocationCodeSequence"], "4031" : ["SQ", "RequestedSubsequentWorkitemCodeSequence"], "4032" : ["SQ", "NonDICOMOutputCodeSequence"], "4033" : ["SQ", "OutputInformationSequence"], "4034" : ["SQ", "ScheduledHumanPerformersSequence"], "4035" : ["SQ", "ActualHumanPerformersSequence"], "4036" : ["LO", "HumanPerformerOrganization"], "4037" : ["PN", "HumanPerformerName"], "4040" : ["CS", "RawDataHandling"], "4041" : ["CS", "InputReadinessState"], "4050" : ["DT", "PerformedProcedureStepStartDateTime"], "4051" : ["DT", "PerformedProcedureStepEndDateTime"], "4052" : ["DT", "ProcedureStepCancellationDateTime"], "8302" : ["DS", "EntranceDoseInmGy"], "9094" : ["SQ", "ReferencedImageRealWorldValueMappingSequence"], "9096" : ["SQ", "RealWorldValueMappingSequence"], "9098" : ["SQ", "PixelValueMappingCodeSequence"], "9210" : ["SH", "LUTLabel"], "9211" : ["SS", "RealWorldValueLastValueMapped"], "9212" : ["FD", "RealWorldValueLUTData"], "9216" : ["SS", "RealWorldValueFirstValueMapped"], "9224" : ["FD", "RealWorldValueIntercept"], "9225" : ["FD", "RealWorldValueSlope"], "A007" : ["CS", "FindingsFlagTrial"], "A010" : ["CS", "RelationshipType"], "A020" : ["SQ", "FindingsSequenceTrial"], "A021" : ["UI", "FindingsGroupUIDTrial"], "A022" : ["UI", "ReferencedFindingsGroupUIDTrial"], "A023" : ["DA", "FindingsGroupRecordingDateTrial"], "A024" : ["TM", "FindingsGroupRecordingTimeTrial"], "A026" : ["SQ", "FindingsSourceCategoryCodeSequenceTrial"], "A027" : ["LO", "VerifyingOrganization"], "A028" : ["SQ", "DocumentingOrganizationIdentifierCodeSequenceTrial"], "A030" : ["DT", "VerificationDateTime"], "A032" : ["DT", "ObservationDateTime"], "A040" : ["CS", "ValueType"], "A043" : ["SQ", "ConceptNameCodeSequence"], "A047" : ["LO", "MeasurementPrecisionDescriptionTrial"], "A050" : ["CS", "ContinuityOfContent"], "A057" : ["CS", "UrgencyOrPriorityAlertsTrial"], "A060" : ["LO", "SequencingIndicatorTrial"], "A066" : ["SQ", "DocumentIdentifierCodeSequenceTrial"], "A067" : ["PN", "DocumentAuthorTrial"], "A068" : ["SQ", "DocumentAuthorIdentifierCodeSequenceTrial"], "A070" : ["SQ", "IdentifierCodeSequenceTrial"], "A073" : ["SQ", "VerifyingObserverSequence"], "A074" : ["OB", "ObjectBinaryIdentifierTrial"], "A075" : ["PN", "VerifyingObserverName"], "A076" : ["SQ", "DocumentingObserverIdentifierCodeSequenceTrial"], "A078" : ["SQ", "AuthorObserverSequence"], "A07A" : ["SQ", "ParticipantSequence"], "A07C" : ["SQ", "CustodialOrganizationSequence"], "A080" : ["CS", "ParticipationType"], "A082" : ["DT", "ParticipationDateTime"], "A084" : ["CS", "ObserverType"], "A085" : ["SQ", "ProcedureIdentifierCodeSequenceTrial"], "A088" : ["SQ", "VerifyingObserverIdentificationCodeSequence"], "A089" : ["OB", "ObjectDirectoryBinaryIdentifierTrial"], "A090" : ["SQ", "EquivalentCDADocumentSequence"], "A0B0" : ["US", "ReferencedWaveformChannels"], "A110" : ["DA", "DateOfDocumentOrVerbalTransactionTrial"], "A112" : ["TM", "TimeOfDocumentCreationOrVerbalTransactionTrial"], "A120" : ["DT", "DateTime"], "A121" : ["DA", "Date"], "A122" : ["TM", "Time"], "A123" : ["PN", "PersonName"], "A124" : ["UI", "UID"], "A125" : ["CS", "ReportStatusIDTrial"], "A130" : ["CS", "TemporalRangeType"], "A132" : ["UL", "ReferencedSamplePositions"], "A136" : ["US", "ReferencedFrameNumbers"], "A138" : ["DS", "ReferencedTimeOffsets"], "A13A" : ["DT", "ReferencedDateTime"], "A160" : ["UT", "TextValue"], "A167" : ["SQ", "ObservationCategoryCodeSequenceTrial"], "A168" : ["SQ", "ConceptCodeSequence"], "A16A" : ["ST", "BibliographicCitationTrial"], "A170" : ["SQ", "PurposeOfReferenceCodeSequence"], "A171" : ["UI", "ObservationUIDTrial"], "A172" : ["UI", "ReferencedObservationUIDTrial"], "A173" : ["CS", "ReferencedObservationClassTrial"], "A174" : ["CS", "ReferencedObjectObservationClassTrial"], "A180" : ["US", "AnnotationGroupNumber"], "A192" : ["DA", "ObservationDateTrial"], "A193" : ["TM", "ObservationTimeTrial"], "A194" : ["CS", "MeasurementAutomationTrial"], "A195" : ["SQ", "ModifierCodeSequence"], "A224" : ["ST", "IdentificationDescriptionTrial"], "A290" : ["CS", "CoordinatesSetGeometricTypeTrial"], "A296" : ["SQ", "AlgorithmCodeSequenceTrial"], "A297" : ["ST", "AlgorithmDescriptionTrial"], "A29A" : ["SL", "PixelCoordinatesSetTrial"], "A300" : ["SQ", "MeasuredValueSequence"], "A301" : ["SQ", "NumericValueQualifierCodeSequence"], "A307" : ["PN", "CurrentObserverTrial"], "A30A" : ["DS", "NumericValue"], "A313" : ["SQ", "ReferencedAccessionSequenceTrial"], "A33A" : ["ST", "ReportStatusCommentTrial"], "A340" : ["SQ", "ProcedureContextSequenceTrial"], "A352" : ["PN", "VerbalSourceTrial"], "A353" : ["ST", "AddressTrial"], "A354" : ["LO", "TelephoneNumberTrial"], "A358" : ["SQ", "VerbalSourceIdentifierCodeSequenceTrial"], "A360" : ["SQ", "PredecessorDocumentsSequence"], "A370" : ["SQ", "ReferencedRequestSequence"], "A372" : ["SQ", "PerformedProcedureCodeSequence"], "A375" : ["SQ", "CurrentRequestedProcedureEvidenceSequence"], "A380" : ["SQ", "ReportDetailSequenceTrial"], "A385" : ["SQ", "PertinentOtherEvidenceSequence"], "A390" : ["SQ", "HL7StructuredDocumentReferenceSequence"], "A402" : ["UI", "ObservationSubjectUIDTrial"], "A403" : ["CS", "ObservationSubjectClassTrial"], "A404" : ["SQ", "ObservationSubjectTypeCodeSequenceTrial"], "A491" : ["CS", "CompletionFlag"], "A492" : ["LO", "CompletionFlagDescription"], "A493" : ["CS", "VerificationFlag"], "A494" : ["CS", "ArchiveRequested"], "A496" : ["CS", "PreliminaryFlag"], "A504" : ["SQ", "ContentTemplateSequence"], "A525" : ["SQ", "IdenticalDocumentsSequence"], "A600" : ["CS", "ObservationSubjectContextFlagTrial"], "A601" : ["CS", "ObserverContextFlagTrial"], "A603" : ["CS", "ProcedureContextFlagTrial"], "A730" : ["SQ", "ContentSequence"], "A731" : ["SQ", "RelationshipSequenceTrial"], "A732" : ["SQ", "RelationshipTypeCodeSequenceTrial"], "A744" : ["SQ", "LanguageCodeSequenceTrial"], "A992" : ["ST", "UniformResourceLocatorTrial"], "B020" : ["SQ", "WaveformAnnotationSequence"], "DB00" : ["CS", "TemplateIdentifier"], "DB06" : ["DT", "TemplateVersion"], "DB07" : ["DT", "TemplateLocalVersion"], "DB0B" : ["CS", "TemplateExtensionFlag"], "DB0C" : ["UI", "TemplateExtensionOrganizationUID"], "DB0D" : ["UI", "TemplateExtensionCreatorUID"], "DB73" : ["UL", "ReferencedContentItemIdentifier"], "E001" : ["ST", "HL7InstanceIdentifier"], "E004" : ["DT", "HL7DocumentEffectiveTime"], "E006" : ["SQ", "HL7DocumentTypeCodeSequence"], "E008" : ["SQ", "DocumentClassCodeSequence"], "E010" : ["UT", "RetrieveURI"], "E011" : ["UI", "RetrieveLocationUID"], "E020" : ["CS", "TypeOfInstances"], "E021" : ["SQ", "DICOMRetrievalSequence"], "E022" : ["SQ", "DICOMMediaRetrievalSequence"], "E023" : ["SQ", "WADORetrievalSequence"], "E024" : ["SQ", "XDSRetrievalSequence"], "E030" : ["UI", "RepositoryUniqueID"], "E031" : ["UI", "HomeCommunityID"] }, "0042" : { "0010" : ["ST", "DocumentTitle"], "0011" : ["OB", "EncapsulatedDocument"], "0012" : ["LO", "MIMETypeOfEncapsulatedDocument"], "0013" : ["SQ", "SourceInstanceSequence"], "0014" : ["LO", "ListOfMIMETypes"] }, "0044" : { "0001" : ["ST", "ProductPackageIdentifier"], "0002" : ["CS", "SubstanceAdministrationApproval"], "0003" : ["LT", "ApprovalStatusFurtherDescription"], "0004" : ["DT", "ApprovalStatusDateTime"], "0007" : ["SQ", "ProductTypeCodeSequence"], "0008" : ["LO", "ProductName"], "0009" : ["LT", "ProductDescription"], "000A" : ["LO", "ProductLotIdentifier"], "000B" : ["DT", "ProductExpirationDateTime"], "0010" : ["DT", "SubstanceAdministrationDateTime"], "0011" : ["LO", "SubstanceAdministrationNotes"], "0012" : ["LO", "SubstanceAdministrationDeviceID"], "0013" : ["SQ", "ProductParameterSequence"], "0019" : ["SQ", "SubstanceAdministrationParameterSequence"] }, "0046" : { "0012" : ["LO", "LensDescription"], "0014" : ["SQ", "RightLensSequence"], "0015" : ["SQ", "LeftLensSequence"], "0016" : ["SQ", "UnspecifiedLateralityLensSequence"], "0018" : ["SQ", "CylinderSequence"], "0028" : ["SQ", "PrismSequence"], "0030" : ["FD", "HorizontalPrismPower"], "0032" : ["CS", "HorizontalPrismBase"], "0034" : ["FD", "VerticalPrismPower"], "0036" : ["CS", "VerticalPrismBase"], "0038" : ["CS", "LensSegmentType"], "0040" : ["FD", "OpticalTransmittance"], "0042" : ["FD", "ChannelWidth"], "0044" : ["FD", "PupilSize"], "0046" : ["FD", "CornealSize"], "0050" : ["SQ", "AutorefractionRightEyeSequence"], "0052" : ["SQ", "AutorefractionLeftEyeSequence"], "0060" : ["FD", "DistancePupillaryDistance"], "0062" : ["FD", "NearPupillaryDistance"], "0063" : ["FD", "IntermediatePupillaryDistance"], "0064" : ["FD", "OtherPupillaryDistance"], "0070" : ["SQ", "KeratometryRightEyeSequence"], "0071" : ["SQ", "KeratometryLeftEyeSequence"], "0074" : ["SQ", "SteepKeratometricAxisSequence"], "0075" : ["FD", "RadiusOfCurvature"], "0076" : ["FD", "KeratometricPower"], "0077" : ["FD", "KeratometricAxis"], "0080" : ["SQ", "FlatKeratometricAxisSequence"], "0092" : ["CS", "BackgroundColor"], "0094" : ["CS", "Optotype"], "0095" : ["CS", "OptotypePresentation"], "0097" : ["SQ", "SubjectiveRefractionRightEyeSequence"], "0098" : ["SQ", "SubjectiveRefractionLeftEyeSequence"], "0100" : ["SQ", "AddNearSequence"], "0101" : ["SQ", "AddIntermediateSequence"], "0102" : ["SQ", "AddOtherSequence"], "0104" : ["FD", "AddPower"], "0106" : ["FD", "ViewingDistance"], "0121" : ["SQ", "VisualAcuityTypeCodeSequence"], "0122" : ["SQ", "VisualAcuityRightEyeSequence"], "0123" : ["SQ", "VisualAcuityLeftEyeSequence"], "0124" : ["SQ", "VisualAcuityBothEyesOpenSequence"], "0125" : ["CS", "ViewingDistanceType"], "0135" : ["SS", "VisualAcuityModifiers"], "0137" : ["FD", "DecimalVisualAcuity"], "0139" : ["LO", "OptotypeDetailedDefinition"], "0145" : ["SQ", "ReferencedRefractiveMeasurementsSequence"], "0146" : ["FD", "SpherePower"], "0147" : ["FD", "CylinderPower"] }, "0048" : { "0001" : ["FL", "ImagedVolumeWidth"], "0002" : ["FL", "ImagedVolumeHeight"], "0003" : ["FL", "ImagedVolumeDepth"], "0006" : ["UL", "TotalPixelMatrixColumns"], "0007" : ["UL", "TotalPixelMatrixRows"], "0008" : ["SQ", "TotalPixelMatrixOriginSequence"], "0010" : ["CS", "SpecimenLabelInImage"], "0011" : ["CS", "FocusMethod"], "0012" : ["CS", "ExtendedDepthOfField"], "0013" : ["US", "NumberOfFocalPlanes"], "0014" : ["FL", "DistanceBetweenFocalPlanes"], "0015" : ["US", "RecommendedAbsentPixelCIELabValue"], "0100" : ["SQ", "IlluminatorTypeCodeSequence"], "0102" : ["DS", "ImageOrientationSlide"], "0105" : ["SQ", "OpticalPathSequence"], "0106" : ["SH", "OpticalPathIdentifier"], "0107" : ["ST", "OpticalPathDescription"], "0108" : ["SQ", "IlluminationColorCodeSequence"], "0110" : ["SQ", "SpecimenReferenceSequence"], "0111" : ["DS", "CondenserLensPower"], "0112" : ["DS", "ObjectiveLensPower"], "0113" : ["DS", "ObjectiveLensNumericalAperture"], "0120" : ["SQ", "PaletteColorLookupTableSequence"], "0200" : ["SQ", "ReferencedImageNavigationSequence"], "0201" : ["US", "TopLeftHandCornerOfLocalizerArea"], "0202" : ["US", "BottomRightHandCornerOfLocalizerArea"], "0207" : ["SQ", "OpticalPathIdentificationSequence"], "021A" : ["SQ", "PlanePositionSlideSequence"], "021E" : ["SL", "RowPositionInTotalImagePixelMatrix"], "021F" : ["SL", "ColumnPositionInTotalImagePixelMatrix"], "0301" : ["CS", "PixelOriginInterpretation"] }, "0050" : { "0004" : ["CS", "CalibrationImage"], "0010" : ["SQ", "DeviceSequence"], "0012" : ["SQ", "ContainerComponentTypeCodeSequence"], "0013" : ["FD", "ContainerComponentThickness"], "0014" : ["DS", "DeviceLength"], "0015" : ["FD", "ContainerComponentWidth"], "0016" : ["DS", "DeviceDiameter"], "0017" : ["CS", "DeviceDiameterUnits"], "0018" : ["DS", "DeviceVolume"], "0019" : ["DS", "InterMarkerDistance"], "001A" : ["CS", "ContainerComponentMaterial"], "001B" : ["LO", "ContainerComponentID"], "001C" : ["FD", "ContainerComponentLength"], "001D" : ["FD", "ContainerComponentDiameter"], "001E" : ["LO", "ContainerComponentDescription"], "0020" : ["LO", "DeviceDescription"] }, "0052" : { "0001" : ["FL", "ContrastBolusIngredientPercentByVolume"], "0002" : ["FD", "OCTFocalDistance"], "0003" : ["FD", "BeamSpotSize"], "0004" : ["FD", "EffectiveRefractiveIndex"], "0006" : ["CS", "OCTAcquisitionDomain"], "0007" : ["FD", "OCTOpticalCenterWavelength"], "0008" : ["FD", "AxialResolution"], "0009" : ["FD", "RangingDepth"], "0011" : ["FD", "ALineRate"], "0012" : ["US", "ALinesPerFrame"], "0013" : ["FD", "CatheterRotationalRate"], "0014" : ["FD", "ALinePixelSpacing"], "0016" : ["SQ", "ModeOfPercutaneousAccessSequence"], "0025" : ["SQ", "IntravascularOCTFrameTypeSequence"], "0026" : ["CS", "OCTZOffsetApplied"], "0027" : ["SQ", "IntravascularFrameContentSequence"], "0028" : ["FD", "IntravascularLongitudinalDistance"], "0029" : ["SQ", "IntravascularOCTFrameContentSequence"], "0030" : ["SS", "OCTZOffsetCorrection"], "0031" : ["CS", "CatheterDirectionOfRotation"], "0033" : ["FD", "SeamLineLocation"], "0034" : ["FD", "FirstALineLocation"], "0036" : ["US", "SeamLineIndex"], "0038" : ["US", "NumberOfPaddedAlines"], "0039" : ["CS", "InterpolationType"], "003A" : ["CS", "RefractiveIndexApplied"] }, "0054" : { "0010" : ["US", "EnergyWindowVector"], "0011" : ["US", "NumberOfEnergyWindows"], "0012" : ["SQ", "EnergyWindowInformationSequence"], "0013" : ["SQ", "EnergyWindowRangeSequence"], "0014" : ["DS", "EnergyWindowLowerLimit"], "0015" : ["DS", "EnergyWindowUpperLimit"], "0016" : ["SQ", "RadiopharmaceuticalInformationSequence"], "0017" : ["IS", "ResidualSyringeCounts"], "0018" : ["SH", "EnergyWindowName"], "0020" : ["US", "DetectorVector"], "0021" : ["US", "NumberOfDetectors"], "0022" : ["SQ", "DetectorInformationSequence"], "0030" : ["US", "PhaseVector"], "0031" : ["US", "NumberOfPhases"], "0032" : ["SQ", "PhaseInformationSequence"], "0033" : ["US", "NumberOfFramesInPhase"], "0036" : ["IS", "PhaseDelay"], "0038" : ["IS", "PauseBetweenFrames"], "0039" : ["CS", "PhaseDescription"], "0050" : ["US", "RotationVector"], "0051" : ["US", "NumberOfRotations"], "0052" : ["SQ", "RotationInformationSequence"], "0053" : ["US", "NumberOfFramesInRotation"], "0060" : ["US", "RRIntervalVector"], "0061" : ["US", "NumberOfRRIntervals"], "0062" : ["SQ", "GatedInformationSequence"], "0063" : ["SQ", "DataInformationSequence"], "0070" : ["US", "TimeSlotVector"], "0071" : ["US", "NumberOfTimeSlots"], "0072" : ["SQ", "TimeSlotInformationSequence"], "0073" : ["DS", "TimeSlotTime"], "0080" : ["US", "SliceVector"], "0081" : ["US", "NumberOfSlices"], "0090" : ["US", "AngularViewVector"], "0100" : ["US", "TimeSliceVector"], "0101" : ["US", "NumberOfTimeSlices"], "0200" : ["DS", "StartAngle"], "0202" : ["CS", "TypeOfDetectorMotion"], "0210" : ["IS", "TriggerVector"], "0211" : ["US", "NumberOfTriggersInPhase"], "0220" : ["SQ", "ViewCodeSequence"], "0222" : ["SQ", "ViewModifierCodeSequence"], "0300" : ["SQ", "RadionuclideCodeSequence"], "0302" : ["SQ", "AdministrationRouteCodeSequence"], "0304" : ["SQ", "RadiopharmaceuticalCodeSequence"], "0306" : ["SQ", "CalibrationDataSequence"], "0308" : ["US", "EnergyWindowNumber"], "0400" : ["SH", "ImageID"], "0410" : ["SQ", "PatientOrientationCodeSequence"], "0412" : ["SQ", "PatientOrientationModifierCodeSequence"], "0414" : ["SQ", "PatientGantryRelationshipCodeSequence"], "0500" : ["CS", "SliceProgressionDirection"], "1000" : ["CS", "SeriesType"], "1001" : ["CS", "Units"], "1002" : ["CS", "CountsSource"], "1004" : ["CS", "ReprojectionMethod"], "1006" : ["CS", "SUVType"], "1100" : ["CS", "RandomsCorrectionMethod"], "1101" : ["LO", "AttenuationCorrectionMethod"], "1102" : ["CS", "DecayCorrection"], "1103" : ["LO", "ReconstructionMethod"], "1104" : ["LO", "DetectorLinesOfResponseUsed"], "1105" : ["LO", "ScatterCorrectionMethod"], "1200" : ["DS", "AxialAcceptance"], "1201" : ["IS", "AxialMash"], "1202" : ["IS", "TransverseMash"], "1203" : ["DS", "DetectorElementSize"], "1210" : ["DS", "CoincidenceWindowWidth"], "1220" : ["CS", "SecondaryCountsType"], "1300" : ["DS", "FrameReferenceTime"], "1310" : ["IS", "PrimaryPromptsCountsAccumulated"], "1311" : ["IS", "SecondaryCountsAccumulated"], "1320" : ["DS", "SliceSensitivityFactor"], "1321" : ["DS", "DecayFactor"], "1322" : ["DS", "DoseCalibrationFactor"], "1323" : ["DS", "ScatterFractionFactor"], "1324" : ["DS", "DeadTimeFactor"], "1330" : ["US", "ImageIndex"], "1400" : ["CS", "CountsIncluded"], "1401" : ["CS", "DeadTimeCorrectionFlag"] }, "0060" : { "3000" : ["SQ", "HistogramSequence"], "3002" : ["US", "HistogramNumberOfBins"], "3004" : ["SS", "HistogramFirstBinValue"], "3006" : ["SS", "HistogramLastBinValue"], "3008" : ["US", "HistogramBinWidth"], "3010" : ["LO", "HistogramExplanation"], "3020" : ["UL", "HistogramData"] }, "0062" : { "0001" : ["CS", "SegmentationType"], "0002" : ["SQ", "SegmentSequence"], "0003" : ["SQ", "SegmentedPropertyCategoryCodeSequence"], "0004" : ["US", "SegmentNumber"], "0005" : ["LO", "SegmentLabel"], "0006" : ["ST", "SegmentDescription"], "0008" : ["CS", "SegmentAlgorithmType"], "0009" : ["LO", "SegmentAlgorithmName"], "000A" : ["SQ", "SegmentIdentificationSequence"], "000B" : ["US", "ReferencedSegmentNumber"], "000C" : ["US", "RecommendedDisplayGrayscaleValue"], "000D" : ["US", "RecommendedDisplayCIELabValue"], "000E" : ["US", "MaximumFractionalValue"], "000F" : ["SQ", "SegmentedPropertyTypeCodeSequence"], "0010" : ["CS", "SegmentationFractionalType"] }, "0064" : { "0002" : ["SQ", "DeformableRegistrationSequence"], "0003" : ["UI", "SourceFrameOfReferenceUID"], "0005" : ["SQ", "DeformableRegistrationGridSequence"], "0007" : ["UL", "GridDimensions"], "0008" : ["FD", "GridResolution"], "0009" : ["OF", "VectorGridData"], "000F" : ["SQ", "PreDeformationMatrixRegistrationSequence"], "0010" : ["SQ", "PostDeformationMatrixRegistrationSequence"] }, "0066" : { "0001" : ["UL", "NumberOfSurfaces"], "0002" : ["SQ", "SurfaceSequence"], "0003" : ["UL", "SurfaceNumber"], "0004" : ["LT", "SurfaceComments"], "0009" : ["CS", "SurfaceProcessing"], "000A" : ["FL", "SurfaceProcessingRatio"], "000B" : ["LO", "SurfaceProcessingDescription"], "000C" : ["FL", "RecommendedPresentationOpacity"], "000D" : ["CS", "RecommendedPresentationType"], "000E" : ["CS", "FiniteVolume"], "0010" : ["CS", "Manifold"], "0011" : ["SQ", "SurfacePointsSequence"], "0012" : ["SQ", "SurfacePointsNormalsSequence"], "0013" : ["SQ", "SurfaceMeshPrimitivesSequence"], "0015" : ["UL", "NumberOfSurfacePoints"], "0016" : ["OF", "PointCoordinatesData"], "0017" : ["FL", "PointPositionAccuracy"], "0018" : ["FL", "MeanPointDistance"], "0019" : ["FL", "MaximumPointDistance"], "001A" : ["FL", "PointsBoundingBoxCoordinates"], "001B" : ["FL", "AxisOfRotation"], "001C" : ["FL", "CenterOfRotation"], "001E" : ["UL", "NumberOfVectors"], "001F" : ["US", "VectorDimensionality"], "0020" : ["FL", "VectorAccuracy"], "0021" : ["OF", "VectorCoordinateData"], "0023" : ["OW", "TrianglePointIndexList"], "0024" : ["OW", "EdgePointIndexList"], "0025" : ["OW", "VertexPointIndexList"], "0026" : ["SQ", "TriangleStripSequence"], "0027" : ["SQ", "TriangleFanSequence"], "0028" : ["SQ", "LineSequence"], "0029" : ["OW", "PrimitivePointIndexList"], "002A" : ["UL", "SurfaceCount"], "002B" : ["SQ", "ReferencedSurfaceSequence"], "002C" : ["UL", "ReferencedSurfaceNumber"], "002D" : ["SQ", "SegmentSurfaceGenerationAlgorithmIdentificationSequence"], "002E" : ["SQ", "SegmentSurfaceSourceInstanceSequence"], "002F" : ["SQ", "AlgorithmFamilyCodeSequence"], "0030" : ["SQ", "AlgorithmNameCodeSequence"], "0031" : ["LO", "AlgorithmVersion"], "0032" : ["LT", "AlgorithmParameters"], "0034" : ["SQ", "FacetSequence"], "0035" : ["SQ", "SurfaceProcessingAlgorithmIdentificationSequence"], "0036" : ["LO", "AlgorithmName"] }, "0068" : { "6210" : ["LO", "ImplantSize"], "6221" : ["LO", "ImplantTemplateVersion"], "6222" : ["SQ", "ReplacedImplantTemplateSequence"], "6223" : ["CS", "ImplantType"], "6224" : ["SQ", "DerivationImplantTemplateSequence"], "6225" : ["SQ", "OriginalImplantTemplateSequence"], "6226" : ["DT", "EffectiveDateTime"], "6230" : ["SQ", "ImplantTargetAnatomySequence"], "6260" : ["SQ", "InformationFromManufacturerSequence"], "6265" : ["SQ", "NotificationFromManufacturerSequence"], "6270" : ["DT", "InformationIssueDateTime"], "6280" : ["ST", "InformationSummary"], "62A0" : ["SQ", "ImplantRegulatoryDisapprovalCodeSequence"], "62A5" : ["FD", "OverallTemplateSpatialTolerance"], "62C0" : ["SQ", "HPGLDocumentSequence"], "62D0" : ["US", "HPGLDocumentID"], "62D5" : ["LO", "HPGLDocumentLabel"], "62E0" : ["SQ", "ViewOrientationCodeSequence"], "62F0" : ["FD", "ViewOrientationModifier"], "62F2" : ["FD", "HPGLDocumentScaling"], "6300" : ["OB", "HPGLDocument"], "6310" : ["US", "HPGLContourPenNumber"], "6320" : ["SQ", "HPGLPenSequence"], "6330" : ["US", "HPGLPenNumber"], "6340" : ["LO", "HPGLPenLabel"], "6345" : ["ST", "HPGLPenDescription"], "6346" : ["FD", "RecommendedRotationPoint"], "6347" : ["FD", "BoundingRectangle"], "6350" : ["US", "ImplantTemplate3DModelSurfaceNumber"], "6360" : ["SQ", "SurfaceModelDescriptionSequence"], "6380" : ["LO", "SurfaceModelLabel"], "6390" : ["FD", "SurfaceModelScalingFactor"], "63A0" : ["SQ", "MaterialsCodeSequence"], "63A4" : ["SQ", "CoatingMaterialsCodeSequence"], "63A8" : ["SQ", "ImplantTypeCodeSequence"], "63AC" : ["SQ", "FixationMethodCodeSequence"], "63B0" : ["SQ", "MatingFeatureSetsSequence"], "63C0" : ["US", "MatingFeatureSetID"], "63D0" : ["LO", "MatingFeatureSetLabel"], "63E0" : ["SQ", "MatingFeatureSequence"], "63F0" : ["US", "MatingFeatureID"], "6400" : ["SQ", "MatingFeatureDegreeOfFreedomSequence"], "6410" : ["US", "DegreeOfFreedomID"], "6420" : ["CS", "DegreeOfFreedomType"], "6430" : ["SQ", "TwoDMatingFeatureCoordinatesSequence"], "6440" : ["US", "ReferencedHPGLDocumentID"], "6450" : ["FD", "TwoDMatingPoint"], "6460" : ["FD", "TwoDMatingAxes"], "6470" : ["SQ", "TwoDDegreeOfFreedomSequence"], "6490" : ["FD", "ThreeDDegreeOfFreedomAxis"], "64A0" : ["FD", "RangeOfFreedom"], "64C0" : ["FD", "ThreeDMatingPoint"], "64D0" : ["FD", "ThreeDMatingAxes"], "64F0" : ["FD", "TwoDDegreeOfFreedomAxis"], "6500" : ["SQ", "PlanningLandmarkPointSequence"], "6510" : ["SQ", "PlanningLandmarkLineSequence"], "6520" : ["SQ", "PlanningLandmarkPlaneSequence"], "6530" : ["US", "PlanningLandmarkID"], "6540" : ["LO", "PlanningLandmarkDescription"], "6545" : ["SQ", "PlanningLandmarkIdentificationCodeSequence"], "6550" : ["SQ", "TwoDPointCoordinatesSequence"], "6560" : ["FD", "TwoDPointCoordinates"], "6590" : ["FD", "ThreeDPointCoordinates"], "65A0" : ["SQ", "TwoDLineCoordinatesSequence"], "65B0" : ["FD", "TwoDLineCoordinates"], "65D0" : ["FD", "ThreeDLineCoordinates"], "65E0" : ["SQ", "TwoDPlaneCoordinatesSequence"], "65F0" : ["FD", "TwoDPlaneIntersection"], "6610" : ["FD", "ThreeDPlaneOrigin"], "6620" : ["FD", "ThreeDPlaneNormal"] }, "0070" : { "0001" : ["SQ", "GraphicAnnotationSequence"], "0002" : ["CS", "GraphicLayer"], "0003" : ["CS", "BoundingBoxAnnotationUnits"], "0004" : ["CS", "AnchorPointAnnotationUnits"], "0005" : ["CS", "GraphicAnnotationUnits"], "0006" : ["ST", "UnformattedTextValue"], "0008" : ["SQ", "TextObjectSequence"], "0009" : ["SQ", "GraphicObjectSequence"], "0010" : ["FL", "BoundingBoxTopLeftHandCorner"], "0011" : ["FL", "BoundingBoxBottomRightHandCorner"], "0012" : ["CS", "BoundingBoxTextHorizontalJustification"], "0014" : ["FL", "AnchorPoint"], "0015" : ["CS", "AnchorPointVisibility"], "0020" : ["US", "GraphicDimensions"], "0021" : ["US", "NumberOfGraphicPoints"], "0022" : ["FL", "GraphicData"], "0023" : ["CS", "GraphicType"], "0024" : ["CS", "GraphicFilled"], "0040" : ["IS", "ImageRotationRetired"], "0041" : ["CS", "ImageHorizontalFlip"], "0042" : ["US", "ImageRotation"], "0050" : ["US", "DisplayedAreaTopLeftHandCornerTrial"], "0051" : ["US", "DisplayedAreaBottomRightHandCornerTrial"], "0052" : ["SL", "DisplayedAreaTopLeftHandCorner"], "0053" : ["SL", "DisplayedAreaBottomRightHandCorner"], "005A" : ["SQ", "DisplayedAreaSelectionSequence"], "0060" : ["SQ", "GraphicLayerSequence"], "0062" : ["IS", "GraphicLayerOrder"], "0066" : ["US", "GraphicLayerRecommendedDisplayGrayscaleValue"], "0067" : ["US", "GraphicLayerRecommendedDisplayRGBValue"], "0068" : ["LO", "GraphicLayerDescription"], "0080" : ["CS", "ContentLabel"], "0081" : ["LO", "ContentDescription"], "0082" : ["DA", "PresentationCreationDate"], "0083" : ["TM", "PresentationCreationTime"], "0084" : ["PN", "ContentCreatorName"], "0086" : ["SQ", "ContentCreatorIdentificationCodeSequence"], "0087" : ["SQ", "AlternateContentDescriptionSequence"], "0100" : ["CS", "PresentationSizeMode"], "0101" : ["DS", "PresentationPixelSpacing"], "0102" : ["IS", "PresentationPixelAspectRatio"], "0103" : ["FL", "PresentationPixelMagnificationRatio"], "0207" : ["LO", "GraphicGroupLabel"], "0208" : ["ST", "GraphicGroupDescription"], "0209" : ["SQ", "CompoundGraphicSequence"], "0226" : ["UL", "CompoundGraphicInstanceID"], "0227" : ["LO", "FontName"], "0228" : ["CS", "FontNameType"], "0229" : ["LO", "CSSFontName"], "0230" : ["FD", "RotationAngle"], "0231" : ["SQ", "TextStyleSequence"], "0232" : ["SQ", "LineStyleSequence"], "0233" : ["SQ", "FillStyleSequence"], "0234" : ["SQ", "GraphicGroupSequence"], "0241" : ["US", "TextColorCIELabValue"], "0242" : ["CS", "HorizontalAlignment"], "0243" : ["CS", "VerticalAlignment"], "0244" : ["CS", "ShadowStyle"], "0245" : ["FL", "ShadowOffsetX"], "0246" : ["FL", "ShadowOffsetY"], "0247" : ["US", "ShadowColorCIELabValue"], "0248" : ["CS", "Underlined"], "0249" : ["CS", "Bold"], "0250" : ["CS", "Italic"], "0251" : ["US", "PatternOnColorCIELabValue"], "0252" : ["US", "PatternOffColorCIELabValue"], "0253" : ["FL", "LineThickness"], "0254" : ["CS", "LineDashingStyle"], "0255" : ["UL", "LinePattern"], "0256" : ["OB", "FillPattern"], "0257" : ["CS", "FillMode"], "0258" : ["FL", "ShadowOpacity"], "0261" : ["FL", "GapLength"], "0262" : ["FL", "DiameterOfVisibility"], "0273" : ["FL", "RotationPoint"], "0274" : ["CS", "TickAlignment"], "0278" : ["CS", "ShowTickLabel"], "0279" : ["CS", "TickLabelAlignment"], "0282" : ["CS", "CompoundGraphicUnits"], "0284" : ["FL", "PatternOnOpacity"], "0285" : ["FL", "PatternOffOpacity"], "0287" : ["SQ", "MajorTicksSequence"], "0288" : ["FL", "TickPosition"], "0289" : ["SH", "TickLabel"], "0294" : ["CS", "CompoundGraphicType"], "0295" : ["UL", "GraphicGroupID"], "0306" : ["CS", "ShapeType"], "0308" : ["SQ", "RegistrationSequence"], "0309" : ["SQ", "MatrixRegistrationSequence"], "030A" : ["SQ", "MatrixSequence"], "030C" : ["CS", "FrameOfReferenceTransformationMatrixType"], "030D" : ["SQ", "RegistrationTypeCodeSequence"], "030F" : ["ST", "FiducialDescription"], "0310" : ["SH", "FiducialIdentifier"], "0311" : ["SQ", "FiducialIdentifierCodeSequence"], "0312" : ["FD", "ContourUncertaintyRadius"], "0314" : ["SQ", "UsedFiducialsSequence"], "0318" : ["SQ", "GraphicCoordinatesDataSequence"], "031A" : ["UI", "FiducialUID"], "031C" : ["SQ", "FiducialSetSequence"], "031E" : ["SQ", "FiducialSequence"], "0401" : ["US", "GraphicLayerRecommendedDisplayCIELabValue"], "0402" : ["SQ", "BlendingSequence"], "0403" : ["FL", "RelativeOpacity"], "0404" : ["SQ", "ReferencedSpatialRegistrationSequence"], "0405" : ["CS", "BlendingPosition"] }, "0072" : { "0002" : ["SH", "HangingProtocolName"], "0004" : ["LO", "HangingProtocolDescription"], "0006" : ["CS", "HangingProtocolLevel"], "0008" : ["LO", "HangingProtocolCreator"], "000A" : ["DT", "HangingProtocolCreationDateTime"], "000C" : ["SQ", "HangingProtocolDefinitionSequence"], "000E" : ["SQ", "HangingProtocolUserIdentificationCodeSequence"], "0010" : ["LO", "HangingProtocolUserGroupName"], "0012" : ["SQ", "SourceHangingProtocolSequence"], "0014" : ["US", "NumberOfPriorsReferenced"], "0020" : ["SQ", "ImageSetsSequence"], "0022" : ["SQ", "ImageSetSelectorSequence"], "0024" : ["CS", "ImageSetSelectorUsageFlag"], "0026" : ["AT", "SelectorAttribute"], "0028" : ["US", "SelectorValueNumber"], "0030" : ["SQ", "TimeBasedImageSetsSequence"], "0032" : ["US", "ImageSetNumber"], "0034" : ["CS", "ImageSetSelectorCategory"], "0038" : ["US", "RelativeTime"], "003A" : ["CS", "RelativeTimeUnits"], "003C" : ["SS", "AbstractPriorValue"], "003E" : ["SQ", "AbstractPriorCodeSequence"], "0040" : ["LO", "ImageSetLabel"], "0050" : ["CS", "SelectorAttributeVR"], "0052" : ["AT", "SelectorSequencePointer"], "0054" : ["LO", "SelectorSequencePointerPrivateCreator"], "0056" : ["LO", "SelectorAttributePrivateCreator"], "0060" : ["AT", "SelectorATValue"], "0062" : ["CS", "SelectorCSValue"], "0064" : ["IS", "SelectorISValue"], "0066" : ["LO", "SelectorLOValue"], "0068" : ["LT", "SelectorLTValue"], "006A" : ["PN", "SelectorPNValue"], "006C" : ["SH", "SelectorSHValue"], "006E" : ["ST", "SelectorSTValue"], "0070" : ["UT", "SelectorUTValue"], "0072" : ["DS", "SelectorDSValue"], "0074" : ["FD", "SelectorFDValue"], "0076" : ["FL", "SelectorFLValue"], "0078" : ["UL", "SelectorULValue"], "007A" : ["US", "SelectorUSValue"], "007C" : ["SL", "SelectorSLValue"], "007E" : ["SS", "SelectorSSValue"], "0080" : ["SQ", "SelectorCodeSequenceValue"], "0100" : ["US", "NumberOfScreens"], "0102" : ["SQ", "NominalScreenDefinitionSequence"], "0104" : ["US", "NumberOfVerticalPixels"], "0106" : ["US", "NumberOfHorizontalPixels"], "0108" : ["FD", "DisplayEnvironmentSpatialPosition"], "010A" : ["US", "ScreenMinimumGrayscaleBitDepth"], "010C" : ["US", "ScreenMinimumColorBitDepth"], "010E" : ["US", "ApplicationMaximumRepaintTime"], "0200" : ["SQ", "DisplaySetsSequence"], "0202" : ["US", "DisplaySetNumber"], "0203" : ["LO", "DisplaySetLabel"], "0204" : ["US", "DisplaySetPresentationGroup"], "0206" : ["LO", "DisplaySetPresentationGroupDescription"], "0208" : ["CS", "PartialDataDisplayHandling"], "0210" : ["SQ", "SynchronizedScrollingSequence"], "0212" : ["US", "DisplaySetScrollingGroup"], "0214" : ["SQ", "NavigationIndicatorSequence"], "0216" : ["US", "NavigationDisplaySet"], "0218" : ["US", "ReferenceDisplaySets"], "0300" : ["SQ", "ImageBoxesSequence"], "0302" : ["US", "ImageBoxNumber"], "0304" : ["CS", "ImageBoxLayoutType"], "0306" : ["US", "ImageBoxTileHorizontalDimension"], "0308" : ["US", "ImageBoxTileVerticalDimension"], "0310" : ["CS", "ImageBoxScrollDirection"], "0312" : ["CS", "ImageBoxSmallScrollType"], "0314" : ["US", "ImageBoxSmallScrollAmount"], "0316" : ["CS", "ImageBoxLargeScrollType"], "0318" : ["US", "ImageBoxLargeScrollAmount"], "0320" : ["US", "ImageBoxOverlapPriority"], "0330" : ["FD", "CineRelativeToRealTime"], "0400" : ["SQ", "FilterOperationsSequence"], "0402" : ["CS", "FilterByCategory"], "0404" : ["CS", "FilterByAttributePresence"], "0406" : ["CS", "FilterByOperator"], "0420" : ["US", "StructuredDisplayBackgroundCIELabValue"], "0421" : ["US", "EmptyImageBoxCIELabValue"], "0422" : ["SQ", "StructuredDisplayImageBoxSequence"], "0424" : ["SQ", "StructuredDisplayTextBoxSequence"], "0427" : ["SQ", "ReferencedFirstFrameSequence"], "0430" : ["SQ", "ImageBoxSynchronizationSequence"], "0432" : ["US", "SynchronizedImageBoxList"], "0434" : ["CS", "TypeOfSynchronization"], "0500" : ["CS", "BlendingOperationType"], "0510" : ["CS", "ReformattingOperationType"], "0512" : ["FD", "ReformattingThickness"], "0514" : ["FD", "ReformattingInterval"], "0516" : ["CS", "ReformattingOperationInitialViewDirection"], "0520" : ["CS", "ThreeDRenderingType"], "0600" : ["SQ", "SortingOperationsSequence"], "0602" : ["CS", "SortByCategory"], "0604" : ["CS", "SortingDirection"], "0700" : ["CS", "DisplaySetPatientOrientation"], "0702" : ["CS", "VOIType"], "0704" : ["CS", "PseudoColorType"], "0705" : ["SQ", "PseudoColorPaletteInstanceReferenceSequence"], "0706" : ["CS", "ShowGrayscaleInverted"], "0710" : ["CS", "ShowImageTrueSizeFlag"], "0712" : ["CS", "ShowGraphicAnnotationFlag"], "0714" : ["CS", "ShowPatientDemographicsFlag"], "0716" : ["CS", "ShowAcquisitionTechniquesFlag"], "0717" : ["CS", "DisplaySetHorizontalJustification"], "0718" : ["CS", "DisplaySetVerticalJustification"] }, "0074" : { "0120" : ["FD", "ContinuationStartMeterset"], "0121" : ["FD", "ContinuationEndMeterset"], "1000" : ["CS", "ProcedureStepState"], "1002" : ["SQ", "ProcedureStepProgressInformationSequence"], "1004" : ["DS", "ProcedureStepProgress"], "1006" : ["ST", "ProcedureStepProgressDescription"], "1008" : ["SQ", "ProcedureStepCommunicationsURISequence"], "100A" : ["ST", "ContactURI"], "100C" : ["LO", "ContactDisplayName"], "100E" : ["SQ", "ProcedureStepDiscontinuationReasonCodeSequence"], "1020" : ["SQ", "BeamTaskSequence"], "1022" : ["CS", "BeamTaskType"], "1024" : ["IS", "BeamOrderIndexTrial"], "1026" : ["FD", "TableTopVerticalAdjustedPosition"], "1027" : ["FD", "TableTopLongitudinalAdjustedPosition"], "1028" : ["FD", "TableTopLateralAdjustedPosition"], "102A" : ["FD", "PatientSupportAdjustedAngle"], "102B" : ["FD", "TableTopEccentricAdjustedAngle"], "102C" : ["FD", "TableTopPitchAdjustedAngle"], "102D" : ["FD", "TableTopRollAdjustedAngle"], "1030" : ["SQ", "DeliveryVerificationImageSequence"], "1032" : ["CS", "VerificationImageTiming"], "1034" : ["CS", "DoubleExposureFlag"], "1036" : ["CS", "DoubleExposureOrdering"], "1038" : ["DS", "DoubleExposureMetersetTrial"], "103A" : ["DS", "DoubleExposureFieldDeltaTrial"], "1040" : ["SQ", "RelatedReferenceRTImageSequence"], "1042" : ["SQ", "GeneralMachineVerificationSequence"], "1044" : ["SQ", "ConventionalMachineVerificationSequence"], "1046" : ["SQ", "IonMachineVerificationSequence"], "1048" : ["SQ", "FailedAttributesSequence"], "104A" : ["SQ", "OverriddenAttributesSequence"], "104C" : ["SQ", "ConventionalControlPointVerificationSequence"], "104E" : ["SQ", "IonControlPointVerificationSequence"], "1050" : ["SQ", "AttributeOccurrenceSequence"], "1052" : ["AT", "AttributeOccurrencePointer"], "1054" : ["UL", "AttributeItemSelector"], "1056" : ["LO", "AttributeOccurrencePrivateCreator"], "1057" : ["IS", "SelectorSequencePointerItems"], "1200" : ["CS", "ScheduledProcedureStepPriority"], "1202" : ["LO", "WorklistLabel"], "1204" : ["LO", "ProcedureStepLabel"], "1210" : ["SQ", "ScheduledProcessingParametersSequence"], "1212" : ["SQ", "PerformedProcessingParametersSequence"], "1216" : ["SQ", "UnifiedProcedureStepPerformedProcedureSequence"], "1220" : ["SQ", "RelatedProcedureStepSequence"], "1222" : ["LO", "ProcedureStepRelationshipType"], "1224" : ["SQ", "ReplacedProcedureStepSequence"], "1230" : ["LO", "DeletionLock"], "1234" : ["AE", "ReceivingAE"], "1236" : ["AE", "RequestingAE"], "1238" : ["LT", "ReasonForCancellation"], "1242" : ["CS", "SCPStatus"], "1244" : ["CS", "SubscriptionListStatus"], "1246" : ["CS", "UnifiedProcedureStepListStatus"], "1324" : ["UL", "BeamOrderIndex"], "1338" : ["FD", "DoubleExposureMeterset"], "133A" : ["FD", "DoubleExposureFieldDelta"] }, "0076" : { "0001" : ["LO", "ImplantAssemblyTemplateName"], "0003" : ["LO", "ImplantAssemblyTemplateIssuer"], "0006" : ["LO", "ImplantAssemblyTemplateVersion"], "0008" : ["SQ", "ReplacedImplantAssemblyTemplateSequence"], "000A" : ["CS", "ImplantAssemblyTemplateType"], "000C" : ["SQ", "OriginalImplantAssemblyTemplateSequence"], "000E" : ["SQ", "DerivationImplantAssemblyTemplateSequence"], "0010" : ["SQ", "ImplantAssemblyTemplateTargetAnatomySequence"], "0020" : ["SQ", "ProcedureTypeCodeSequence"], "0030" : ["LO", "SurgicalTechnique"], "0032" : ["SQ", "ComponentTypesSequence"], "0034" : ["CS", "ComponentTypeCodeSequence"], "0036" : ["CS", "ExclusiveComponentType"], "0038" : ["CS", "MandatoryComponentType"], "0040" : ["SQ", "ComponentSequence"], "0055" : ["US", "ComponentID"], "0060" : ["SQ", "ComponentAssemblySequence"], "0070" : ["US", "Component1ReferencedID"], "0080" : ["US", "Component1ReferencedMatingFeatureSetID"], "0090" : ["US", "Component1ReferencedMatingFeatureID"], "00A0" : ["US", "Component2ReferencedID"], "00B0" : ["US", "Component2ReferencedMatingFeatureSetID"], "00C0" : ["US", "Component2ReferencedMatingFeatureID"] }, "0078" : { "0001" : ["LO", "ImplantTemplateGroupName"], "0010" : ["ST", "ImplantTemplateGroupDescription"], "0020" : ["LO", "ImplantTemplateGroupIssuer"], "0024" : ["LO", "ImplantTemplateGroupVersion"], "0026" : ["SQ", "ReplacedImplantTemplateGroupSequence"], "0028" : ["SQ", "ImplantTemplateGroupTargetAnatomySequence"], "002A" : ["SQ", "ImplantTemplateGroupMembersSequence"], "002E" : ["US", "ImplantTemplateGroupMemberID"], "0050" : ["FD", "ThreeDImplantTemplateGroupMemberMatchingPoint"], "0060" : ["FD", "ThreeDImplantTemplateGroupMemberMatchingAxes"], "0070" : ["SQ", "ImplantTemplateGroupMemberMatching2DCoordinatesSequence"], "0090" : ["FD", "TwoDImplantTemplateGroupMemberMatchingPoint"], "00A0" : ["FD", "TwoDImplantTemplateGroupMemberMatchingAxes"], "00B0" : ["SQ", "ImplantTemplateGroupVariationDimensionSequence"], "00B2" : ["LO", "ImplantTemplateGroupVariationDimensionName"], "00B4" : ["SQ", "ImplantTemplateGroupVariationDimensionRankSequence"], "00B6" : ["US", "ReferencedImplantTemplateGroupMemberID"], "00B8" : ["US", "ImplantTemplateGroupVariationDimensionRank"] }, "0088" : { "0130" : ["SH", "StorageMediaFileSetID"], "0140" : ["UI", "StorageMediaFileSetUID"], "0200" : ["SQ", "IconImageSequence"], "0904" : ["LO", "TopicTitle"], "0906" : ["ST", "TopicSubject"], "0910" : ["LO", "TopicAuthor"], "0912" : ["LO", "TopicKeywords"] }, "0100" : { "0410" : ["CS", "SOPInstanceStatus"], "0420" : ["DT", "SOPAuthorizationDateTime"], "0424" : ["LT", "SOPAuthorizationComment"], "0426" : ["LO", "AuthorizationEquipmentCertificationNumber"] }, "0400" : { "0005" : ["US", "MACIDNumber"], "0010" : ["UI", "MACCalculationTransferSyntaxUID"], "0015" : ["CS", "MACAlgorithm"], "0020" : ["AT", "DataElementsSigned"], "0100" : ["UI", "DigitalSignatureUID"], "0105" : ["DT", "DigitalSignatureDateTime"], "0110" : ["CS", "CertificateType"], "0115" : ["OB", "CertificateOfSigner"], "0120" : ["OB", "Signature"], "0305" : ["CS", "CertifiedTimestampType"], "0310" : ["OB", "CertifiedTimestamp"], "0401" : ["SQ", "DigitalSignaturePurposeCodeSequence"], "0402" : ["SQ", "ReferencedDigitalSignatureSequence"], "0403" : ["SQ", "ReferencedSOPInstanceMACSequence"], "0404" : ["OB", "MAC"], "0500" : ["SQ", "EncryptedAttributesSequence"], "0510" : ["UI", "EncryptedContentTransferSyntaxUID"], "0520" : ["OB", "EncryptedContent"], "0550" : ["SQ", "ModifiedAttributesSequence"], "0561" : ["SQ", "OriginalAttributesSequence"], "0562" : ["DT", "AttributeModificationDateTime"], "0563" : ["LO", "ModifyingSystem"], "0564" : ["LO", "SourceOfPreviousValues"], "0565" : ["CS", "ReasonForTheAttributeModification"] }, "2000" : { "0010" : ["IS", "NumberOfCopies"], "001E" : ["SQ", "PrinterConfigurationSequence"], "0020" : ["CS", "PrintPriority"], "0030" : ["CS", "MediumType"], "0040" : ["CS", "FilmDestination"], "0050" : ["LO", "FilmSessionLabel"], "0060" : ["IS", "MemoryAllocation"], "0061" : ["IS", "MaximumMemoryAllocation"], "0062" : ["CS", "ColorImagePrintingFlag"], "0063" : ["CS", "CollationFlag"], "0065" : ["CS", "AnnotationFlag"], "0067" : ["CS", "ImageOverlayFlag"], "0069" : ["CS", "PresentationLUTFlag"], "006A" : ["CS", "ImageBoxPresentationLUTFlag"], "00A0" : ["US", "MemoryBitDepth"], "00A1" : ["US", "PrintingBitDepth"], "00A2" : ["SQ", "MediaInstalledSequence"], "00A4" : ["SQ", "OtherMediaAvailableSequence"], "00A8" : ["SQ", "SupportedImageDisplayFormatsSequence"], "0500" : ["SQ", "ReferencedFilmBoxSequence"], "0510" : ["SQ", "ReferencedStoredPrintSequence"] }, "2010" : { "0010" : ["ST", "ImageDisplayFormat"], "0030" : ["CS", "AnnotationDisplayFormatID"], "0040" : ["CS", "FilmOrientation"], "0050" : ["CS", "FilmSizeID"], "0052" : ["CS", "PrinterResolutionID"], "0054" : ["CS", "DefaultPrinterResolutionID"], "0060" : ["CS", "MagnificationType"], "0080" : ["CS", "SmoothingType"], "00A6" : ["CS", "DefaultMagnificationType"], "00A7" : ["CS", "OtherMagnificationTypesAvailable"], "00A8" : ["CS", "DefaultSmoothingType"], "00A9" : ["CS", "OtherSmoothingTypesAvailable"], "0100" : ["CS", "BorderDensity"], "0110" : ["CS", "EmptyImageDensity"], "0120" : ["US", "MinDensity"], "0130" : ["US", "MaxDensity"], "0140" : ["CS", "Trim"], "0150" : ["ST", "ConfigurationInformation"], "0152" : ["LT", "ConfigurationInformationDescription"], "0154" : ["IS", "MaximumCollatedFilms"], "015E" : ["US", "Illumination"], "0160" : ["US", "ReflectedAmbientLight"], "0376" : ["DS", "PrinterPixelSpacing"], "0500" : ["SQ", "ReferencedFilmSessionSequence"], "0510" : ["SQ", "ReferencedImageBoxSequence"], "0520" : ["SQ", "ReferencedBasicAnnotationBoxSequence"] }, "2020" : { "0010" : ["US", "ImageBoxPosition"], "0020" : ["CS", "Polarity"], "0030" : ["DS", "RequestedImageSize"], "0040" : ["CS", "RequestedDecimateCropBehavior"], "0050" : ["CS", "RequestedResolutionID"], "00A0" : ["CS", "RequestedImageSizeFlag"], "00A2" : ["CS", "DecimateCropResult"], "0110" : ["SQ", "BasicGrayscaleImageSequence"], "0111" : ["SQ", "BasicColorImageSequence"], "0130" : ["SQ", "ReferencedImageOverlayBoxSequence"], "0140" : ["SQ", "ReferencedVOILUTBoxSequence"] }, "2030" : { "0010" : ["US", "AnnotationPosition"], "0020" : ["LO", "TextString"] }, "2040" : { "0010" : ["SQ", "ReferencedOverlayPlaneSequence"], "0011" : ["US", "ReferencedOverlayPlaneGroups"], "0020" : ["SQ", "OverlayPixelDataSequence"], "0060" : ["CS", "OverlayMagnificationType"], "0070" : ["CS", "OverlaySmoothingType"], "0072" : ["CS", "OverlayOrImageMagnification"], "0074" : ["US", "MagnifyToNumberOfColumns"], "0080" : ["CS", "OverlayForegroundDensity"], "0082" : ["CS", "OverlayBackgroundDensity"], "0090" : ["CS", "OverlayMode"], "0100" : ["CS", "ThresholdDensity"], "0500" : ["SQ", "ReferencedImageBoxSequenceRetired"] }, "2050" : { "0010" : ["SQ", "PresentationLUTSequence"], "0020" : ["CS", "PresentationLUTShape"], "0500" : ["SQ", "ReferencedPresentationLUTSequence"] }, "2100" : { "0010" : ["SH", "PrintJobID"], "0020" : ["CS", "ExecutionStatus"], "0030" : ["CS", "ExecutionStatusInfo"], "0040" : ["DA", "CreationDate"], "0050" : ["TM", "CreationTime"], "0070" : ["AE", "Originator"], "0140" : ["AE", "DestinationAE"], "0160" : ["SH", "OwnerID"], "0170" : ["IS", "NumberOfFilms"], "0500" : ["SQ", "ReferencedPrintJobSequencePullStoredPrint"] }, "2110" : { "0010" : ["CS", "PrinterStatus"], "0020" : ["CS", "PrinterStatusInfo"], "0030" : ["LO", "PrinterName"], "0099" : ["SH", "PrintQueueID"] }, "2120" : { "0010" : ["CS", "QueueStatus"], "0050" : ["SQ", "PrintJobDescriptionSequence"], "0070" : ["SQ", "ReferencedPrintJobSequence"] }, "2130" : { "0010" : ["SQ", "PrintManagementCapabilitiesSequence"], "0015" : ["SQ", "PrinterCharacteristicsSequence"], "0030" : ["SQ", "FilmBoxContentSequence"], "0040" : ["SQ", "ImageBoxContentSequence"], "0050" : ["SQ", "AnnotationContentSequence"], "0060" : ["SQ", "ImageOverlayBoxContentSequence"], "0080" : ["SQ", "PresentationLUTContentSequence"], "00A0" : ["SQ", "ProposedStudySequence"], "00C0" : ["SQ", "OriginalImageSequence"] }, "2200" : { "0001" : ["CS", "LabelUsingInformationExtractedFromInstances"], "0002" : ["UT", "LabelText"], "0003" : ["CS", "LabelStyleSelection"], "0004" : ["LT", "MediaDisposition"], "0005" : ["LT", "BarcodeValue"], "0006" : ["CS", "BarcodeSymbology"], "0007" : ["CS", "AllowMediaSplitting"], "0008" : ["CS", "IncludeNonDICOMObjects"], "0009" : ["CS", "IncludeDisplayApplication"], "000A" : ["CS", "PreserveCompositeInstancesAfterMediaCreation"], "000B" : ["US", "TotalNumberOfPiecesOfMediaCreated"], "000C" : ["LO", "RequestedMediaApplicationProfile"], "000D" : ["SQ", "ReferencedStorageMediaSequence"], "000E" : ["AT", "FailureAttributes"], "000F" : ["CS", "AllowLossyCompression"], "0020" : ["CS", "RequestPriority"] }, "3002" : { "0002" : ["SH", "RTImageLabel"], "0003" : ["LO", "RTImageName"], "0004" : ["ST", "RTImageDescription"], "000A" : ["CS", "ReportedValuesOrigin"], "000C" : ["CS", "RTImagePlane"], "000D" : ["DS", "XRayImageReceptorTranslation"], "000E" : ["DS", "XRayImageReceptorAngle"], "0010" : ["DS", "RTImageOrientation"], "0011" : ["DS", "ImagePlanePixelSpacing"], "0012" : ["DS", "RTImagePosition"], "0020" : ["SH", "RadiationMachineName"], "0022" : ["DS", "RadiationMachineSAD"], "0024" : ["DS", "RadiationMachineSSD"], "0026" : ["DS", "RTImageSID"], "0028" : ["DS", "SourceToReferenceObjectDistance"], "0029" : ["IS", "FractionNumber"], "0030" : ["SQ", "ExposureSequence"], "0032" : ["DS", "MetersetExposure"], "0034" : ["DS", "DiaphragmPosition"], "0040" : ["SQ", "FluenceMapSequence"], "0041" : ["CS", "FluenceDataSource"], "0042" : ["DS", "FluenceDataScale"], "0050" : ["SQ", "PrimaryFluenceModeSequence"], "0051" : ["CS", "FluenceMode"], "0052" : ["SH", "FluenceModeID"] }, "3004" : { "0001" : ["CS", "DVHType"], "0002" : ["CS", "DoseUnits"], "0004" : ["CS", "DoseType"], "0006" : ["LO", "DoseComment"], "0008" : ["DS", "NormalizationPoint"], "000A" : ["CS", "DoseSummationType"], "000C" : ["DS", "GridFrameOffsetVector"], "000E" : ["DS", "DoseGridScaling"], "0010" : ["SQ", "RTDoseROISequence"], "0012" : ["DS", "DoseValue"], "0014" : ["CS", "TissueHeterogeneityCorrection"], "0040" : ["DS", "DVHNormalizationPoint"], "0042" : ["DS", "DVHNormalizationDoseValue"], "0050" : ["SQ", "DVHSequence"], "0052" : ["DS", "DVHDoseScaling"], "0054" : ["CS", "DVHVolumeUnits"], "0056" : ["IS", "DVHNumberOfBins"], "0058" : ["DS", "DVHData"], "0060" : ["SQ", "DVHReferencedROISequence"], "0062" : ["CS", "DVHROIContributionType"], "0070" : ["DS", "DVHMinimumDose"], "0072" : ["DS", "DVHMaximumDose"], "0074" : ["DS", "DVHMeanDose"] }, "3006" : { "0002" : ["SH", "StructureSetLabel"], "0004" : ["LO", "StructureSetName"], "0006" : ["ST", "StructureSetDescription"], "0008" : ["DA", "StructureSetDate"], "0009" : ["TM", "StructureSetTime"], "0010" : ["SQ", "ReferencedFrameOfReferenceSequence"], "0012" : ["SQ", "RTReferencedStudySequence"], "0014" : ["SQ", "RTReferencedSeriesSequence"], "0016" : ["SQ", "ContourImageSequence"], "0020" : ["SQ", "StructureSetROISequence"], "0022" : ["IS", "ROINumber"], "0024" : ["UI", "ReferencedFrameOfReferenceUID"], "0026" : ["LO", "ROIName"], "0028" : ["ST", "ROIDescription"], "002A" : ["IS", "ROIDisplayColor"], "002C" : ["DS", "ROIVolume"], "0030" : ["SQ", "RTRelatedROISequence"], "0033" : ["CS", "RTROIRelationship"], "0036" : ["CS", "ROIGenerationAlgorithm"], "0038" : ["LO", "ROIGenerationDescription"], "0039" : ["SQ", "ROIContourSequence"], "0040" : ["SQ", "ContourSequence"], "0042" : ["CS", "ContourGeometricType"], "0044" : ["DS", "ContourSlabThickness"], "0045" : ["DS", "ContourOffsetVector"], "0046" : ["IS", "NumberOfContourPoints"], "0048" : ["IS", "ContourNumber"], "0049" : ["IS", "AttachedContours"], "0050" : ["DS", "ContourData"], "0080" : ["SQ", "RTROIObservationsSequence"], "0082" : ["IS", "ObservationNumber"], "0084" : ["IS", "ReferencedROINumber"], "0085" : ["SH", "ROIObservationLabel"], "0086" : ["SQ", "RTROIIdentificationCodeSequence"], "0088" : ["ST", "ROIObservationDescription"], "00A0" : ["SQ", "RelatedRTROIObservationsSequence"], "00A4" : ["CS", "RTROIInterpretedType"], "00A6" : ["PN", "ROIInterpreter"], "00B0" : ["SQ", "ROIPhysicalPropertiesSequence"], "00B2" : ["CS", "ROIPhysicalProperty"], "00B4" : ["DS", "ROIPhysicalPropertyValue"], "00B6" : ["SQ", "ROIElementalCompositionSequence"], "00B7" : ["US", "ROIElementalCompositionAtomicNumber"], "00B8" : ["FL", "ROIElementalCompositionAtomicMassFraction"], "00C0" : ["SQ", "FrameOfReferenceRelationshipSequence"], "00C2" : ["UI", "RelatedFrameOfReferenceUID"], "00C4" : ["CS", "FrameOfReferenceTransformationType"], "00C6" : ["DS", "FrameOfReferenceTransformationMatrix"], "00C8" : ["LO", "FrameOfReferenceTransformationComment"] }, "3008" : { "0010" : ["SQ", "MeasuredDoseReferenceSequence"], "0012" : ["ST", "MeasuredDoseDescription"], "0014" : ["CS", "MeasuredDoseType"], "0016" : ["DS", "MeasuredDoseValue"], "0020" : ["SQ", "TreatmentSessionBeamSequence"], "0021" : ["SQ", "TreatmentSessionIonBeamSequence"], "0022" : ["IS", "CurrentFractionNumber"], "0024" : ["DA", "TreatmentControlPointDate"], "0025" : ["TM", "TreatmentControlPointTime"], "002A" : ["CS", "TreatmentTerminationStatus"], "002B" : ["SH", "TreatmentTerminationCode"], "002C" : ["CS", "TreatmentVerificationStatus"], "0030" : ["SQ", "ReferencedTreatmentRecordSequence"], "0032" : ["DS", "SpecifiedPrimaryMeterset"], "0033" : ["DS", "SpecifiedSecondaryMeterset"], "0036" : ["DS", "DeliveredPrimaryMeterset"], "0037" : ["DS", "DeliveredSecondaryMeterset"], "003A" : ["DS", "SpecifiedTreatmentTime"], "003B" : ["DS", "DeliveredTreatmentTime"], "0040" : ["SQ", "ControlPointDeliverySequence"], "0041" : ["SQ", "IonControlPointDeliverySequence"], "0042" : ["DS", "SpecifiedMeterset"], "0044" : ["DS", "DeliveredMeterset"], "0045" : ["FL", "MetersetRateSet"], "0046" : ["FL", "MetersetRateDelivered"], "0047" : ["FL", "ScanSpotMetersetsDelivered"], "0048" : ["DS", "DoseRateDelivered"], "0050" : ["SQ", "TreatmentSummaryCalculatedDoseReferenceSequence"], "0052" : ["DS", "CumulativeDoseToDoseReference"], "0054" : ["DA", "FirstTreatmentDate"], "0056" : ["DA", "MostRecentTreatmentDate"], "005A" : ["IS", "NumberOfFractionsDelivered"], "0060" : ["SQ", "OverrideSequence"], "0061" : ["AT", "ParameterSequencePointer"], "0062" : ["AT", "OverrideParameterPointer"], "0063" : ["IS", "ParameterItemIndex"], "0064" : ["IS", "MeasuredDoseReferenceNumber"], "0065" : ["AT", "ParameterPointer"], "0066" : ["ST", "OverrideReason"], "0068" : ["SQ", "CorrectedParameterSequence"], "006A" : ["FL", "CorrectionValue"], "0070" : ["SQ", "CalculatedDoseReferenceSequence"], "0072" : ["IS", "CalculatedDoseReferenceNumber"], "0074" : ["ST", "CalculatedDoseReferenceDescription"], "0076" : ["DS", "CalculatedDoseReferenceDoseValue"], "0078" : ["DS", "StartMeterset"], "007A" : ["DS", "EndMeterset"], "0080" : ["SQ", "ReferencedMeasuredDoseReferenceSequence"], "0082" : ["IS", "ReferencedMeasuredDoseReferenceNumber"], "0090" : ["SQ", "ReferencedCalculatedDoseReferenceSequence"], "0092" : ["IS", "ReferencedCalculatedDoseReferenceNumber"], "00A0" : ["SQ", "BeamLimitingDeviceLeafPairsSequence"], "00B0" : ["SQ", "RecordedWedgeSequence"], "00C0" : ["SQ", "RecordedCompensatorSequence"], "00D0" : ["SQ", "RecordedBlockSequence"], "00E0" : ["SQ", "TreatmentSummaryMeasuredDoseReferenceSequence"], "00F0" : ["SQ", "RecordedSnoutSequence"], "00F2" : ["SQ", "RecordedRangeShifterSequence"], "00F4" : ["SQ", "RecordedLateralSpreadingDeviceSequence"], "00F6" : ["SQ", "RecordedRangeModulatorSequence"], "0100" : ["SQ", "RecordedSourceSequence"], "0105" : ["LO", "SourceSerialNumber"], "0110" : ["SQ", "TreatmentSessionApplicationSetupSequence"], "0116" : ["CS", "ApplicationSetupCheck"], "0120" : ["SQ", "RecordedBrachyAccessoryDeviceSequence"], "0122" : ["IS", "ReferencedBrachyAccessoryDeviceNumber"], "0130" : ["SQ", "RecordedChannelSequence"], "0132" : ["DS", "SpecifiedChannelTotalTime"], "0134" : ["DS", "DeliveredChannelTotalTime"], "0136" : ["IS", "SpecifiedNumberOfPulses"], "0138" : ["IS", "DeliveredNumberOfPulses"], "013A" : ["DS", "SpecifiedPulseRepetitionInterval"], "013C" : ["DS", "DeliveredPulseRepetitionInterval"], "0140" : ["SQ", "RecordedSourceApplicatorSequence"], "0142" : ["IS", "ReferencedSourceApplicatorNumber"], "0150" : ["SQ", "RecordedChannelShieldSequence"], "0152" : ["IS", "ReferencedChannelShieldNumber"], "0160" : ["SQ", "BrachyControlPointDeliveredSequence"], "0162" : ["DA", "SafePositionExitDate"], "0164" : ["TM", "SafePositionExitTime"], "0166" : ["DA", "SafePositionReturnDate"], "0168" : ["TM", "SafePositionReturnTime"], "0200" : ["CS", "CurrentTreatmentStatus"], "0202" : ["ST", "TreatmentStatusComment"], "0220" : ["SQ", "FractionGroupSummarySequence"], "0223" : ["IS", "ReferencedFractionNumber"], "0224" : ["CS", "FractionGroupType"], "0230" : ["CS", "BeamStopperPosition"], "0240" : ["SQ", "FractionStatusSummarySequence"], "0250" : ["DA", "TreatmentDate"], "0251" : ["TM", "TreatmentTime"] }, "300A" : { "0002" : ["SH", "RTPlanLabel"], "0003" : ["LO", "RTPlanName"], "0004" : ["ST", "RTPlanDescription"], "0006" : ["DA", "RTPlanDate"], "0007" : ["TM", "RTPlanTime"], "0009" : ["LO", "TreatmentProtocols"], "000A" : ["CS", "PlanIntent"], "000B" : ["LO", "TreatmentSites"], "000C" : ["CS", "RTPlanGeometry"], "000E" : ["ST", "PrescriptionDescription"], "0010" : ["SQ", "DoseReferenceSequence"], "0012" : ["IS", "DoseReferenceNumber"], "0013" : ["UI", "DoseReferenceUID"], "0014" : ["CS", "DoseReferenceStructureType"], "0015" : ["CS", "NominalBeamEnergyUnit"], "0016" : ["LO", "DoseReferenceDescription"], "0018" : ["DS", "DoseReferencePointCoordinates"], "001A" : ["DS", "NominalPriorDose"], "0020" : ["CS", "DoseReferenceType"], "0021" : ["DS", "ConstraintWeight"], "0022" : ["DS", "DeliveryWarningDose"], "0023" : ["DS", "DeliveryMaximumDose"], "0025" : ["DS", "TargetMinimumDose"], "0026" : ["DS", "TargetPrescriptionDose"], "0027" : ["DS", "TargetMaximumDose"], "0028" : ["DS", "TargetUnderdoseVolumeFraction"], "002A" : ["DS", "OrganAtRiskFullVolumeDose"], "002B" : ["DS", "OrganAtRiskLimitDose"], "002C" : ["DS", "OrganAtRiskMaximumDose"], "002D" : ["DS", "OrganAtRiskOverdoseVolumeFraction"], "0040" : ["SQ", "ToleranceTableSequence"], "0042" : ["IS", "ToleranceTableNumber"], "0043" : ["SH", "ToleranceTableLabel"], "0044" : ["DS", "GantryAngleTolerance"], "0046" : ["DS", "BeamLimitingDeviceAngleTolerance"], "0048" : ["SQ", "BeamLimitingDeviceToleranceSequence"], "004A" : ["DS", "BeamLimitingDevicePositionTolerance"], "004B" : ["FL", "SnoutPositionTolerance"], "004C" : ["DS", "PatientSupportAngleTolerance"], "004E" : ["DS", "TableTopEccentricAngleTolerance"], "004F" : ["FL", "TableTopPitchAngleTolerance"], "0050" : ["FL", "TableTopRollAngleTolerance"], "0051" : ["DS", "TableTopVerticalPositionTolerance"], "0052" : ["DS", "TableTopLongitudinalPositionTolerance"], "0053" : ["DS", "TableTopLateralPositionTolerance"], "0055" : ["CS", "RTPlanRelationship"], "0070" : ["SQ", "FractionGroupSequence"], "0071" : ["IS", "FractionGroupNumber"], "0072" : ["LO", "FractionGroupDescription"], "0078" : ["IS", "NumberOfFractionsPlanned"], "0079" : ["IS", "NumberOfFractionPatternDigitsPerDay"], "007A" : ["IS", "RepeatFractionCycleLength"], "007B" : ["LT", "FractionPattern"], "0080" : ["IS", "NumberOfBeams"], "0082" : ["DS", "BeamDoseSpecificationPoint"], "0084" : ["DS", "BeamDose"], "0086" : ["DS", "BeamMeterset"], "0088" : ["FL", "BeamDosePointDepth"], "0089" : ["FL", "BeamDosePointEquivalentDepth"], "008A" : ["FL", "BeamDosePointSSD"], "00A0" : ["IS", "NumberOfBrachyApplicationSetups"], "00A2" : ["DS", "BrachyApplicationSetupDoseSpecificationPoint"], "00A4" : ["DS", "BrachyApplicationSetupDose"], "00B0" : ["SQ", "BeamSequence"], "00B2" : ["SH", "TreatmentMachineName"], "00B3" : ["CS", "PrimaryDosimeterUnit"], "00B4" : ["DS", "SourceAxisDistance"], "00B6" : ["SQ", "BeamLimitingDeviceSequence"], "00B8" : ["CS", "RTBeamLimitingDeviceType"], "00BA" : ["DS", "SourceToBeamLimitingDeviceDistance"], "00BB" : ["FL", "IsocenterToBeamLimitingDeviceDistance"], "00BC" : ["IS", "NumberOfLeafJawPairs"], "00BE" : ["DS", "LeafPositionBoundaries"], "00C0" : ["IS", "BeamNumber"], "00C2" : ["LO", "BeamName"], "00C3" : ["ST", "BeamDescription"], "00C4" : ["CS", "BeamType"], "00C6" : ["CS", "RadiationType"], "00C7" : ["CS", "HighDoseTechniqueType"], "00C8" : ["IS", "ReferenceImageNumber"], "00CA" : ["SQ", "PlannedVerificationImageSequence"], "00CC" : ["LO", "ImagingDeviceSpecificAcquisitionParameters"], "00CE" : ["CS", "TreatmentDeliveryType"], "00D0" : ["IS", "NumberOfWedges"], "00D1" : ["SQ", "WedgeSequence"], "00D2" : ["IS", "WedgeNumber"], "00D3" : ["CS", "WedgeType"], "00D4" : ["SH", "WedgeID"], "00D5" : ["IS", "WedgeAngle"], "00D6" : ["DS", "WedgeFactor"], "00D7" : ["FL", "TotalWedgeTrayWaterEquivalentThickness"], "00D8" : ["DS", "WedgeOrientation"], "00D9" : ["FL", "IsocenterToWedgeTrayDistance"], "00DA" : ["DS", "SourceToWedgeTrayDistance"], "00DB" : ["FL", "WedgeThinEdgePosition"], "00DC" : ["SH", "BolusID"], "00DD" : ["ST", "BolusDescription"], "00E0" : ["IS", "NumberOfCompensators"], "00E1" : ["SH", "MaterialID"], "00E2" : ["DS", "TotalCompensatorTrayFactor"], "00E3" : ["SQ", "CompensatorSequence"], "00E4" : ["IS", "CompensatorNumber"], "00E5" : ["SH", "CompensatorID"], "00E6" : ["DS", "SourceToCompensatorTrayDistance"], "00E7" : ["IS", "CompensatorRows"], "00E8" : ["IS", "CompensatorColumns"], "00E9" : ["DS", "CompensatorPixelSpacing"], "00EA" : ["DS", "CompensatorPosition"], "00EB" : ["DS", "CompensatorTransmissionData"], "00EC" : ["DS", "CompensatorThicknessData"], "00ED" : ["IS", "NumberOfBoli"], "00EE" : ["CS", "CompensatorType"], "00F0" : ["IS", "NumberOfBlocks"], "00F2" : ["DS", "TotalBlockTrayFactor"], "00F3" : ["FL", "TotalBlockTrayWaterEquivalentThickness"], "00F4" : ["SQ", "BlockSequence"], "00F5" : ["SH", "BlockTrayID"], "00F6" : ["DS", "SourceToBlockTrayDistance"], "00F7" : ["FL", "IsocenterToBlockTrayDistance"], "00F8" : ["CS", "BlockType"], "00F9" : ["LO", "AccessoryCode"], "00FA" : ["CS", "BlockDivergence"], "00FB" : ["CS", "BlockMountingPosition"], "00FC" : ["IS", "BlockNumber"], "00FE" : ["LO", "BlockName"], "0100" : ["DS", "BlockThickness"], "0102" : ["DS", "BlockTransmission"], "0104" : ["IS", "BlockNumberOfPoints"], "0106" : ["DS", "BlockData"], "0107" : ["SQ", "ApplicatorSequence"], "0108" : ["SH", "ApplicatorID"], "0109" : ["CS", "ApplicatorType"], "010A" : ["LO", "ApplicatorDescription"], "010C" : ["DS", "CumulativeDoseReferenceCoefficient"], "010E" : ["DS", "FinalCumulativeMetersetWeight"], "0110" : ["IS", "NumberOfControlPoints"], "0111" : ["SQ", "ControlPointSequence"], "0112" : ["IS", "ControlPointIndex"], "0114" : ["DS", "NominalBeamEnergy"], "0115" : ["DS", "DoseRateSet"], "0116" : ["SQ", "WedgePositionSequence"], "0118" : ["CS", "WedgePosition"], "011A" : ["SQ", "BeamLimitingDevicePositionSequence"], "011C" : ["DS", "LeafJawPositions"], "011E" : ["DS", "GantryAngle"], "011F" : ["CS", "GantryRotationDirection"], "0120" : ["DS", "BeamLimitingDeviceAngle"], "0121" : ["CS", "BeamLimitingDeviceRotationDirection"], "0122" : ["DS", "PatientSupportAngle"], "0123" : ["CS", "PatientSupportRotationDirection"], "0124" : ["DS", "TableTopEccentricAxisDistance"], "0125" : ["DS", "TableTopEccentricAngle"], "0126" : ["CS", "TableTopEccentricRotationDirection"], "0128" : ["DS", "TableTopVerticalPosition"], "0129" : ["DS", "TableTopLongitudinalPosition"], "012A" : ["DS", "TableTopLateralPosition"], "012C" : ["DS", "IsocenterPosition"], "012E" : ["DS", "SurfaceEntryPoint"], "0130" : ["DS", "SourceToSurfaceDistance"], "0134" : ["DS", "CumulativeMetersetWeight"], "0140" : ["FL", "TableTopPitchAngle"], "0142" : ["CS", "TableTopPitchRotationDirection"], "0144" : ["FL", "TableTopRollAngle"], "0146" : ["CS", "TableTopRollRotationDirection"], "0148" : ["FL", "HeadFixationAngle"], "014A" : ["FL", "GantryPitchAngle"], "014C" : ["CS", "GantryPitchRotationDirection"], "014E" : ["FL", "GantryPitchAngleTolerance"], "0180" : ["SQ", "PatientSetupSequence"], "0182" : ["IS", "PatientSetupNumber"], "0183" : ["LO", "PatientSetupLabel"], "0184" : ["LO", "PatientAdditionalPosition"], "0190" : ["SQ", "FixationDeviceSequence"], "0192" : ["CS", "FixationDeviceType"], "0194" : ["SH", "FixationDeviceLabel"], "0196" : ["ST", "FixationDeviceDescription"], "0198" : ["SH", "FixationDevicePosition"], "0199" : ["FL", "FixationDevicePitchAngle"], "019A" : ["FL", "FixationDeviceRollAngle"], "01A0" : ["SQ", "ShieldingDeviceSequence"], "01A2" : ["CS", "ShieldingDeviceType"], "01A4" : ["SH", "ShieldingDeviceLabel"], "01A6" : ["ST", "ShieldingDeviceDescription"], "01A8" : ["SH", "ShieldingDevicePosition"], "01B0" : ["CS", "SetupTechnique"], "01B2" : ["ST", "SetupTechniqueDescription"], "01B4" : ["SQ", "SetupDeviceSequence"], "01B6" : ["CS", "SetupDeviceType"], "01B8" : ["SH", "SetupDeviceLabel"], "01BA" : ["ST", "SetupDeviceDescription"], "01BC" : ["DS", "SetupDeviceParameter"], "01D0" : ["ST", "SetupReferenceDescription"], "01D2" : ["DS", "TableTopVerticalSetupDisplacement"], "01D4" : ["DS", "TableTopLongitudinalSetupDisplacement"], "01D6" : ["DS", "TableTopLateralSetupDisplacement"], "0200" : ["CS", "BrachyTreatmentTechnique"], "0202" : ["CS", "BrachyTreatmentType"], "0206" : ["SQ", "TreatmentMachineSequence"], "0210" : ["SQ", "SourceSequence"], "0212" : ["IS", "SourceNumber"], "0214" : ["CS", "SourceType"], "0216" : ["LO", "SourceManufacturer"], "0218" : ["DS", "ActiveSourceDiameter"], "021A" : ["DS", "ActiveSourceLength"], "0222" : ["DS", "SourceEncapsulationNominalThickness"], "0224" : ["DS", "SourceEncapsulationNominalTransmission"], "0226" : ["LO", "SourceIsotopeName"], "0228" : ["DS", "SourceIsotopeHalfLife"], "0229" : ["CS", "SourceStrengthUnits"], "022A" : ["DS", "ReferenceAirKermaRate"], "022B" : ["DS", "SourceStrength"], "022C" : ["DA", "SourceStrengthReferenceDate"], "022E" : ["TM", "SourceStrengthReferenceTime"], "0230" : ["SQ", "ApplicationSetupSequence"], "0232" : ["CS", "ApplicationSetupType"], "0234" : ["IS", "ApplicationSetupNumber"], "0236" : ["LO", "ApplicationSetupName"], "0238" : ["LO", "ApplicationSetupManufacturer"], "0240" : ["IS", "TemplateNumber"], "0242" : ["SH", "TemplateType"], "0244" : ["LO", "TemplateName"], "0250" : ["DS", "TotalReferenceAirKerma"], "0260" : ["SQ", "BrachyAccessoryDeviceSequence"], "0262" : ["IS", "BrachyAccessoryDeviceNumber"], "0263" : ["SH", "BrachyAccessoryDeviceID"], "0264" : ["CS", "BrachyAccessoryDeviceType"], "0266" : ["LO", "BrachyAccessoryDeviceName"], "026A" : ["DS", "BrachyAccessoryDeviceNominalThickness"], "026C" : ["DS", "BrachyAccessoryDeviceNominalTransmission"], "0280" : ["SQ", "ChannelSequence"], "0282" : ["IS", "ChannelNumber"], "0284" : ["DS", "ChannelLength"], "0286" : ["DS", "ChannelTotalTime"], "0288" : ["CS", "SourceMovementType"], "028A" : ["IS", "NumberOfPulses"], "028C" : ["DS", "PulseRepetitionInterval"], "0290" : ["IS", "SourceApplicatorNumber"], "0291" : ["SH", "SourceApplicatorID"], "0292" : ["CS", "SourceApplicatorType"], "0294" : ["LO", "SourceApplicatorName"], "0296" : ["DS", "SourceApplicatorLength"], "0298" : ["LO", "SourceApplicatorManufacturer"], "029C" : ["DS", "SourceApplicatorWallNominalThickness"], "029E" : ["DS", "SourceApplicatorWallNominalTransmission"], "02A0" : ["DS", "SourceApplicatorStepSize"], "02A2" : ["IS", "TransferTubeNumber"], "02A4" : ["DS", "TransferTubeLength"], "02B0" : ["SQ", "ChannelShieldSequence"], "02B2" : ["IS", "ChannelShieldNumber"], "02B3" : ["SH", "ChannelShieldID"], "02B4" : ["LO", "ChannelShieldName"], "02B8" : ["DS", "ChannelShieldNominalThickness"], "02BA" : ["DS", "ChannelShieldNominalTransmission"], "02C8" : ["DS", "FinalCumulativeTimeWeight"], "02D0" : ["SQ", "BrachyControlPointSequence"], "02D2" : ["DS", "ControlPointRelativePosition"], "02D4" : ["DS", "ControlPoint3DPosition"], "02D6" : ["DS", "CumulativeTimeWeight"], "02E0" : ["CS", "CompensatorDivergence"], "02E1" : ["CS", "CompensatorMountingPosition"], "02E2" : ["DS", "SourceToCompensatorDistance"], "02E3" : ["FL", "TotalCompensatorTrayWaterEquivalentThickness"], "02E4" : ["FL", "IsocenterToCompensatorTrayDistance"], "02E5" : ["FL", "CompensatorColumnOffset"], "02E6" : ["FL", "IsocenterToCompensatorDistances"], "02E7" : ["FL", "CompensatorRelativeStoppingPowerRatio"], "02E8" : ["FL", "CompensatorMillingToolDiameter"], "02EA" : ["SQ", "IonRangeCompensatorSequence"], "02EB" : ["LT", "CompensatorDescription"], "0302" : ["IS", "RadiationMassNumber"], "0304" : ["IS", "RadiationAtomicNumber"], "0306" : ["SS", "RadiationChargeState"], "0308" : ["CS", "ScanMode"], "030A" : ["FL", "VirtualSourceAxisDistances"], "030C" : ["SQ", "SnoutSequence"], "030D" : ["FL", "SnoutPosition"], "030F" : ["SH", "SnoutID"], "0312" : ["IS", "NumberOfRangeShifters"], "0314" : ["SQ", "RangeShifterSequence"], "0316" : ["IS", "RangeShifterNumber"], "0318" : ["SH", "RangeShifterID"], "0320" : ["CS", "RangeShifterType"], "0322" : ["LO", "RangeShifterDescription"], "0330" : ["IS", "NumberOfLateralSpreadingDevices"], "0332" : ["SQ", "LateralSpreadingDeviceSequence"], "0334" : ["IS", "LateralSpreadingDeviceNumber"], "0336" : ["SH", "LateralSpreadingDeviceID"], "0338" : ["CS", "LateralSpreadingDeviceType"], "033A" : ["LO", "LateralSpreadingDeviceDescription"], "033C" : ["FL", "LateralSpreadingDeviceWaterEquivalentThickness"], "0340" : ["IS", "NumberOfRangeModulators"], "0342" : ["SQ", "RangeModulatorSequence"], "0344" : ["IS", "RangeModulatorNumber"], "0346" : ["SH", "RangeModulatorID"], "0348" : ["CS", "RangeModulatorType"], "034A" : ["LO", "RangeModulatorDescription"], "034C" : ["SH", "BeamCurrentModulationID"], "0350" : ["CS", "PatientSupportType"], "0352" : ["SH", "PatientSupportID"], "0354" : ["LO", "PatientSupportAccessoryCode"], "0356" : ["FL", "FixationLightAzimuthalAngle"], "0358" : ["FL", "FixationLightPolarAngle"], "035A" : ["FL", "MetersetRate"], "0360" : ["SQ", "RangeShifterSettingsSequence"], "0362" : ["LO", "RangeShifterSetting"], "0364" : ["FL", "IsocenterToRangeShifterDistance"], "0366" : ["FL", "RangeShifterWaterEquivalentThickness"], "0370" : ["SQ", "LateralSpreadingDeviceSettingsSequence"], "0372" : ["LO", "LateralSpreadingDeviceSetting"], "0374" : ["FL", "IsocenterToLateralSpreadingDeviceDistance"], "0380" : ["SQ", "RangeModulatorSettingsSequence"], "0382" : ["FL", "RangeModulatorGatingStartValue"], "0384" : ["FL", "RangeModulatorGatingStopValue"], "0386" : ["FL", "RangeModulatorGatingStartWaterEquivalentThickness"], "0388" : ["FL", "RangeModulatorGatingStopWaterEquivalentThickness"], "038A" : ["FL", "IsocenterToRangeModulatorDistance"], "0390" : ["SH", "ScanSpotTuneID"], "0392" : ["IS", "NumberOfScanSpotPositions"], "0394" : ["FL", "ScanSpotPositionMap"], "0396" : ["FL", "ScanSpotMetersetWeights"], "0398" : ["FL", "ScanningSpotSize"], "039A" : ["IS", "NumberOfPaintings"], "03A0" : ["SQ", "IonToleranceTableSequence"], "03A2" : ["SQ", "IonBeamSequence"], "03A4" : ["SQ", "IonBeamLimitingDeviceSequence"], "03A6" : ["SQ", "IonBlockSequence"], "03A8" : ["SQ", "IonControlPointSequence"], "03AA" : ["SQ", "IonWedgeSequence"], "03AC" : ["SQ", "IonWedgePositionSequence"], "0401" : ["SQ", "ReferencedSetupImageSequence"], "0402" : ["ST", "SetupImageComment"], "0410" : ["SQ", "MotionSynchronizationSequence"], "0412" : ["FL", "ControlPointOrientation"], "0420" : ["SQ", "GeneralAccessorySequence"], "0421" : ["SH", "GeneralAccessoryID"], "0422" : ["ST", "GeneralAccessoryDescription"], "0423" : ["CS", "GeneralAccessoryType"], "0424" : ["IS", "GeneralAccessoryNumber"], "0431" : ["SQ", "ApplicatorGeometrySequence"], "0432" : ["CS", "ApplicatorApertureShape"], "0433" : ["FL", "ApplicatorOpening"], "0434" : ["FL", "ApplicatorOpeningX"], "0435" : ["FL", "ApplicatorOpeningY"], "0436" : ["FL", "SourceToApplicatorMountingPositionDistance"] }, "300C" : { "0002" : ["SQ", "ReferencedRTPlanSequence"], "0004" : ["SQ", "ReferencedBeamSequence"], "0006" : ["IS", "ReferencedBeamNumber"], "0007" : ["IS", "ReferencedReferenceImageNumber"], "0008" : ["DS", "StartCumulativeMetersetWeight"], "0009" : ["DS", "EndCumulativeMetersetWeight"], "000A" : ["SQ", "ReferencedBrachyApplicationSetupSequence"], "000C" : ["IS", "ReferencedBrachyApplicationSetupNumber"], "000E" : ["IS", "ReferencedSourceNumber"], "0020" : ["SQ", "ReferencedFractionGroupSequence"], "0022" : ["IS", "ReferencedFractionGroupNumber"], "0040" : ["SQ", "ReferencedVerificationImageSequence"], "0042" : ["SQ", "ReferencedReferenceImageSequence"], "0050" : ["SQ", "ReferencedDoseReferenceSequence"], "0051" : ["IS", "ReferencedDoseReferenceNumber"], "0055" : ["SQ", "BrachyReferencedDoseReferenceSequence"], "0060" : ["SQ", "ReferencedStructureSetSequence"], "006A" : ["IS", "ReferencedPatientSetupNumber"], "0080" : ["SQ", "ReferencedDoseSequence"], "00A0" : ["IS", "ReferencedToleranceTableNumber"], "00B0" : ["SQ", "ReferencedBolusSequence"], "00C0" : ["IS", "ReferencedWedgeNumber"], "00D0" : ["IS", "ReferencedCompensatorNumber"], "00E0" : ["IS", "ReferencedBlockNumber"], "00F0" : ["IS", "ReferencedControlPointIndex"], "00F2" : ["SQ", "ReferencedControlPointSequence"], "00F4" : ["IS", "ReferencedStartControlPointIndex"], "00F6" : ["IS", "ReferencedStopControlPointIndex"], "0100" : ["IS", "ReferencedRangeShifterNumber"], "0102" : ["IS", "ReferencedLateralSpreadingDeviceNumber"], "0104" : ["IS", "ReferencedRangeModulatorNumber"] }, "300E" : { "0002" : ["CS", "ApprovalStatus"], "0004" : ["DA", "ReviewDate"], "0005" : ["TM", "ReviewTime"], "0008" : ["PN", "ReviewerName"] }, "4000" : { "0010" : ["LT", "Arbitrary"], "4000" : ["LT", "TextComments"] }, "4008" : { "0040" : ["SH", "ResultsID"], "0042" : ["LO", "ResultsIDIssuer"], "0050" : ["SQ", "ReferencedInterpretationSequence"], "00FF" : ["CS", "ReportProductionStatusTrial"], "0100" : ["DA", "InterpretationRecordedDate"], "0101" : ["TM", "InterpretationRecordedTime"], "0102" : ["PN", "InterpretationRecorder"], "0103" : ["LO", "ReferenceToRecordedSound"], "0108" : ["DA", "InterpretationTranscriptionDate"], "0109" : ["TM", "InterpretationTranscriptionTime"], "010A" : ["PN", "InterpretationTranscriber"], "010B" : ["ST", "InterpretationText"], "010C" : ["PN", "InterpretationAuthor"], "0111" : ["SQ", "InterpretationApproverSequence"], "0112" : ["DA", "InterpretationApprovalDate"], "0113" : ["TM", "InterpretationApprovalTime"], "0114" : ["PN", "PhysicianApprovingInterpretation"], "0115" : ["LT", "InterpretationDiagnosisDescription"], "0117" : ["SQ", "InterpretationDiagnosisCodeSequence"], "0118" : ["SQ", "ResultsDistributionListSequence"], "0119" : ["PN", "DistributionName"], "011A" : ["LO", "DistributionAddress"], "0200" : ["SH", "InterpretationID"], "0202" : ["LO", "InterpretationIDIssuer"], "0210" : ["CS", "InterpretationTypeID"], "0212" : ["CS", "InterpretationStatusID"], "0300" : ["ST", "Impressions"], "4000" : ["ST", "ResultsComments"] }, "4010" : { "0001" : ["CS", "LowEnergyDetectors"], "0002" : ["CS", "HighEnergyDetectors"], "0004" : ["SQ", "DetectorGeometrySequence"], "1001" : ["SQ", "ThreatROIVoxelSequence"], "1004" : ["FL", "ThreatROIBase"], "1005" : ["FL", "ThreatROIExtents"], "1006" : ["OB", "ThreatROIBitmap"], "1007" : ["SH", "RouteSegmentID"], "1008" : ["CS", "GantryType"], "1009" : ["CS", "OOIOwnerType"], "100A" : ["SQ", "RouteSegmentSequence"], "1010" : ["US", "PotentialThreatObjectID"], "1011" : ["SQ", "ThreatSequence"], "1012" : ["CS", "ThreatCategory"], "1013" : ["LT", "ThreatCategoryDescription"], "1014" : ["CS", "ATDAbilityAssessment"], "1015" : ["CS", "ATDAssessmentFlag"], "1016" : ["FL", "ATDAssessmentProbability"], "1017" : ["FL", "Mass"], "1018" : ["FL", "Density"], "1019" : ["FL", "ZEffective"], "101A" : ["SH", "BoardingPassID"], "101B" : ["FL", "CenterOfMass"], "101C" : ["FL", "CenterOfPTO"], "101D" : ["FL", "BoundingPolygon"], "101E" : ["SH", "RouteSegmentStartLocationID"], "101F" : ["SH", "RouteSegmentEndLocationID"], "1020" : ["CS", "RouteSegmentLocationIDType"], "1021" : ["CS", "AbortReason"], "1023" : ["FL", "VolumeOfPTO"], "1024" : ["CS", "AbortFlag"], "1025" : ["DT", "RouteSegmentStartTime"], "1026" : ["DT", "RouteSegmentEndTime"], "1027" : ["CS", "TDRType"], "1028" : ["CS", "InternationalRouteSegment"], "1029" : ["LO", "ThreatDetectionAlgorithmandVersion"], "102A" : ["SH", "AssignedLocation"], "102B" : ["DT", "AlarmDecisionTime"], "1031" : ["CS", "AlarmDecision"], "1033" : ["US", "NumberOfTotalObjects"], "1034" : ["US", "NumberOfAlarmObjects"], "1037" : ["SQ", "PTORepresentationSequence"], "1038" : ["SQ", "ATDAssessmentSequence"], "1039" : ["CS", "TIPType"], "103A" : ["CS", "DICOSVersion"], "1041" : ["DT", "OOIOwnerCreationTime"], "1042" : ["CS", "OOIType"], "1043" : ["FL", "OOISize"], "1044" : ["CS", "AcquisitionStatus"], "1045" : ["SQ", "BasisMaterialsCodeSequence"], "1046" : ["CS", "PhantomType"], "1047" : ["SQ", "OOIOwnerSequence"], "1048" : ["CS", "ScanType"], "1051" : ["LO", "ItineraryID"], "1052" : ["SH", "ItineraryIDType"], "1053" : ["LO", "ItineraryIDAssigningAuthority"], "1054" : ["SH", "RouteID"], "1055" : ["SH", "RouteIDAssigningAuthority"], "1056" : ["CS", "InboundArrivalType"], "1058" : ["SH", "CarrierID"], "1059" : ["CS", "CarrierIDAssigningAuthority"], "1060" : ["FL", "SourceOrientation"], "1061" : ["FL", "SourcePosition"], "1062" : ["FL", "BeltHeight"], "1064" : ["SQ", "AlgorithmRoutingCodeSequence"], "1067" : ["CS", "TransportClassification"], "1068" : ["LT", "OOITypeDescriptor"], "1069" : ["FL", "TotalProcessingTime"], "106C" : ["OB", "DetectorCalibrationData"] } }; /*** Static Methods ***/ daikon.Dictionary.getVR = function (group, element) { var vr, elementData, groupData; groupData = daikon.Dictionary.dict[daikon.Utils.dec2hex(group)]; if (groupData) { elementData = groupData[daikon.Utils.dec2hex(element)]; if (elementData) { vr = elementData[0]; } } if (!vr) { groupData = daikon.Dictionary.dictPrivate[daikon.Utils.dec2hex(group)]; if (groupData) { elementData = groupData[daikon.Utils.dec2hex(element)]; if (elementData) { vr = elementData[0]; } } } if (!vr) { vr = 'OB'; } return vr; }; daikon.Dictionary.getDescription = function (group, element) { var des, elementData, groupData; groupData = daikon.Dictionary.dict[daikon.Utils.dec2hex(group)]; if (groupData) { elementData = groupData[daikon.Utils.dec2hex(element)]; if (elementData) { des = elementData[1]; } } if (!des) { groupData = daikon.Dictionary.dictPrivate[daikon.Utils.dec2hex(group)]; if (groupData) { elementData = groupData[daikon.Utils.dec2hex(element)]; if (elementData) { des = elementData[1]; } } } if (!des) { des = 'PrivateData'; } return des; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Dictionary; } /*jslint browser: true, node: true */ /*global require, module */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Tag = daikon.Tag || ((typeof require !== 'undefined') ? require('./tag.js') : null); daikon.Parser = daikon.Parser || ((typeof require !== 'undefined') ? require('./parser.js') : null); /*** Constructor ***/ daikon.Image = daikon.Image || function () { this.tags = {}; this.littleEndian = false; this.index = -1; }; /*** Static Pseudo-constants ***/ daikon.Image.SLICE_DIRECTION_UNKNOWN = -1; daikon.Image.SLICE_DIRECTION_AXIAL = 2; daikon.Image.SLICE_DIRECTION_CORONAL = 1; daikon.Image.SLICE_DIRECTION_SAGITTAL = 0; daikon.Image.SLICE_DIRECTION_OBLIQUE = 3; daikon.Image.OBLIQUITY_THRESHOLD_COSINE_VALUE = 0.8; daikon.Image.BYTE_TYPE_UNKNOWN = 0; daikon.Image.BYTE_TYPE_BINARY = 1; daikon.Image.BYTE_TYPE_INTEGER = 2; daikon.Image.BYTE_TYPE_INTEGER_UNSIGNED = 3; daikon.Image.BYTE_TYPE_FLOAT = 4; daikon.Image.BYTE_TYPE_COMPLEX = 5; daikon.Image.BYTE_TYPE_RGB = 6; /*** Static Methods ***/ daikon.Image.getSingleValueSafely = function (tag, index) { if (tag && tag.value) { return tag.value[index]; } return null; }; daikon.Image.getValueSafely = function (tag) { if (tag) { return tag.value; } return null; }; // originally from: http://public.kitware.com/pipermail/insight-users/2005-March/012246.html daikon.Image.getMajorAxisFromPatientRelativeDirectionCosine = function(x, y, z) { var axis, orientationX, orientationY, orientationZ, absX, absY, absZ; orientationX = (x < 0) ? "R" : "L"; orientationY = (y < 0) ? "A" : "P"; orientationZ = (z < 0) ? "F" : "H"; absX = Math.abs(x); absY = Math.abs(y); absZ = Math.abs(z); // The tests here really don't need to check the other dimensions, // just the threshold, since the sum of the squares should be == 1.0 // but just in case ... if ((absX > daikon.Image.OBLIQUITY_THRESHOLD_COSINE_VALUE) && (absX > absY) && (absX > absZ)) { axis = orientationX; } else if ((absY > daikon.Image.OBLIQUITY_THRESHOLD_COSINE_VALUE) && (absY > absX) && (absY > absZ)) { axis = orientationY; } else if ((absZ > daikon.Image.OBLIQUITY_THRESHOLD_COSINE_VALUE) && (absZ > absX) && (absZ > absY)) { axis = orientationZ; } else { axis = null; } return axis; }; /*** Prototype Methods ***/ daikon.Image.prototype.getCols = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_COLS[0], daikon.Tag.TAG_COLS[1]), 0); }; daikon.Image.prototype.getRows = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_ROWS[0], daikon.Tag.TAG_ROWS[1]), 0); }; daikon.Image.prototype.getSeriesDescription = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SERIES_DESCRIPTION[0], daikon.Tag.TAG_SERIES_DESCRIPTION[1]), 0); }; daikon.Image.prototype.getSeriesInstanceUID = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SERIES_INSTANCE_UID[0], daikon.Tag.TAG_SERIES_INSTANCE_UID[1]), 0); }; daikon.Image.prototype.getSeriesNumber = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SERIES_NUMBER[0], daikon.Tag.TAG_SERIES_NUMBER[1]), 0); }; daikon.Image.prototype.getEchoNumber = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_ECHO_NUMBER[0], daikon.Tag.TAG_ECHO_NUMBER[1]), 0); }; daikon.Image.prototype.getImagePosition = function () { return daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_POSITION[0], daikon.Tag.TAG_IMAGE_POSITION[1])); }; daikon.Image.prototype.getImagePositionSliceDir = function (sliceDir) { var imagePos = daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_POSITION[0], daikon.Tag.TAG_IMAGE_POSITION[1])); if (imagePos) { if (sliceDir >= 0) { return imagePos[sliceDir]; } } return 0; }; daikon.Image.prototype.getSliceLocation = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SLICE_LOCATION[0], daikon.Tag.TAG_SLICE_LOCATION[1]), 0); }; daikon.Image.prototype.getSliceLocationVector = function () { return daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_SLICE_LOCATION_VECTOR[0], daikon.Tag.TAG_SLICE_LOCATION_VECTOR[1])); }; daikon.Image.prototype.getImageNumber = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_NUM[0], daikon.Tag.TAG_IMAGE_NUM[1]), 0); }; daikon.Image.prototype.getTemporalPosition = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_TEMPORAL_POSITION[0], daikon.Tag.TAG_TEMPORAL_POSITION[1]), 0); }; daikon.Image.prototype.getTemporalNumber = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_NUMBER_TEMPORAL_POSITIONS[0], daikon.Tag.TAG_NUMBER_TEMPORAL_POSITIONS[1]), 0); }; daikon.Image.prototype.getSliceGap = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SLICE_GAP[0], daikon.Tag.TAG_SLICE_GAP[1]), 0); }; daikon.Image.prototype.getSliceThickness = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SLICE_THICKNESS[0], daikon.Tag.TAG_SLICE_THICKNESS[1]), 0); }; daikon.Image.prototype.getImageMax = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_MAX[0], daikon.Tag.TAG_IMAGE_MAX[1]), 0); }; daikon.Image.prototype.getImageMin = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_MIN[0], daikon.Tag.TAG_IMAGE_MIN[1]), 0); }; daikon.Image.prototype.getDataScaleSlope = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_DATA_SCALE_SLOPE[0], daikon.Tag.TAG_DATA_SCALE_SLOPE[1]), 0); }; daikon.Image.prototype.getDataScaleIntercept = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_DATA_SCALE_INTERCEPT[0], daikon.Tag.TAG_DATA_SCALE_INTERCEPT[1]), 0); }; daikon.Image.prototype.getDataScaleElscint = function () { var scale = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_DATA_SCALE_ELSCINT[0], daikon.Tag.TAG_DATA_SCALE_ELSCINT[1]), 0); if (!scale) { scale = 1; } var bandwidth = this.getPixelBandwidth(); scale = Math.sqrt(bandwidth) / (10 * scale); if (scale <= 0) { scale = 1; } return scale; }; daikon.Image.prototype.getWindowWidth = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_WINDOW_WIDTH[0], daikon.Tag.TAG_WINDOW_WIDTH[1]), 0); }; daikon.Image.prototype.getWindowCenter = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_WINDOW_CENTER[0], daikon.Tag.TAG_WINDOW_CENTER[1]), 0); }; daikon.Image.prototype.getPixelBandwidth = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PIXEL_BANDWIDTH[0], daikon.Tag.TAG_PIXEL_BANDWIDTH[1]), 0); }; daikon.Image.prototype.getSeriesId = function () { var des = this.getSeriesDescription(); var uid = this.getSeriesInstanceUID(); var num = this.getSeriesNumber(); var echo = this.getEchoNumber(); var orientation = this.getOrientation(); var id = ""; if (des !== null) { id += (" " + des); } if (uid !== null) { id += (" " + uid); } if (num !== null) { id += (" " + num); } if (echo !== null) { id += (" " + echo); } if (orientation !== null) { id += (" " + orientation); } return id; }; daikon.Image.prototype.getPixelSpacing = function () { return daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_PIXEL_SPACING[0], daikon.Tag.TAG_PIXEL_SPACING[1])); }; daikon.Image.prototype.getImageType = function () { return daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_TYPE[0], daikon.Tag.TAG_IMAGE_TYPE[1])); }; daikon.Image.prototype.getBitsStored = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_BITS_STORED[0], daikon.Tag.TAG_BITS_STORED[1]), 0); }; daikon.Image.prototype.getBitsAllocated = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_BITS_ALLOCATED[0], daikon.Tag.TAG_BITS_ALLOCATED[1]), 0); }; daikon.Image.prototype.getFrameTime = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_FRAME_TIME[0], daikon.Tag.TAG_FRAME_TIME[1]), 0); }; daikon.Image.prototype.getAcquisitionMatrix = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_ACQUISITION_MATRIX[0], daikon.Tag.TAG_ACQUISITION_MATRIX[1]), 0); }; daikon.Image.prototype.getTR = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_TR, daikon.Tag.TAG_TR[1]), 0); }; daikon.Image.prototype.putTag = function (tag) { this.tags[tag.id] = tag; }; daikon.Image.prototype.getTag = function (group, element) { return this.tags[daikon.Tag.createId(group, element)]; }; daikon.Image.prototype.getPixelData = function () { return this.tags[daikon.Tag.createId(daikon.Tag.TAG_PIXEL_DATA[0], daikon.Tag.TAG_PIXEL_DATA[1])]; }; daikon.Image.prototype.hasPixelData = function () { return (this.tags[daikon.Tag.createId(daikon.Tag.TAG_PIXEL_DATA[0], daikon.Tag.TAG_PIXEL_DATA[1])] !== undefined); }; daikon.Image.prototype.clearPixelData = function () { this.tags[daikon.Tag.createId(daikon.Tag.TAG_PIXEL_DATA[0], daikon.Tag.TAG_PIXEL_DATA[1])].value = null; }; daikon.Image.prototype.getOrientation = function () { var orientation = null, dirCos = daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_ORIENTATION[0], daikon.Tag.TAG_IMAGE_ORIENTATION[1])), ctr, spacing, rowSpacing, swapZ, bigRow = 0, bigCol = 0, biggest = 0, orient = ''; if (!dirCos || (dirCos.length !== 6)) { return null; } spacing = this.getPixelSpacing(); if (!spacing) { return null; } rowSpacing = spacing[0]; swapZ = true; for (ctr = 0; ctr < 3; ctr += 1) { if (Math.abs(dirCos[ctr]) > biggest) { biggest = Math.abs(dirCos[ctr]); bigRow = ctr; } } biggest = 0; for (; ctr < 6; ctr += 1) { if (Math.abs(dirCos[ctr]) > biggest) { biggest = Math.abs(dirCos[ctr]); bigCol = ctr; } } switch (bigRow) { case 0: orient += ('X'); if (bigCol === 4) { orient += ("YZ"); } else { orient += ("ZY"); } break; case 1: orient += ('Y'); if (bigCol === 3) { orient += ("XZ"); } else { orient += ("ZX"); } break; case 2: orient += ('Z'); if (bigCol === 3) { orient += ("XY"); } else { orient += ("YX"); } break; default: break; } switch (bigRow) { case 0: if (dirCos[bigRow] > 0.0) { orient += ('-'); } else { orient += ('+'); } if (bigCol === 4) { if (dirCos[bigCol] > 0.0) { orient += ('-'); } else { orient += ('+'); } } else { if (dirCos[bigCol] > 0.0) { orient += ('+'); } else { orient += ('-'); } } break; case 1: if (dirCos[bigRow] > 0.0) { orient += ('-'); } else { orient += ('+'); } if (bigCol === 3) { if (dirCos[bigCol] > 0.0) { orient += ('-'); } else { orient += ('+'); } } else { if (dirCos[bigCol] > 0.0) { orient += ('+'); } else { orient += ('-'); } } break; case 2: if (dirCos[bigRow] > 0.0) { orient += ('+'); } else { orient += ('-'); } //Has to be X or Y so opposite senses if (dirCos[bigCol] > 0.0) { orient += ('-'); } else { orient += ('+'); } break; default: break; } if (rowSpacing === 0.0) { orient += ('+'); orientation = orient; } else { if (swapZ) { switch (orient.charAt(2)) { case 'X': if (rowSpacing > 0.0) { orient += ('-'); } else { orient += ('+'); } break; case 'Y': case 'Z': if (rowSpacing > 0.0) { orient += ('+'); } else { orient += ('-'); } break; default: break; } } else { switch (orient.charAt(2)) { case 'X': if (rowSpacing > 0.0) { orient += ('+'); } else { orient += ('-'); } break; case 'Y': case 'Z': if (rowSpacing > 0.0) { orient += ('-'); } else { orient += ('+'); } break; default: break; } } orientation = orient; } return orientation; }; daikon.Image.prototype.isMosaic = function () { var imageType, labeledAsMosaic = false, canReadAsMosaic, ctr, matSize; imageType = this.getImageType(); if (imageType !== null) { for (ctr = 0; ctr < imageType.length; ctr += 1) { if (imageType[ctr].toUpperCase().indexOf("MOSAIC") !== -1) { labeledAsMosaic = true; break; } } } matSize = this.getAcquisitionMatrix(); canReadAsMosaic = (matSize > 0) && ((matSize < this.getRows()) || (matSize < this.getCols())); return labeledAsMosaic && canReadAsMosaic; }; daikon.Image.prototype.getMosaicCols = function() { return this.getCols() / this.getAcquisitionMatrix(); }; daikon.Image.prototype.getMosaicRows = function() { return this.getRows() / this.getAcquisitionMatrix(); }; daikon.Image.prototype.isElscint = function() { var dataScale = this.getDataScaleElscint(); return ((dataScale !== null) && (dataScale !== 0)); }; daikon.Image.prototype.isCompressed = function() { var transferSyntax = this.getTransferSyntax(); if (transferSyntax) { if (transferSyntax.indexOf(daikon.Parser.TRANSFER_SYNTAX_COMPRESSION_JPEG) !== -1) { return true; } else if (transferSyntax.indexOf(daikon.Parser.TRANSFER_SYNTAX_COMPRESSION_RLE) !== -1) { return true; } } return false; }; daikon.Image.prototype.getNumberOfFrames = function () { var value = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_NUMBER_OF_FRAMES[0], daikon.Tag.TAG_NUMBER_OF_FRAMES[1]), 0); if (value !== null) { return value; } return 1; }; daikon.Image.prototype.getNumberOfImplicitFrames = function () { var pixelData, length, size; pixelData = this.getPixelData(); length = pixelData.offsetEnd - pixelData.offsetValue; size = this.getCols() * this.getRows() * (parseInt(this.getBitsAllocated() / 8)); return parseInt(length / size); }; daikon.Image.prototype.getPixelRepresentation = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PIXEL_REPRESENTATION[0], daikon.Tag.TAG_PIXEL_REPRESENTATION[1]), 0); }; daikon.Image.prototype.getPhotometricInterpretation = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PHOTOMETRIC_INTERPRETATION[0], daikon.Tag.TAG_PHOTOMETRIC_INTERPRETATION[1]), 0); }; daikon.Image.prototype.getPatientName = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PATIENT_NAME[0], daikon.Tag.TAG_PATIENT_NAME[1]), 0); }; daikon.Image.prototype.getPatientID = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PATIENT_ID[0], daikon.Tag.TAG_PATIENT_ID[1]), 0); }; daikon.Image.prototype.getStudyTime = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_STUDY_TIME[0], daikon.Tag.TAG_STUDY_TIME[1]), 0); }; daikon.Image.prototype.getTransferSyntax = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_TRANSFER_SYNTAX[0], daikon.Tag.TAG_TRANSFER_SYNTAX[1]), 0); }; daikon.Image.prototype.getStudyDate = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_STUDY_DATE[0], daikon.Tag.TAG_STUDY_DATE[1]), 0); }; daikon.Image.prototype.getImageDescription = function () { var value, string = ""; value = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_STUDY_DES[0], daikon.Tag.TAG_STUDY_DES[1]), 0); if (value !== null) { string += (" " + value); } value = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SERIES_DESCRIPTION[0], daikon.Tag.TAG_SERIES_DESCRIPTION[1]), 0); if (value !== null) { string += (" " + value); } value = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_COMMENTS[0], daikon.Tag.TAG_IMAGE_COMMENTS[1]), 0); if (value !== null) { string += (" " + value); } return string.trim(); }; daikon.Image.prototype.getDataType = function () { var interp, dataType; dataType = this.getPixelRepresentation(); if (dataType === null) { return daikon.Image.BYTE_TYPE_UNKNOWN; } interp = this.getPhotometricInterpretation(); if (interp !== null) { if (interp.trim() === "RGB") { return daikon.Image.BYTE_TYPE_RGB; } } if (dataType === 0) { return daikon.Image.BYTE_TYPE_INTEGER_UNSIGNED; } else if (dataType === 1) { return daikon.Image.BYTE_TYPE_INTEGER; } else { return daikon.Image.BYTE_TYPE_UNKNOWN; } }; // originally from: http://public.kitware.com/pipermail/insight-users/2005-March/012246.html daikon.Image.prototype.getAcquiredSliceDirection = function () { var dirCos, rowAxis, colAxis, label; dirCos = daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_ORIENTATION[0], daikon.Tag.TAG_IMAGE_ORIENTATION[1])); if (!dirCos || (dirCos.length !== 6)) { return daikon.Image.SLICE_DIRECTION_UNKNOWN; } rowAxis = daikon.Image.getMajorAxisFromPatientRelativeDirectionCosine(dirCos[0], dirCos[1], dirCos[2]); colAxis = daikon.Image.getMajorAxisFromPatientRelativeDirectionCosine(dirCos[3], dirCos[4], dirCos[5]); if ((rowAxis !== null) && (colAxis !== null)) { if (((rowAxis === "R") || (rowAxis === "L")) && ((colAxis === "A") || (colAxis === "P"))) { label = daikon.Image.SLICE_DIRECTION_AXIAL; } else if (((colAxis === "R") || (colAxis === "L")) && ((rowAxis === "A") || (rowAxis === "P"))) { label = daikon.Image.SLICE_DIRECTION_AXIAL; } else if (((rowAxis === "R") || (rowAxis === "L")) && ((colAxis === "H") || (colAxis === "F"))) { label = daikon.Image.SLICE_DIRECTION_CORONAL; } else if (((colAxis === "R") || (colAxis === "L")) && ((rowAxis === "H") || (rowAxis === "F"))) { label = daikon.Image.SLICE_DIRECTION_CORONAL; } else if (((rowAxis === "A") || (rowAxis === "P")) && ((colAxis === "H") || (colAxis === "F"))) { label = daikon.Image.SLICE_DIRECTION_SAGITTAL; } else if (((colAxis === "A") || (colAxis === "P")) && ((rowAxis === "H") || (rowAxis === "F"))) { label = daikon.Image.SLICE_DIRECTION_SAGITTAL; } } else { label = daikon.Image.SLICE_DIRECTION_OBLIQUE; } return label; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Image; } /*jslint browser: true, node: true */ /*global require */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.OrderedMap = daikon.OrderedMap || ((typeof require !== 'undefined') ? require('./orderedmap.js') : null); /*** Constructor ***/ daikon.OrderedMapIterator = daikon.OrderedMapIterator || function (orderedMap) { this.orderedMap = orderedMap; this.index = 0; }; /*** Prototype Methods ***/ daikon.OrderedMapIterator.prototype.hasNext = function() { return (this.index < this.orderedMap.orderedKeys.length); }; daikon.OrderedMapIterator.prototype.next = function() { var item = this.orderedMap.get(this.orderedMap.orderedKeys[this.index]); this.index += 1; return item; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.OrderedMapIterator; } /*jslint browser: true, node: true */ /*global require */ "use strict"; // Based on: http://stackoverflow.com/questions/3549894/javascript-data-structure-for-fast-lookup-and-ordered-looping /*** Imports ***/ var daikon = daikon || {}; daikon.OrderedMapIterator = daikon.OrderedMapIterator || ((typeof require !== 'undefined') ? require('./iterator.js') : null); /*** Constructor ***/ daikon.OrderedMap = daikon.OrderedMap || function () { this.map = {}; this.orderedKeys = []; }; daikon.OrderedMap.prototype.put = function(key, value) { if (key in this.map) { // key already exists, replace value this.map[key] = value; } else { // insert new key and value this.orderedKeys.push(key); this.orderedKeys.sort(function(a, b) { return parseFloat(a) - parseFloat(b); }); this.map[key] = value; } }; daikon.OrderedMap.prototype.remove = function(key) { var index = this.orderedKeys.indexOf(key); if(index === -1) { throw new Error('key does not exist'); } this.orderedKeys.splice(index, 1); delete this.map[key]; }; daikon.OrderedMap.prototype.get = function(key) { if (key in this.map) { return this.map[key]; } return null; }; daikon.OrderedMap.prototype.iterator = function() { return new daikon.OrderedMapIterator(this); }; daikon.OrderedMap.prototype.getOrderedValues = function() { var orderedValues = [], it = this.iterator(); while (it.hasNext()) { orderedValues.push(it.next()); } return orderedValues; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.OrderedMap; } /*jslint browser: true, node: true */ /*global require */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Tag = daikon.Tag || ((typeof require !== 'undefined') ? require('./tag.js') : null); daikon.Utils = daikon.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null); daikon.Dictionary = daikon.Dictionary || ((typeof require !== 'undefined') ? require('./dictionary.js') : null); daikon.Image = daikon.Image || ((typeof require !== 'undefined') ? require('./image.js') : null); /*** Constructor ***/ daikon.Parser = daikon.Parser || function () { this.littleEndian = true; this.explicit = true; this.metaFound = false; this.metaFinished = false; this.metaFinishedOffset = -1; this.error = null; }; /*** Static Fields ***/ daikon.Parser.verbose = false; /*** Static Pseudo-constants ***/ daikon.Parser.MAGIC_COOKIE_OFFSET = 128; daikon.Parser.MAGIC_COOKIE = [68, 73, 67, 77]; daikon.Parser.VRS = ["AE", "AS", "AT", "CS", "DA", "DS", "DT", "FL", "FD", "IS", "LO", "LT", "OB", "OD", "OF", "OW", "PN", "SH", "SL", "SS", "ST", "TM", "UI", "UL", "UN", "US", "UT"]; daikon.Parser.DATA_VRS = ["OB", "OW", "OF", "SQ", "UT", "UN"]; daikon.Parser.RAW_DATA_VRS = ["OB", "OD", "OF", "OW", "UN"]; daikon.Parser.TRANSFER_SYNTAX_IMPLICIT_LITTLE = "1.2.840.10008.1.2"; daikon.Parser.TRANSFER_SYNTAX_EXPLICIT_LITTLE = "1.2.840.10008.1.2.1"; daikon.Parser.TRANSFER_SYNTAX_EXPLICIT_BIG = "1.2.840.10008.1.2.2"; daikon.Parser.TRANSFER_SYNTAX_COMPRESSION_JPEG = "1.2.840.10008.1.2.4"; daikon.Parser.TRANSFER_SYNTAX_COMPRESSION_RLE = "1.2.840.10008.1.2.5"; daikon.Parser.UNDEFINED_LENGTH = 0xFFFFFFFF; /*** Static Methods ***/ daikon.Parser.isMagicCookieFound = function (data) { var offset = daikon.Parser.MAGIC_COOKIE_OFFSET, magicCookieLength = daikon.Parser.MAGIC_COOKIE.length, ctr; for (ctr = 0; ctr < magicCookieLength; ctr += 1) { if (data.getUint8(offset + ctr) !== daikon.Parser.MAGIC_COOKIE[ctr]) { return false; } } return true; }; /*** Prototype Methods ***/ daikon.Parser.prototype.parse = function (data) { var image = null, offset, tag; try { image = new daikon.Image(); offset = this.findFirstTagOffset(data); tag = this.getNextTag(data, offset); while (tag !== null) { if (daikon.Parser.verbose) { console.log(tag.toString()); } image.putTag(tag); if (tag.isPixelData()) { break; } tag = this.getNextTag(data, tag.offsetEnd); } } catch (err) { this.error = err; } if (image !== null) { image.littleEndian = this.littleEndian; } return image; }; daikon.Parser.prototype.testForValidTag = function (data) { var offset, tag = null; try { offset = this.findFirstTagOffset(data); tag = this.getNextTag(data, offset, true); } catch (err) { this.error = err; } return tag; }; daikon.Parser.prototype.getNextTag = function (data, offset, testForTag) { var group = 0, element, value = null, offsetStart = offset, offsetValue, length = 0, little = true, vr = null, tag; if (offset >= data.byteLength) { return null; } if (this.metaFinished) { little = this.littleEndian; group = data.getUint16(offset, little); } else { group = data.getUint16(offset, true); if (((this.metaFinishedOffset !== -1) && (offset >= this.metaFinishedOffset)) || (group !== 0x0002)) { this.metaFinished = true; little = this.littleEndian; group = data.getUint16(offset, little); } else { little = true; } } if (!this.metaFound && (group === 0x0002)) { this.metaFound = true; } offset += 2; element = data.getUint16(offset, true); offset += 2; if (this.explicit || !this.metaFinished) { vr = daikon.Utils.getStringAt(data, offset, 2); if (!this.metaFound && this.metaFinished && (daikon.Parser.VRS.indexOf(vr) === -1)) { vr = daikon.Dictionary.getVR(group, element); length = data.getUint32(offset, little); offset += 4; this.explicit = false; } else { offset += 2; if (daikon.Parser.DATA_VRS.indexOf(vr) !== -1) { offset += 2; // skip two empty bytes length = data.getUint32(offset, little); offset += 4; } else { length = data.getUint16(offset, little); offset += 2; } } } else { vr = daikon.Dictionary.getVR(group, element); length = data.getUint32(offset, little); if (length === daikon.Parser.UNDEFINED_LENGTH) { vr = 'SQ'; } offset += 4; } offsetValue = offset; if (vr === 'SQ') { value = this.parseSublist(data, offset, length); if (length === daikon.Parser.UNDEFINED_LENGTH) { length = value[value.length - 1].offsetEnd - offset; } } else if ((length > 0) && !testForTag) { value = data.buffer.slice(offset, offset + length); } offset += length; tag = new daikon.Tag(group, element, vr, value, offsetStart, offsetValue, offset, this.littleEndian); if (tag.isTransformSyntax()) { if (tag.value[0] === daikon.Parser.TRANSFER_SYNTAX_IMPLICIT_LITTLE) { this.explicit = false; this.littleEndian = true; } else if (tag.value[0] === daikon.Parser.TRANSFER_SYNTAX_EXPLICIT_LITTLE) { this.explicit = true; this.littleEndian = true; } else if (tag.value[0] === daikon.Parser.TRANSFER_SYNTAX_EXPLICIT_BIG) { this.explicit = true; this.littleEndian = false; } } else if (tag.isMetaLength()) { this.metaFinishedOffset = tag.value[0] + offset; } return tag; }; daikon.Parser.prototype.parseSublist = function (data, offset, length) { var sublistItem, offsetEnd = offset + length, tags = []; if (length === daikon.Parser.UNDEFINED_LENGTH) { sublistItem = this.parseSublistItem(data, offset); while (!sublistItem.isSequenceDelim()) { tags.push(sublistItem); offset = sublistItem.offsetEnd; sublistItem = this.parseSublistItem(data, offset); } tags.push(sublistItem); } else { while (offset < offsetEnd) { sublistItem = this.parseSublistItem(data, offset); tags.push(sublistItem); offset = sublistItem.offsetEnd; } } return tags; }; daikon.Parser.prototype.parseSublistItem = function (data, offset) { var group, element, length, offsetEnd, tag, offsetStart = offset, offsetValue, sublistItemTag, tags = []; group = data.getUint16(offset, this.littleEndian); offset += 2; element = data.getUint16(offset, this.littleEndian); offset += 2; length = data.getUint32(offset, this.littleEndian); offset += 4; offsetValue = offset; if (length === daikon.Parser.UNDEFINED_LENGTH) { tag = this.getNextTag(data, offset); while (!tag.isSublistItemDelim()) { tags.push(tag); offset = tag.offsetEnd; tag = this.getNextTag(data, offset); } tags.push(tag); offset = tag.offsetEnd; } else { offsetEnd = offset + length; while (offset < offsetEnd) { tag = this.getNextTag(data, offset); tags.push(tag); offset = tag.offsetEnd; } } sublistItemTag = new daikon.Tag(group, element, null, tags, offsetStart, offsetValue, offset, this.littleEndian); return sublistItemTag; }; daikon.Parser.prototype.findFirstTagOffset = function (data) { var offset = 0, magicCookieLength = daikon.Parser.MAGIC_COOKIE.length, searchOffsetMax = daikon.Parser.MAGIC_COOKIE_OFFSET * 2, found = false, ctr = 0, ctrIn = 0, ch = 0; if (daikon.Parser.isMagicCookieFound(data)) { offset = daikon.Parser.MAGIC_COOKIE_OFFSET + magicCookieLength; } else { for (ctr = 0; ctr < searchOffsetMax; ctr += 1) { ch = data.getUint8(offset); if (ch === daikon.Parser.MAGIC_COOKIE[0]) { found = true; for (ctrIn = 1; ctrIn < magicCookieLength; ctrIn += 1) { if (data.getUint8(ctr + ctrIn) !== daikon.Parser.MAGIC_COOKIE[ctrIn]) { found = false; } } if (found) { offset = ctr; break; } } } } return offset; }; daikon.Parser.prototype.hasError = function () { return (this.error !== null); }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Parser; } /*jslint browser: true, node: true */ /*global require, module */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Parser = daikon.Parser || ((typeof require !== 'undefined') ? require('./parser.js') : null); daikon.Image = daikon.Image || ((typeof require !== 'undefined') ? require('./image.js') : null); daikon.OrderedMap = daikon.OrderedMap || ((typeof require !== 'undefined') ? require('./orderedmap.js') : null); daikon.OrderedMapIterator = daikon.OrderedMapIterator || ((typeof require !== 'undefined') ? require('./iterator.js') : null); daikon.Utils = daikon.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null); /*** Constructor ***/ daikon.Series = daikon.Series || function () { this.images = []; this.imagesOriginalOrder = null; this.isMosaic = false; this.isElscint = false; this.isCompressed = false; this.numberOfFrames = 0; this.numberOfFramesInFile = 0; this.isMultiFrame = false; this.isMultiFrameVolume = false; this.isMultiFrameTimeseries = false; this.isImplicitTimeseries = false; this.sliceSense = false; this.sliceDir = daikon.Image.SLICE_DIRECTION_UNKNOWN; this.error = null; }; /*** Static fields ***/ daikon.Series.parserError = null; /*** Static Methods ***/ daikon.Series.parseImage = function (data) { var parser, image; parser = new daikon.Parser(); image = parser.parse(data); if (parser.hasError()) { daikon.Series.parserError = parser.error; return null; } return image; }; daikon.Series.getMosaicOffset = function (mosaicCols, mosaicColWidth, mosaicRowHeight, mosaicWidth, xLocVal, yLocVal, zLocVal) { var xLoc, yLoc, zLoc; xLoc = xLocVal; yLoc = yLocVal; zLoc = zLocVal; xLoc = ((zLoc % mosaicCols) * mosaicColWidth) + xLoc; yLoc = (((parseInt(zLoc / mosaicCols)) * mosaicRowHeight) + yLoc) * mosaicWidth; return (xLoc + yLoc); }; daikon.Series.orderDicoms = function (images, numFrames, sliceDir) { var hasImagePosition, hasSliceLocation, hasImageNumber, timeMap, timeIt, ctr, ctrIn, dg, ordered, imagesOrderedByTimeAndSpace; hasImagePosition = (images[0].getImagePosition() !== null); hasSliceLocation = (images[0].getSliceLocation() !== null); hasImageNumber = (images[0].getImageNumber() !== null); timeMap = daikon.Series.orderByTime(images, numFrames, sliceDir, hasImagePosition, hasSliceLocation); timeIt = timeMap.orderedKeys; imagesOrderedByTimeAndSpace = []; for (ctr = 0; ctr < timeIt.length; ctr += 1) { dg = timeMap.get(timeIt[ctr]); if (hasImagePosition) { ordered = daikon.Series.orderByImagePosition(dg, sliceDir); } else if (hasSliceLocation) { ordered = daikon.Series.orderBySliceLocation(dg); } else if (hasImageNumber) { ordered = daikon.Series.orderByImageNumber(dg); } else { ordered = dg; } for (ctrIn = 0; ctrIn < ordered.length; ctrIn += 1) { imagesOrderedByTimeAndSpace.push(ordered[ctrIn]); } } for (ctrIn = 0; ctrIn < imagesOrderedByTimeAndSpace.length; ctrIn += 1) { imagesOrderedByTimeAndSpace[ctrIn].index = ctrIn; } return imagesOrderedByTimeAndSpace; }; daikon.Series.orderByImagePosition = function (images, sliceDir) { var dicomMap, ctr; dicomMap = new daikon.OrderedMap(); for (ctr = 0; ctr < images.length; ctr += 1) { dicomMap.put(images[ctr].getImagePositionSliceDir(sliceDir), images[ctr]); } return dicomMap.getOrderedValues(); }; daikon.Series.orderBySliceLocation = function (images) { var dicomMap, ctr; dicomMap = new daikon.OrderedMap(); for (ctr = 0; ctr < images.length; ctr += 1) { dicomMap.put(images[ctr].getSliceLocation(), images[ctr]); } return dicomMap.getOrderedValues(); }; daikon.Series.orderByImageNumber = function (images) { var dicomMap, ctr; dicomMap = new daikon.OrderedMap(); for (ctr = 0; ctr < images.length; ctr += 1) { dicomMap.put(images[ctr].getImageNumber(), images[ctr]); } return dicomMap.getOrderedValues(); }; daikon.Series.hasMatchingSlice = function (dg, image, sliceDir, doImagePos, doSliceLoc) { var matchingNum = 0, ctr, current, imagePos, sliceLoc, imageNum; if (doImagePos) { matchingNum = image.getImagePositionSliceDir(sliceDir); } else if (doSliceLoc) { matchingNum = image.getSliceLocation(); } else { matchingNum = image.getImageNumber(); } for (ctr = 0; ctr < dg.length; ctr += 1) { current = dg[ctr]; if (doImagePos) { imagePos = current.getImagePositionSliceDir(sliceDir); if (imagePos === matchingNum) { return true; } } else if (doSliceLoc) { sliceLoc = current.getSliceLocation(); if (sliceLoc === matchingNum) { return true; } } else { imageNum = current.getImageNumber(); if (imageNum === matchingNum) { return true; } } } return false; }; daikon.Series.orderByTime = function (images, numFrames, sliceDir, hasImagePosition, hasSliceLocation) { var dicomMap, hasTemporalPosition, hasTemporalNumber, ctr, image, tempPos, dg, timeBySliceMap, imageNum, sliceMarker, slice, dicomsCopy, dicomsCopyIndex, sliceIt, timeIt, dgFound, it; dicomMap = new daikon.OrderedMap(); hasTemporalPosition = (numFrames > 1) && (images[0].getTemporalPosition() !== null); hasTemporalNumber = (numFrames > 1) && (images[0].getTemporalNumber() !== null) && (images[0].getTemporalNumber() === numFrames); if (hasTemporalPosition && hasTemporalNumber) { // explicit series for (ctr = 0; ctr < images.length; ctr += 1) { image = images[ctr]; tempPos = image.getTemporalPosition(); dg = dicomMap.get(tempPos); if (!dg) { dg = []; dicomMap.put(tempPos, dg); } dg.push(image); } } else { // implicit series // order data by slice then time timeBySliceMap = new daikon.OrderedMap(); for (ctr = 0; ctr < images.length; ctr += 1) { if (images[ctr] !== null) { imageNum = images[ctr].getImageNumber(); sliceMarker = ctr; if (hasImagePosition) { sliceMarker = images[ctr].getImagePositionSliceDir(sliceDir); } else if (hasSliceLocation) { sliceMarker = images[ctr].getSliceLocation(); } slice = timeBySliceMap.get(sliceMarker); if (slice === null) { slice = new daikon.OrderedMap(); timeBySliceMap.put(sliceMarker, slice); } slice.put(imageNum, images[ctr]); } } // copy into DICOM array (ordered by slice by time) dicomsCopy = []; dicomsCopyIndex = 0; sliceIt = timeBySliceMap.iterator(); while (sliceIt.hasNext()) { slice = sliceIt.next(); timeIt = slice.iterator(); while (timeIt.hasNext()) { dicomsCopy[dicomsCopyIndex] = timeIt.next(); dicomsCopyIndex += 1; } } // groups dicoms by timepoint for (ctr = 0; ctr < dicomsCopy.length; ctr += 1) { if (dicomsCopy[ctr] !== null) { dgFound = null; it = dicomMap.iterator(); while (it.hasNext()) { dg = it.next(); if (!daikon.Series.hasMatchingSlice(dg, dicomsCopy[ctr], sliceDir, hasImagePosition, hasSliceLocation)) { dgFound = dg; break; } } if (dgFound === null) { dgFound = []; dicomMap.put(dicomMap.orderedKeys.length, dgFound); } dgFound.push(dicomsCopy[ctr]); } } } return dicomMap; }; /*** Prototype Methods ***/ daikon.Series.prototype.getOrder = function () { var ctr, order = []; for (ctr = 0; ctr < this.imagesOriginalOrder.length; ctr += 1) { order[ctr] = this.imagesOriginalOrder[ctr].index; } return order; }; daikon.Series.prototype.toString = function () { return this.images[0].getSeriesId(); }; daikon.Series.prototype.getName = function () { var des = this.images[0].getSeriesDescription(); var uid = this.images[0].getSeriesInstanceUID(); if (des !== null) { return des; } if (uid !== null) { return uid; } return null; }; daikon.Series.prototype.addImage = function (image) { this.images.push(image); }; daikon.Series.prototype.matchesSeries = function (image) { if (this.images.length === 0) { return true; } return (this.images[0].getSeriesId() === image.getSeriesId()); }; daikon.Series.prototype.buildSeries = function () { var hasFrameTime, ctr, sliceLoc, orderedImages, sliceLocationFirst, sliceLocationLast, sliceLocDiff, sliceLocations, orientation, imagePos; this.isMosaic = this.images[0].isMosaic(); this.isElscint = this.images[0].isElscint(); this.isCompressed = this.images[0].isCompressed(); // check for multi-frame this.numberOfFrames = this.images[0].getNumberOfFrames(); this.numberOfFramesInFile = this.images[0].getNumberOfImplicitFrames(); this.isMultiFrame = (this.numberOfFrames > 1) || (this.isMosaic && (this.images[0].length > 1)); this.isMultiFrameVolume = false; this.isMultiFrameTimeseries = false; this.isImplicitTimeseries = false; if (this.isMultiFrame) { hasFrameTime = (this.images[0].getFrameTime() > 0); if (this.isMosaic) { this.isMultiFrameTimeseries = true; } else { if (hasFrameTime) { this.isMultiFrameTimeseries = true; } else if (this.numberOfFramesInFile > 1) { this.isMultiFrameTimeseries = true; this.numberOfFrames = this.images.length; } else { this.isMultiFrameVolume = true; } } } if (!this.isMosaic && (this.numberOfFrames <= 1)) { // check for implicit frame count imagePos = (this.images[0].getImagePosition() || []); sliceLoc = imagePos.toString(); this.numberOfFrames = 0; for (ctr = 0; ctr < this.images.length; ctr += 1) { imagePos = (this.images[ctr].getImagePosition() || []); if (imagePos.toString() === sliceLoc) { this.numberOfFrames += 1; } } if (this.numberOfFrames > 1) { this.isImplicitTimeseries = true; } } this.sliceDir = this.images[0].getAcquiredSliceDirection(); orderedImages = daikon.Series.orderDicoms(this.images, this.numberOfFrames, this.sliceDir); sliceLocationFirst = orderedImages[0].getImagePositionSliceDir(this.sliceDir); sliceLocationLast = orderedImages[orderedImages.length - 1].getImagePositionSliceDir(this.sliceDir); sliceLocDiff = sliceLocationLast - sliceLocationFirst; if (this.isMosaic) { this.sliceSense = true; } else if (this.isMultiFrame) { sliceLocations = orderedImages[0].getSliceLocationVector(); if (sliceLocations !== null) { orientation = orderedImages[0].getOrientation(); if (orientation.charAt(2) === 'Z') { this.sliceSense = (sliceLocations[0] - sliceLocations[sliceLocations.length - 1]) < 0; } else { this.sliceSense = (sliceLocations[0] - sliceLocations[sliceLocations.length - 1]) > 0; } } else { this.sliceSense = sliceLocationFirst < 0 ? false : true; // maybe??? } } else { /* * "The direction of the axes is defined fully by the patient's orientation. The x-axis is increasing to the left hand side of the patient. The * y-axis is increasing to the posterior side of the patient. The z-axis is increasing toward the head of the patient." */ if ((this.sliceDir === daikon.Image.SLICE_DIRECTION_SAGITTAL) || (this.sliceDir === daikon.Image.SLICE_DIRECTION_CORONAL)) { if (sliceLocDiff > 0) { this.sliceSense = false; } else { this.sliceSense = true; } } else { if (sliceLocDiff > 0) { this.sliceSense = true; } else { this.sliceSense = false; } } } this.imagesOriginalOrder = this.images; this.images = orderedImages; }; daikon.Series.prototype.concatenateImageData = function (progressMeter, onFinishedImageRead) { var buffer; if (this.isMosaic) { buffer = this.getMosaicData(this.images[0], this.images[0].getPixelData().value.buffer); this.images[0].clearPixelData(); } else { buffer = this.images[0].getPixelData().value.buffer; this.images[0].clearPixelData(); } setTimeout(this.concatenateNextImageData(buffer, progressMeter, 1, onFinishedImageRead), 0); }; daikon.Series.prototype.concatenateNextImageData = function (buffer, progressMeter, index, onFinishedImageRead) { if (index >= this.images.length) { if (progressMeter) { progressMeter.drawProgress(1, "Reading DICOM Images"); } onFinishedImageRead(buffer); } else { if (progressMeter) { progressMeter.drawProgress(index / this.images.length, "Reading DICOM Images"); } if (this.isMosaic) { buffer = daikon.Utils.concatArrayBuffers(buffer, this.getMosaicData(this.images[index], this.images[index].getPixelData().value.buffer)); this.images[index].clearPixelData(); } else { buffer = daikon.Utils.concatArrayBuffers(buffer, this.images[index].getPixelData().value.buffer); this.images[index].clearPixelData(); } setTimeout(daikon.Utils.bind(this, function() {this.concatenateNextImageData(buffer, progressMeter, index + 1, onFinishedImageRead);}), 0); } }; daikon.Series.prototype.getMosaicData = function (image, data) { var mosaicWidth, mosaicHeight, mosaicRows, mosaicCols, mosaicRowHeight, mosaicColWidth, numBytes, ctrS, ctrR, ctrC, numSlices, numRows, numCols, buffer, dataTyped, offset, ctr, index = 0; numBytes = parseInt(this.images[0].getBitsAllocated() / 8); numSlices = this.images[0].getMosaicCols() * this.images[0].getMosaicRows(); numRows = parseInt(this.images[0].getRows() / this.images[0].getMosaicRows()); numCols = parseInt(this.images[0].getCols() / this.images[0].getMosaicCols()); mosaicWidth = this.images[0].getCols(); mosaicHeight = this.images[0].getRows(); mosaicRows = this.images[0].getMosaicRows(); mosaicCols = this.images[0].getMosaicCols(); mosaicRowHeight = parseInt(mosaicHeight / mosaicRows); mosaicColWidth = parseInt(mosaicWidth / mosaicCols); buffer = new Uint8Array(new ArrayBuffer(numSlices * numRows * numCols * numBytes)); dataTyped = new Uint8Array(data); for (ctrS = 0; ctrS < numSlices; ctrS += 1) { for (ctrR = 0; ctrR < numRows; ctrR += 1) { for (ctrC = 0; ctrC < numCols; ctrC += 1) { offset = daikon.Series.getMosaicOffset(mosaicCols, mosaicColWidth, mosaicRowHeight, mosaicWidth, ctrC, ctrR, ctrS); for (ctr = 0; ctr < numBytes; ctr += 1) { buffer[index] = dataTyped[(offset * numBytes) + ctr]; index += 1; } } } } return buffer.buffer; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Series; } /*jslint browser: true, node: true */ /*global require */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Utils = daikon.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null); daikon.Dictionary = daikon.Dictionary || ((typeof require !== 'undefined') ? require('./dictionary.js') : null); /*** Constructor ***/ daikon.Tag = daikon.Tag || function (group, element, vr, value, offsetStart, offsetValue, offsetEnd, littleEndian) { this.group = group; this.element = element; this.vr = vr; this.offsetStart = offsetStart; this.offsetValue = offsetValue; this.offsetEnd = offsetEnd; this.sublist = false; this.id = daikon.Tag.createId(group, element); if (value instanceof Array) { this.value = value; this.sublist = true; } else if (value !== null) { this.value = daikon.Tag.convertValue(vr, new DataView(value), littleEndian); } else { this.value = null; } }; /*** Static Pseudo-constants ***/ daikon.Tag.VR_AE_MAX_LENGTH = 16; daikon.Tag.VR_AS_MAX_LENGTH = 4; daikon.Tag.VR_AT_MAX_LENGTH = 4; daikon.Tag.VR_CS_MAX_LENGTH = 16; daikon.Tag.VR_DA_MAX_LENGTH = 8; daikon.Tag.VR_DS_MAX_LENGTH = 16; daikon.Tag.VR_DT_MAX_LENGTH = 26; daikon.Tag.VR_FL_MAX_LENGTH = 4; daikon.Tag.VR_FD_MAX_LENGTH = 8; daikon.Tag.VR_IS_MAX_LENGTH = 12; daikon.Tag.VR_LO_MAX_LENGTH = 64; daikon.Tag.VR_LT_MAX_LENGTH = 10240; daikon.Tag.VR_OB_MAX_LENGTH = -1; daikon.Tag.VR_OD_MAX_LENGTH = -1; daikon.Tag.VR_OF_MAX_LENGTH = -1; daikon.Tag.VR_OW_MAX_LENGTH = -1; daikon.Tag.VR_PN_MAX_LENGTH = 64 * 5; daikon.Tag.VR_SH_MAX_LENGTH = 16; daikon.Tag.VR_SL_MAX_LENGTH = 4; daikon.Tag.VR_SS_MAX_LENGTH = 2; daikon.Tag.VR_ST_MAX_LENGTH = 1024; daikon.Tag.VR_TM_MAX_LENGTH = 16; daikon.Tag.VR_UI_MAX_LENGTH = 64; daikon.Tag.VR_UL_MAX_LENGTH = 4; daikon.Tag.VR_UN_MAX_LENGTH = -1; daikon.Tag.VR_US_MAX_LENGTH = 2; daikon.Tag.VR_UT_MAX_LENGTH = -1; // metadata daikon.Tag.TAG_TRANSFER_SYNTAX = [0x0002, 0x0010]; daikon.Tag.TAG_META_LENGTH = [0x0002, 0x0000]; // sublists daikon.Tag.TAG_SUBLIST_ITEM = [0xFFFE, 0xE000]; daikon.Tag.TAG_SUBLIST_ITEM_DELIM = [0xFFFE, 0xE00D]; daikon.Tag.TAG_SUBLIST_SEQ_DELIM = [0xFFFE, 0xE0DD]; // image dims daikon.Tag.TAG_ROWS = [0x0028, 0x0010]; daikon.Tag.TAG_COLS = [0x0028, 0x0011]; daikon.Tag.TAG_ACQUISITION_MATRIX = [0x0018, 0x1310]; daikon.Tag.TAG_NUMBER_OF_FRAMES = [0x0028, 0x0008]; daikon.Tag.TAG_NUMBER_TEMPORAL_POSITIONS = [0x0020, 0x0105]; // voxel dims daikon.Tag.TAG_PIXEL_SPACING = [0x0028, 0x0030]; daikon.Tag.TAG_SLICE_THICKNESS = [0x0018, 0x0050]; daikon.Tag.TAG_SLICE_GAP = [0x0018, 0x0088]; daikon.Tag.TAG_TR = [0x0018, 0x0080]; daikon.Tag.TAG_FRAME_TIME = [0x0018, 0x1063]; // datatype daikon.Tag.TAG_BITS_ALLOCATED = [0x0028, 0x0100]; daikon.Tag.TAG_BITS_STORED = [0x0028, 0x0101]; daikon.Tag.TAG_PIXEL_REPRESENTATION = [0x0028, 0x0103]; daikon.Tag.TAG_HIGH_BIT = [0x0028, 0x0102]; daikon.Tag.TAG_PHOTOMETRIC_INTERPRETATION = [0x0028, 0x0004]; daikon.Tag.TAG_SAMPLES_PER_PIXEL = [0x0028, 0x0002]; // data scale daikon.Tag.TAG_DATA_SCALE_SLOPE = [0x0028, 0x1053]; daikon.Tag.TAG_DATA_SCALE_INTERCEPT = [0x0028, 0x1052]; daikon.Tag.TAG_DATA_SCALE_ELSCINT = [0x0207, 0x101F]; daikon.Tag.TAG_PIXEL_BANDWIDTH = [0x0018, 0x0095]; // range daikon.Tag.TAG_IMAGE_MIN = [0x0028, 0x0106]; daikon.Tag.TAG_IMAGE_MAX = [0x0028, 0x0107]; daikon.Tag.TAG_WINDOW_CENTER = [0x0028, 0x1050]; daikon.Tag.TAG_WINDOW_WIDTH = [0x0028, 0x1051]; // descriptors daikon.Tag.TAG_PATIENT_NAME = [0x0010, 0x0010]; daikon.Tag.TAG_PATIENT_ID = [0x0010, 0x0020]; daikon.Tag.TAG_STUDY_DATE = [0x0008, 0x0020]; daikon.Tag.TAG_STUDY_TIME = [0x0008, 0x0030]; daikon.Tag.TAG_STUDY_DES = [0x0008, 0x1030]; daikon.Tag.TAG_IMAGE_TYPE = [0x0008, 0x0008]; daikon.Tag.TAG_IMAGE_COMMENTS = [0x0020, 0x4000]; daikon.Tag.TAG_SEQUENCE_NAME = [0x0018, 0x0024]; daikon.Tag.TAG_MODALITY = [0x0008, 0x0060]; // session ID daikon.Tag.TAG_FRAME_OF_REF_UID = [0x0020, 0x0052]; // study ID daikon.Tag.TAG_STUDY_UID = [0x0020, 0x000D]; // volume ID daikon.Tag.TAG_SERIES_DESCRIPTION = [0x0008, 0x103E]; daikon.Tag.TAG_SERIES_INSTANCE_UID = [0x0020, 0x000E]; daikon.Tag.TAG_SERIES_NUMBER = [0x0020, 0x0011]; daikon.Tag.TAG_ECHO_NUMBER = [0x0018, 0x0086]; daikon.Tag.TAG_TEMPORAL_POSITION = [0x0020, 0x0100]; // slice ID daikon.Tag.TAG_IMAGE_NUM = [0x0020, 0x0013]; daikon.Tag.TAG_SLICE_LOCATION = [0x0020, 0x1041]; // orientation daikon.Tag.TAG_IMAGE_ORIENTATION = [0x0020, 0x0037]; daikon.Tag.TAG_IMAGE_POSITION = [0x0020, 0x0032]; daikon.Tag.TAG_SLICE_LOCATION_VECTOR = [0x0018, 0x2005]; // pixel data daikon.Tag.TAG_PIXEL_DATA = [0x7FE0, 0x0010]; /*** Static methods ***/ daikon.Tag.createId = function (group, element) { var groupStr = daikon.Utils.dec2hex(group), elemStr = daikon.Utils.dec2hex(element); return groupStr + elemStr; }; daikon.Tag.getUnsignedInteger16 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 2; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getUint16(ctr * 2, littleEndian); } return data; }; daikon.Tag.getSignedInteger16 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 2; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getInt16(ctr * 2, littleEndian); } return data; }; daikon.Tag.getFloat32 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 4; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getFloat32(ctr * 4, littleEndian); } return data; }; daikon.Tag.getSignedInteger32 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 4; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getInt32(ctr * 4, littleEndian); } return data; }; daikon.Tag.getUnsignedInteger32 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 4; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getUint32(ctr * 4, littleEndian); } return data; }; daikon.Tag.getFloat64 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 8; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getFloat64(ctr * 8, littleEndian); } return data; }; daikon.Tag.getDoubleElscint = function (rawData) { var data = [], reordered = [], ctr; for (ctr = 0; ctr < 8; ctr += 1) { data[ctr] = rawData.getUint8(ctr); } reordered[0] = data[3]; reordered[1] = data[2]; reordered[2] = data[1]; reordered[3] = data[0]; reordered[4] = data[7]; reordered[5] = data[6]; reordered[6] = data[5]; reordered[7] = data[4]; data = [daikon.Utils.bytesToDouble(reordered)]; return data; }; daikon.Tag.getFixedLengthStringValue = function (rawData, maxLength) { var data, mul, ctr; mul = Math.floor(rawData.byteLength / maxLength); data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = daikon.Utils.getStringAt(rawData, ctr * maxLength, maxLength); } return data; }; daikon.Tag.getStringValue = function (rawData) { var data = daikon.Utils.getStringAt(rawData, 0, rawData.byteLength).split('\\'), ctr; for (ctr = 0; ctr < data.length; ctr += 1) { data[ctr] = daikon.Utils.trim(data[ctr]); } return data; }; daikon.Tag.getDateStringValue = function (rawData) { var dotFormat = (daikon.Tag.getSingleStringValue(rawData)[0].indexOf('.') !== -1), stringData = daikon.Tag.getFixedLengthStringValue(rawData, dotFormat ? 10 : daikon.Tag.VR_DA_MAX_LENGTH), parts = null, data = [], ctr; for (ctr = 0; ctr < stringData.length; ctr += 1) { if (dotFormat) { parts = stringData[ctr].split('.'); data[ctr] = new Date(daikon.Utils.safeParseInt(parts[0]), daikon.Utils.safeParseInt(parts[1]) - 1, daikon.Utils.safeParseInt(parts[2])); } else if (stringData[ctr].length === 8) { data[ctr] = new Date(daikon.Utils.safeParseInt(stringData[ctr].substring(0, 4)), daikon.Utils.safeParseInt(stringData[ctr].substring(4, 6)) - 1, daikon.Utils.safeParseInt(stringData[ctr].substring(6, 8))); } else { data[ctr] = Date.parse(stringData[ctr]); } } return data; }; daikon.Tag.getDateTimeStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], ctr, year = null, month = null, date = null, hours = null, minutes = null, seconds = null; for (ctr = 0; ctr < stringData.length; ctr += 1) { if (stringData[ctr].length >= 4) { year = parseInt(stringData[ctr].substring(0, 4), 10); // required if (stringData[ctr].length >= 6) { month = daikon.Utils.safeParseInt(stringData[ctr].substring(4, 6)) - 1; } if (stringData[ctr].length >= 8) { date = daikon.Utils.safeParseInt(stringData[ctr].substring(6, 8)); } if (stringData[ctr].length >= 10) { hours = daikon.Utils.safeParseInt(stringData[ctr].substring(8, 10)); } if (stringData[ctr].length >= 12) { minutes = daikon.Utils.safeParseInt(stringData[ctr].substring(10, 12)); } if (stringData[ctr].length >= 14) { seconds = daikon.Utils.safeParseInt(stringData[ctr].substring(12, 14)); } data[ctr] = new Date(year, month, date, hours, minutes, seconds); } else { data[ctr] = Date.parse(stringData[ctr]); } } return data; }; daikon.Tag.getTimeStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], parts = null, ctr, hours = 0, minutes = 0, seconds = 0; for (ctr = 0; ctr < stringData.length; ctr += 1) { if (stringData[ctr].indexOf(':') !== -1) { parts = stringData[ctr].split(':'); hours = daikon.Utils.safeParseInt(parts[0]); if (parts.length > 1) { minutes = daikon.Utils.safeParseInt(parts[1]); } if (parts.length > 2) { seconds = daikon.Utils.safeParseFloat(parts[2]); } } else { if (stringData[ctr].length >= 2) { hours = daikon.Utils.safeParseInt(stringData[ctr].substring(0, 2)); } if (stringData[ctr].length >= 4) { minutes = daikon.Utils.safeParseInt(stringData[ctr].substring(2, 4)); } if (stringData[ctr].length >= 6) { seconds = daikon.Utils.safeParseFloat(stringData[ctr].substring(4)); } } data[ctr] = Math.round((hours * 60 * 60 * 1000) + (minutes * 60 * 1000) + (seconds * 1000)); } return data; }; daikon.Tag.getDoubleStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], ctr; for (ctr = 0; ctr < stringData.length; ctr += 1) { data[ctr] = parseFloat(stringData[ctr]); } return data; }; daikon.Tag.getIntegerStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], ctr; for (ctr = 0; ctr < stringData.length; ctr += 1) { data[ctr] = parseInt(stringData[ctr], 10); } return data; }; daikon.Tag.getSingleStringValue = function (rawData) { return [daikon.Utils.trim(daikon.Utils.getStringAt(rawData, 0, rawData.byteLength))]; }; daikon.Tag.getPersonNameStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], ctr; for (ctr = 0; ctr < stringData.length; ctr += 1) { data[ctr] = stringData[ctr].replace('^', ' '); } return data; }; daikon.Tag.convertValue = function (vr, rawData, littleEndian) { var data = null; if (vr === 'AE') { data = daikon.Tag.getSingleStringValue(rawData, daikon.Tag.VR_AE_MAX_LENGTH); } else if (vr === 'AS') { data = daikon.Tag.getFixedLengthStringValue(rawData, daikon.Tag.VR_AS_MAX_LENGTH); } else if (vr === 'AT') { data = daikon.Tag.getUnsignedInteger16(rawData, littleEndian); } else if (vr === 'CS') { data = daikon.Tag.getStringValue(rawData); } else if (vr === 'DA') { data = daikon.Tag.getDateStringValue(rawData); } else if (vr === 'DS') { data = daikon.Tag.getDoubleStringValue(rawData); } else if (vr === 'DT') { data = daikon.Tag.getDateTimeStringValue(rawData); } else if (vr === 'FL') { data = daikon.Tag.getFloat32(rawData, littleEndian); } else if (vr === 'FD') { data = daikon.Tag.getFloat64(rawData, littleEndian); } else if (vr === 'FE') { // special Elscint double (see dictionary) data = daikon.Tag.getDoubleElscint(rawData, littleEndian); } else if (vr === 'IS') { data = daikon.Tag.getIntegerStringValue(rawData); } else if (vr === 'LO') { data = daikon.Tag.getStringValue(rawData); } else if (vr === 'LT') { data = daikon.Tag.getSingleStringValue(rawData); } else if (vr === 'OB') { data = rawData; } else if (vr === 'OD') { data = rawData; } else if (vr === 'OF') { data = rawData; } else if (vr === 'OW') { data = rawData; } else if (vr === 'PN') { data = daikon.Tag.getPersonNameStringValue(rawData); } else if (vr === 'SH') { data = daikon.Tag.getStringValue(rawData); } else if (vr === 'SL') { data = daikon.Tag.getSignedInteger32(rawData, littleEndian); } else if (vr === 'SQ') { data = null; } else if (vr === 'SS') { data = daikon.Tag.getSignedInteger16(rawData, littleEndian); } else if (vr === 'ST') { data = daikon.Tag.getSingleStringValue(rawData); } else if (vr === 'TM') { data = daikon.Tag.getTimeStringValue(rawData); } else if (vr === 'UI') { data = daikon.Tag.getStringValue(rawData); } else if (vr === 'UL') { data = daikon.Tag.getUnsignedInteger32(rawData, littleEndian); } else if (vr === 'UN') { data = rawData; } else if (vr === 'US') { data = daikon.Tag.getUnsignedInteger16(rawData, littleEndian); } else if (vr === 'UT') { data = daikon.Tag.getSingleStringValue(rawData); } return data; }; /*** Prototype Methods ***/ daikon.Tag.prototype.toString = function (level) { var valueStr = '', ctr, groupStr = daikon.Utils.dec2hex(this.group), elemStr = daikon.Utils.dec2hex(this.element), tagStr = '(' + groupStr + ',' + elemStr + ')', des = '', padding; if (level === undefined) { level = 0; } padding = ""; for (ctr = 0; ctr < level; ctr += 1) { padding += " "; } if (this.sublist) { for (ctr = 0; ctr < this.value.length; ctr += 1) { valueStr += ('\n' + (this.value[ctr].toString(level + 1))); } } else if (this.vr === 'SQ') { valueStr = ''; } else if (this.isPixelData()) { valueStr = ''; } else if (!this.value) { valueStr = ''; } else { valueStr = '[' + this.value + ']'; } if (this.isSublistItem()) { tagStr = "Sequence Item"; } else if (this.isSublistItemDelim()) { tagStr = "Sequence Item Delimiter"; } else if (this.isSequenceDelim()) { tagStr = "Sequence Delimiter"; } else if (this.isPixelData()) { tagStr = "Pixel Data"; } else { des = daikon.Utils.convertCamcelCaseToTitleCase(daikon.Dictionary.getDescription(this.group, this.element)); } return padding + tagStr + ' ' + des + ' ' + valueStr; }; daikon.Tag.prototype.isTransformSyntax = function () { return (this.group === daikon.Tag.TAG_TRANSFER_SYNTAX[0]) && (this.element === daikon.Tag.TAG_TRANSFER_SYNTAX[1]); }; daikon.Tag.prototype.isPixelData = function () { return (this.group === daikon.Tag.TAG_PIXEL_DATA[0]) && (this.element === daikon.Tag.TAG_PIXEL_DATA[1]); }; daikon.Tag.prototype.isSublistItem = function () { return (this.group === daikon.Tag.TAG_SUBLIST_ITEM[0]) && (this.element === daikon.Tag.TAG_SUBLIST_ITEM[1]); }; daikon.Tag.prototype.isSublistItemDelim = function () { return (this.group === daikon.Tag.TAG_SUBLIST_ITEM_DELIM[0]) && (this.element === daikon.Tag.TAG_SUBLIST_ITEM_DELIM[1]); }; daikon.Tag.prototype.isSequenceDelim = function () { return (this.group === daikon.Tag.TAG_SUBLIST_SEQ_DELIM[0]) && (this.element === daikon.Tag.TAG_SUBLIST_SEQ_DELIM[1]); }; daikon.Tag.prototype.isMetaLength = function () { return (this.group === daikon.Tag.TAG_META_LENGTH[0]) && (this.element === daikon.Tag.TAG_META_LENGTH[1]); }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Tag; } /*jslint browser: true, node: true */ /*global require, module */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Utils = daikon.Utils || {}; /*** Static methods ***/ daikon.Utils.dec2hex = function (i) { return (i + 0x10000).toString(16).substr(-4).toUpperCase(); }; daikon.Utils.getStringAt = function (dataview, start, length) { var str = "", ctr, ch; for (ctr = 0; ctr < length; ctr += 1) { ch = dataview.getUint8(start + ctr); if (ch !== 0) { str += String.fromCharCode(ch); } } return str; }; daikon.Utils.trim = function (str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }; daikon.Utils.stripLeadingZeros = function (str) { return str.replace(/^[0]+/g, ""); }; daikon.Utils.safeParseInt = function (str) { str = daikon.Utils.stripLeadingZeros(str); if (str.length > 0) { return parseInt(str, 10); } return 0; }; daikon.Utils.convertCamcelCaseToTitleCase = function (str) { var result = str.replace(/([A-Z][a-z])/g, " $1"); return daikon.Utils.trim(result.charAt(0).toUpperCase() + result.slice(1)); }; daikon.Utils.safeParseFloat = function (str) { str = daikon.Utils.stripLeadingZeros(str); if (str.length > 0) { return parseFloat(str); } return 0; }; // http://stackoverflow.com/questions/8361086/convert-byte-array-to-numbers-in-javascript daikon.Utils.bytesToDouble = function (data) { var sign = (data[0] & 1<<7)>>7; var exponent = (((data[0] & 127) << 4) | (data[1]&(15<<4))>>4); if(exponent == 0) return 0; if(exponent == 0x7ff) return (sign) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; var mul = Math.pow(2,exponent - 1023 - 52); var mantissa = data[7]+ data[6]*Math.pow(2,8*1)+ data[5]*Math.pow(2,8*2)+ data[4]*Math.pow(2,8*3)+ data[3]*Math.pow(2,8*4)+ data[2]*Math.pow(2,8*5)+ (data[1]&15)*Math.pow(2,8*6)+ Math.pow(2,52); return Math.pow(-1,sign)*mantissa*mul; }; daikon.Utils.concatArrayBuffers = function (buffer1, buffer2) { var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength); tmp.set(new Uint8Array(buffer1), 0); tmp.set(new Uint8Array(buffer2), buffer1.byteLength); return tmp.buffer; }; daikon.Utils.bind = function (scope, fn, args, appendArgs) { if (arguments.length === 2) { return function () { return fn.apply(scope, arguments); }; } var method = fn, slice = Array.prototype.slice; return function () { var callArgs = args || arguments; if (appendArgs === true) { callArgs = slice.call(arguments, 0); callArgs = callArgs.concat(args); } else if (typeof appendArgs === 'number') { callArgs = slice.call(arguments, 0); // copy arguments first Ext.Array.insert(callArgs, appendArgs, args); } return method.apply(scope || window, callArgs); }; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Utils; }
lib/daikon.js
/*! * Copyright (c) 2012-2013, RII-UTHSCSA * All rights reserved. * * THIS PRODUCT IS NOT FOR CLINICAL USE. * * 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 RII-UTHSCSA 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 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. */ /*jslint browser: true, node: true */ /*global require, module */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Dictionary = daikon.Dictionary || {}; /*** Static Pseudo-constants ***/ daikon.Dictionary.GROUP_INDICES = []; daikon.Dictionary.GROUP_INDICES[0x0002] = 0; daikon.Dictionary.GROUP_INDICES[0x0004] = 10; daikon.Dictionary.GROUP_INDICES[0x0008] = 27; daikon.Dictionary.GROUP_INDICES[0x0010] = 197; daikon.Dictionary.GROUP_INDICES[0x0012] = 248; daikon.Dictionary.GROUP_INDICES[0x0014] = 267; daikon.Dictionary.GROUP_INDICES[0x0018] = 394; daikon.Dictionary.GROUP_INDICES[0x0020] = 1096; daikon.Dictionary.GROUP_INDICES[0x0022] = 1212; daikon.Dictionary.GROUP_INDICES[0x0024] = 1317; daikon.Dictionary.GROUP_INDICES[0x0028] = 1418; daikon.Dictionary.GROUP_INDICES[0x0032] = 1598; daikon.Dictionary.GROUP_INDICES[0x0038] = 1625; daikon.Dictionary.GROUP_INDICES[0x003A] = 1653; daikon.Dictionary.GROUP_INDICES[0x0040] = 1691; daikon.Dictionary.GROUP_INDICES[0x0042] = 1992; daikon.Dictionary.GROUP_INDICES[0x0046] = 2011; daikon.Dictionary.GROUP_INDICES[0x0048] = 2060; daikon.Dictionary.GROUP_INDICES[0x0050] = 2091; daikon.Dictionary.GROUP_INDICES[0x0052] = 2107; daikon.Dictionary.GROUP_INDICES[0x0054] = 2133; daikon.Dictionary.GROUP_INDICES[0x0060] = 2213; daikon.Dictionary.GROUP_INDICES[0x0062] = 2220; daikon.Dictionary.GROUP_INDICES[0x0064] = 2235; daikon.Dictionary.GROUP_INDICES[0x0066] = 2243; daikon.Dictionary.GROUP_INDICES[0x0068] = 2288; daikon.Dictionary.GROUP_INDICES[0x0070] = 2358; daikon.Dictionary.GROUP_INDICES[0x0072] = 2464; daikon.Dictionary.GROUP_INDICES[0x0074] = 2571; daikon.Dictionary.GROUP_INDICES[0x0076] = 2629; daikon.Dictionary.GROUP_INDICES[0x0078] = 2652; daikon.Dictionary.GROUP_INDICES[0x0088] = 2670; daikon.Dictionary.GROUP_INDICES[0x0100] = 2677; daikon.Dictionary.GROUP_INDICES[0x0400] = 2681; daikon.Dictionary.dictPrivate = [ [0x0207,0x101F,"ElscintDataScale","FE"] // uses special Elscint double type (see Tag class) ]; daikon.Dictionary.dict = [ [0x0002,0x0000,"Group0002Length","UL"], [0x0002,0x0001,"FileMetaInformationVersion","OB"], [0x0002,0x0002,"MediaStoredSOPClassUID","UI"], [0x0002,0x0003,"MediaStoredSOPInstanceUID","UI"], [0x0002,0x0010,"TransferSyntaxUID","UI"], [0x0002,0x0012,"ImplementationClassUID","UI"], [0x0002,0x0013,"ImplementationVersionName","SH"], [0x0002,0x0016,"SourceApplicationEntityTitle","AE"], [0x0002,0x0100,"PrivateInformationCreatorUID","UI"], [0x0002,0x0102,"PrivateInformation","OB"], [0x0004,0x0000,"Group0004Length","UL"], [0x0004,0x1130,"FilesetID","CS"], [0x0004,0x1141,"FilesetDescriptorFileFileID","CS"], [0x0004,0x1142,"FilesetDescriptorFileFormat","CS"], [0x0004,0x1200,"RootDirectoryEntitysFirstDirectoryRecordOffset","UL"], [0x0004,0x1202,"RootDirectoryEntitysLastDirectoryRecordOffset","UL"], [0x0004,0x1212,"File-setConsistenceFlag","US"], [0x0004,0x1220,"DirectoryRecordSequence","SQ"], [0x0004,0x1400,"NextDirectoryRecordOffset","UL"], [0x0004,0x1410,"RecordInuseFlag","US"], [0x0004,0x1420,"ReferencedLowerlevelDirectoryEntityOffset","UL"], [0x0004,0x1430,"DirectoryRecordType","CS"], [0x0004,0x1432,"PrivateRecordUID","UI"], [0x0004,0x1500,"ReferencedFileID","CS"], [0x0004,0x1510,"ReferencedSOPClassUIDInFile","UI"], [0x0004,0x1511,"ReferencedSOPInstanceUIDInFile","UI"], [0x0004,0x1600,"NumberOfReferences","UL"], [0x0008,0x0001,"LengthToEnd","UL"], [0x0008,0x0005,"SpecificCharacterSet","CS"], [0x0008,0x0006,"LanguageCodeSequence","SQ"], [0x0008,0x0008,"ImageType","CS"], [0x0008,0x0010,"RecognitionCode","SH"], [0x0008,0x0012,"InstanceCreationDate","DA"], [0x0008,0x0013,"InstanceCreationTime","TM"], [0x0008,0x0014,"InstanceCreatorUID","UI"], [0x0008,0x0016,"SOPClassUID","UI"], [0x0008,0x0018,"SOPInstanceUID","UI"], [0x0008,0x001A,"RelatedGeneralSOPClassUID","UI"], [0x0008,0x001B,"OriginalSpecializedSOPClassUID","UI"], [0x0008,0x0020,"StudyDate","DA"], [0x0008,0x0021,"SeriesDate","DA"], [0x0008,0x0022,"AcquisitionDate","DA"], [0x0008,0x0023,"ContentDate","DA"], [0x0008,0x0024,"OverlayDate","DA"], [0x0008,0x0025,"CurveDate","DA"], [0x0008,0x002A,"AcquisitionDateTime","DT"], [0x0008,0x0030,"StudyTime","TM"], [0x0008,0x0031,"SeriesTime","TM"], [0x0008,0x0032,"AcquisitionTime","TM"], [0x0008,0x0033,"ContentTime","TM"], [0x0008,0x0034,"OverlayTime","TM"], [0x0008,0x0035,"CurveTime","TM"], [0x0008,0x0040,"DataSetType","US"], [0x0008,0x0041,"DataSetSubtype","LO"], [0x0008,0x0042,"NuclearMedicineSeriesType","CS"], [0x0008,0x0050,"AccessionNumber","SH"], [0x0008,0x0051,"IssuerOfAccessionNumberSequence","SQ"], [0x0008,0x0052,"QueryRetrieveLevel","CS"], [0x0008,0x0054,"RetrieveAETitle","AE"], [0x0008,0x0056,"InstanceAvailability","CS"], [0x0008,0x0058,"FailedSOPInstanceUIDList","UI"], [0x0008,0x0060,"Modality","CS"], [0x0008,0x0061,"ModalitiesInStudy","CS"], [0x0008,0x0062,"SOPClassesInStudy","UI"], [0x0008,0x0064,"ConversionType","CS"], [0x0008,0x0068,"PresentationIntentType","CS"], [0x0008,0x0070,"Manufacturer","LO"], [0x0008,0x0080,"InstitutionName","LO"], [0x0008,0x0081,"InstitutionAddress","ST"], [0x0008,0x0082,"InstitutionCodeSequence","SQ"], [0x0008,0x0090,"ReferringPhysicianName","PN"], [0x0008,0x0092,"ReferringPhysicianAddress","ST"], [0x0008,0x0094,"ReferringPhysicianTelephoneNumbers","SH"], [0x0008,0x0096,"ReferringPhysicianIdentificationSequence","SQ"], [0x0008,0x0100,"CodeValue","SH"], [0x0008,0x0102,"CodingSchemeDesignator","SH"], [0x0008,0x0103,"CodingSchemeVersion","SH"], [0x0008,0x0104,"CodeMeaning","LO"], [0x0008,0x0105,"MappingResource","CS"], [0x0008,0x0106,"ContextGroupVersion","DT"], [0x0008,0x0107,"ContextGroupLocalVersion","DT"], [0x0008,0x010B,"ContextGroupExtensionFlag","CS"], [0x0008,0x010C,"CodingSchemeUID","UI"], [0x0008,0x010D,"ContextGroupExtensionCreatorUID","UI"], [0x0008,0x010F,"ContextIdentifier","CS"], [0x0008,0x0110,"CodingSchemeIdentificationSequence","SQ"], [0x0008,0x0112,"CodingSchemeRegistry","LO"], [0x0008,0x0114,"CodingSchemeExternalID","ST"], [0x0008,0x0115,"CodingSchemeName","ST"], [0x0008,0x0116,"CodingSchemeResponsibleOrganization","ST"], [0x0008,0x0117,"ContextUID","UI"], [0x0008,0x0201,"TimezoneOffsetFromUTC","SH"], [0x0008,0x1000,"NetworkID","AE"], [0x0008,0x1010,"StationName","SH"], [0x0008,0x1030,"StudyDescription","LO"], [0x0008,0x1032,"ProcedureCodeSequence","SQ"], [0x0008,0x103E,"SeriesDescription","LO"], [0x0008,0x103F,"SeriesDescriptionCodeSequence","SQ"], [0x0008,0x1040,"InstitutionalDepartmentName","LO"], [0x0008,0x1048,"PhysiciansOfRecord","PN"], [0x0008,0x1049,"PhysiciansOfRecordIdentificationSequence","SQ"], [0x0008,0x1050,"PerformingPhysicianName","PN"], [0x0008,0x1052,"PerformingPhysicianIdentificationSequence","SQ"], [0x0008,0x1060,"NameOfPhysiciansReadingStudy","PN"], [0x0008,0x1062,"PhysiciansReadingStudyIdentificationSequence","SQ"], [0x0008,0x1070,"OperatorsName","PN"], [0x0008,0x1072,"OperatorIdentificationSequence","SQ"], [0x0008,0x1080,"AdmittingDiagnosesDescription","LO"], [0x0008,0x1084,"AdmittingDiagnosesCodeSequence","SQ"], [0x0008,0x1090,"ManufacturerModelName","LO"], [0x0008,0x1100,"ReferencedResultsSequence","SQ"], [0x0008,0x1110,"ReferencedStudySequence","SQ"], [0x0008,0x1111,"ReferencedPerformedProcedureStepSequence","SQ"], [0x0008,0x1115,"ReferencedSeriesSequence","SQ"], [0x0008,0x1120,"ReferencedPatientSequence","SQ"], [0x0008,0x1125,"ReferencedVisitSequence","SQ"], [0x0008,0x1130,"ReferencedOverlaySequence","SQ"], [0x0008,0x1134,"ReferencedStereometricInstanceSequence","SQ"], [0x0008,0x113A,"ReferencedWaveformSequence","SQ"], [0x0008,0x1140,"ReferencedImageSequence","SQ"], [0x0008,0x1145,"ReferencedCurveSequence","SQ"], [0x0008,0x114A,"ReferencedInstanceSequence","SQ"], [0x0008,0x114B,"ReferencedRealWorldValueMappingInstanceSequence","SQ"], [0x0008,0x1150,"ReferencedSOPClassUID","UI"], [0x0008,0x1155,"ReferencedSOPInstanceUID","UI"], [0x0008,0x115A,"SOPClassesSupported","UI"], [0x0008,0x1160,"ReferencedFrameNumber","IS"], [0x0008,0x1161,"SimpleFrameList","UL"], [0x0008,0x1162,"CalculatedFrameList","UL"], [0x0008,0x1163,"TimeRange","FD"], [0x0008,0x1164,"FrameExtractionSequence","SQ"], [0x0008,0x1167,"MultiFrameSourceSOPInstanceUID","UI"], [0x0008,0x1195,"TransactionUID","UI"], [0x0008,0x1197,"FailureReason","US"], [0x0008,0x1198,"FailedSOPSequence","SQ"], [0x0008,0x1199,"ReferencedSOPSequence","SQ"], [0x0008,0x1200,"StudiesContainingOtherReferencedInstancesSequence","SQ"], [0x0008,0x1250,"RelatedSeriesSequence","SQ"], [0x0008,0x2110,"LossyImageCompressionRetired","CS"], [0x0008,0x2111,"DerivationDescription","ST"], [0x0008,0x2112,"SourceImageSequence","SQ"], [0x0008,0x2120,"StageName","SH"], [0x0008,0x2122,"StageNumber","IS"], [0x0008,0x2124,"NumberOfStages","IS"], [0x0008,0x2127,"ViewName","SH"], [0x0008,0x2128,"ViewNumber","IS"], [0x0008,0x2129,"NumberOfEventTimers","IS"], [0x0008,0x212A,"NumberOfViewsInStage","IS"], [0x0008,0x2130,"EventElapsedTimes","DS"], [0x0008,0x2132,"EventTimerNames","LO"], [0x0008,0x2133,"EventTimerSequence","SQ"], [0x0008,0x2134,"EventTimeOffset","FD"], [0x0008,0x2135,"EventCodeSequence","SQ"], [0x0008,0x2142,"StartTrim","IS"], [0x0008,0x2143,"StopTrim","IS"], [0x0008,0x2144,"RecommendedDisplayFrameRate","IS"], [0x0008,0x2200,"TransducerPosition","CS"], [0x0008,0x2204,"TransducerOrientation","CS"], [0x0008,0x2208,"AnatomicStructure","CS"], [0x0008,0x2218,"AnatomicRegionSequence","SQ"], [0x0008,0x2220,"AnatomicRegionModifierSequence","SQ"], [0x0008,0x2228,"PrimaryAnatomicStructureSequence","SQ"], [0x0008,0x2229,"AnatomicStructureSpaceOrRegionSequence","SQ"], [0x0008,0x2230,"PrimaryAnatomicStructureModifierSequence","SQ"], [0x0008,0x2240,"TransducerPositionSequence","SQ"], [0x0008,0x2242,"TransducerPositionModifierSequence","SQ"], [0x0008,0x2244,"TransducerOrientationSequence","SQ"], [0x0008,0x2246,"TransducerOrientationModifierSequence","SQ"], [0x0008,0x2251,"AnatomicStructureSpaceOrRegionCodeSequenceTrial","SQ"], [0x0008,0x2253,"AnatomicPortalOfEntranceCodeSequenceTrial","SQ"], [0x0008,0x2255,"AnatomicApproachDirectionCodeSequenceTrial","SQ"], [0x0008,0x2256,"AnatomicPerspectiveDescriptionTrial","ST"], [0x0008,0x2257,"AnatomicPerspectiveCodeSequenceTrial","SQ"], [0x0008,0x2258,"AnatomicLocationOfExaminingInstrumentDescriptionTrial","ST"], [0x0008,0x2259,"AnatomicLocationOfExaminingInstrumentCodeSequenceTrial","SQ"], [0x0008,0x225A,"AnatomicStructureSpaceOrRegionModifierCodeSequenceTrial","SQ"], [0x0008,0x225C,"OnAxisBackgroundAnatomicStructureCodeSequenceTrial","SQ"], [0x0008,0x3001,"AlternateRepresentationSequence","SQ"], [0x0008,0x3010,"IrradiationEventUID","UI"], [0x0008,0x4000,"IdentifyingComments","LT"], [0x0008,0x9007,"FrameType","CS"], [0x0008,0x9092,"ReferencedImageEvidenceSequence","SQ"], [0x0008,0x9121,"ReferencedRawDataSequence","SQ"], [0x0008,0x9123,"CreatorVersionUID","UI"], [0x0008,0x9124,"DerivationImageSequence","SQ"], [0x0008,0x9154,"SourceImageEvidenceSequence","SQ"], [0x0008,0x9205,"PixelPresentation","CS"], [0x0008,0x9206,"VolumetricProperties","CS"], [0x0008,0x9207,"VolumeBasedCalculationTechnique","CS"], [0x0008,0x9208,"ComplexImageComponent","CS"], [0x0008,0x9209,"AcquisitionContrast","CS"], [0x0008,0x9215,"DerivationCodeSequence","SQ"], [0x0008,0x9237,"ReferencedPresentationStateSequence","SQ"], [0x0008,0x9410,"ReferencedOtherPlaneSequence","SQ"], [0x0008,0x9458,"FrameDisplaySequence","SQ"], [0x0008,0x9459,"RecommendedDisplayFrameRateInFloat","FL"], [0x0008,0x9460,"SkipFrameRangeFlag","CS"], [0x0010,0x0010,"PatientName","PN"], [0x0010,0x0020,"PatientID","LO"], [0x0010,0x0021,"IssuerOfPatientID","LO"], [0x0010,0x0022,"TypeOfPatientID","CS"], [0x0010,0x0024,"IssuerOfPatientIDQualifiersSequence","SQ"], [0x0010,0x0030,"PatientBirthDate","DA"], [0x0010,0x0032,"PatientBirthTime","TM"], [0x0010,0x0040,"PatientSex","CS"], [0x0010,0x0050,"PatientInsurancePlanCodeSequence","SQ"], [0x0010,0x0101,"PatientPrimaryLanguageCodeSequence","SQ"], [0x0010,0x0102,"PatientPrimaryLanguageModifierCodeSequence","SQ"], [0x0010,0x1000,"OtherPatientIDs","LO"], [0x0010,0x1001,"OtherPatientNames","PN"], [0x0010,0x1002,"OtherPatientIDsSequence","SQ"], [0x0010,0x1005,"PatientBirthName","PN"], [0x0010,0x1010,"PatientAge","AS"], [0x0010,0x1020,"PatientSize","DS"], [0x0010,0x1021,"PatientSizeCodeSequence","SQ"], [0x0010,0x1030,"PatientWeight","DS"], [0x0010,0x1040,"PatientAddress","LO"], [0x0010,0x1050,"InsurancePlanIdentification","LO"], [0x0010,0x1060,"PatientMotherBirthName","PN"], [0x0010,0x1080,"MilitaryRank","LO"], [0x0010,0x1081,"BranchOfService","LO"], [0x0010,0x1090,"MedicalRecordLocator","LO"], [0x0010,0x2000,"MedicalAlerts","LO"], [0x0010,0x2110,"Allergies","LO"], [0x0010,0x2150,"CountryOfResidence","LO"], [0x0010,0x2152,"RegionOfResidence","LO"], [0x0010,0x2154,"PatientTelephoneNumbers","SH"], [0x0010,0x2160,"EthnicGroup","SH"], [0x0010,0x2180,"Occupation","SH"], [0x0010,0x21A0,"SmokingStatus","CS"], [0x0010,0x21B0,"AdditionalPatientHistory","LT"], [0x0010,0x21C0,"PregnancyStatus","US"], [0x0010,0x21D0,"LastMenstrualDate","DA"], [0x0010,0x21F0,"PatientReligiousPreference","LO"], [0x0010,0x2201,"PatientSpeciesDescription","LO"], [0x0010,0x2202,"PatientSpeciesCodeSequence","SQ"], [0x0010,0x2203,"PatientSexNeutered","CS"], [0x0010,0x2210,"AnatomicalOrientationType","CS"], [0x0010,0x2292,"PatientBreedDescription","LO"], [0x0010,0x2293,"PatientBreedCodeSequence","SQ"], [0x0010,0x2294,"BreedRegistrationSequence","SQ"], [0x0010,0x2295,"BreedRegistrationNumber","LO"], [0x0010,0x2296,"BreedRegistryCodeSequence","SQ"], [0x0010,0x2297,"ResponsiblePerson","PN"], [0x0010,0x2298,"ResponsiblePersonRole","CS"], [0x0010,0x2299,"ResponsibleOrganization","LO"], [0x0010,0x4000,"PatientComments","LT"], [0x0010,0x9431,"ExaminedBodyThickness","FL"], [0x0012,0x0010,"ClinicalTrialSponsorName","LO"], [0x0012,0x0020,"ClinicalTrialProtocolID","LO"], [0x0012,0x0021,"ClinicalTrialProtocolName","LO"], [0x0012,0x0030,"ClinicalTrialSiteID","LO"], [0x0012,0x0031,"ClinicalTrialSiteName","LO"], [0x0012,0x0040,"ClinicalTrialSubjectID","LO"], [0x0012,0x0042,"ClinicalTrialSubjectReadingID","LO"], [0x0012,0x0050,"ClinicalTrialTimePointID","LO"], [0x0012,0x0051,"ClinicalTrialTimePointDescription","ST"], [0x0012,0x0060,"ClinicalTrialCoordinatingCenterName","LO"], [0x0012,0x0062,"PatientIdentityRemoved","CS"], [0x0012,0x0063,"DeidentificationMethod","LO"], [0x0012,0x0064,"DeidentificationMethodCodeSequence","SQ"], [0x0012,0x0071,"ClinicalTrialSeriesID","LO"], [0x0012,0x0072,"ClinicalTrialSeriesDescription","LO"], [0x0012,0x0081,"ClinicalTrialProtocolEthicsCommitteeName","LO"], [0x0012,0x0082,"ClinicalTrialProtocolEthicsCommitteeApprovalNumber","LO"], [0x0012,0x0083,"ConsentForClinicalTrialUseSequence","SQ"], [0x0012,0x0084,"DistributionType","CS"], [0x0012,0x0085,"ConsentForDistributionFlag","CS"], [0x0014,0x0023,"CADFileFormat","ST"], [0x0014,0x0024,"ComponentReferenceSystem","ST"], [0x0014,0x0025,"ComponentManufacturingProcedure","ST"], [0x0014,0x0028,"ComponentManufacturer","ST"], [0x0014,0x0030,"MaterialThickness","DS"], [0x0014,0x0032,"MaterialPipeDiameter","DS"], [0x0014,0x0034,"MaterialIsolationDiameter","DS"], [0x0014,0x0042,"MaterialGrade","ST"], [0x0014,0x0044,"MaterialPropertiesFileID","ST"], [0x0014,0x0045,"MaterialPropertiesFileFormat","ST"], [0x0014,0x0046,"MaterialNotes","LT"], [0x0014,0x0050,"ComponentShape","CS"], [0x0014,0x0052,"CurvatureType","CS"], [0x0014,0x0054,"OuterDiameter","DS"], [0x0014,0x0056,"InnerDiameter","DS"], [0x0014,0x1010,"ActualEnvironmentalConditions","ST"], [0x0014,0x1020,"ExpiryDate","DA"], [0x0014,0x1040,"EnvironmentalConditions","ST"], [0x0014,0x2002,"EvaluatorSequence","SQ"], [0x0014,0x2004,"EvaluatorNumber","IS"], [0x0014,0x2006,"EvaluatorName","PN"], [0x0014,0x2008,"EvaluationAttempt","IS"], [0x0014,0x2012,"IndicationSequence","SQ"], [0x0014,0x2014,"IndicationNumber ","IS"], [0x0014,0x2016,"IndicationLabel","SH"], [0x0014,0x2018,"IndicationDescription","ST"], [0x0014,0x201A,"IndicationType","CS"], [0x0014,0x201C,"IndicationDisposition","CS"], [0x0014,0x201E,"IndicationROISequence","SQ"], [0x0014,0x2030,"IndicationPhysicalPropertySequence","SQ"], [0x0014,0x2032,"PropertyLabel","SH"], [0x0014,0x2202,"CoordinateSystemNumberOfAxes ","IS"], [0x0014,0x2204,"CoordinateSystemAxesSequence","SQ"], [0x0014,0x2206,"CoordinateSystemAxisDescription","ST"], [0x0014,0x2208,"CoordinateSystemDataSetMapping","CS"], [0x0014,0x220A,"CoordinateSystemAxisNumber","IS"], [0x0014,0x220C,"CoordinateSystemAxisType","CS"], [0x0014,0x220E,"CoordinateSystemAxisUnits","CS"], [0x0014,0x2210,"CoordinateSystemAxisValues","OB"], [0x0014,0x2220,"CoordinateSystemTransformSequence","SQ"], [0x0014,0x2222,"TransformDescription","ST"], [0x0014,0x2224,"TransformNumberOfAxes","IS"], [0x0014,0x2226,"TransformOrderOfAxes","IS"], [0x0014,0x2228,"TransformedAxisUnits","CS"], [0x0014,0x222A,"CoordinateSystemTransformRotationAndScaleMatrix","DS"], [0x0014,0x222C,"CoordinateSystemTransformTranslationMatrix","DS"], [0x0014,0x3011,"InternalDetectorFrameTime","DS"], [0x0014,0x3012,"NumberOfFramesIntegrated","DS"], [0x0014,0x3020,"DetectorTemperatureSequence","SQ"], [0x0014,0x3022,"SensorName","DS"], [0x0014,0x3024,"HorizontalOffsetOfSensor","DS"], [0x0014,0x3026,"VerticalOffsetOfSensor","DS"], [0x0014,0x3028,"SensorTemperature","DS"], [0x0014,0x3040,"DarkCurrentSequence","SQ"], [0x0014,0x3050,"DarkCurrentCounts","OB"], [0x0014,0x3060,"GainCorrectionReferenceSequence","SQ"], [0x0014,0x3070,"AirCounts","OB"], [0x0014,0x3071,"KVUsedInGainCalibration","DS"], [0x0014,0x3072,"MAUsedInGainCalibration","DS"], [0x0014,0x3073,"NumberOfFramesUsedForIntegration","DS"], [0x0014,0x3074,"FilterMaterialUsedInGainCalibration","LO"], [0x0014,0x3075,"FilterThicknessUsedInGainCalibration","DS"], [0x0014,0x3076,"DateOfGainCalibration","DA"], [0x0014,0x3077,"TimeOfGainCalibration","TM"], [0x0014,0x3080,"BadPixelImage","OB"], [0x0014,0x3099,"CalibrationNotes","LT"], [0x0014,0x4002,"PulserEquipmentSequence","SQ"], [0x0014,0x4004,"PulserType","CS"], [0x0014,0x4006,"PulserNotes","LT"], [0x0014,0x4008,"ReceiverEquipmentSequence","SQ"], [0x0014,0x400A,"AmplifierType","CS"], [0x0014,0x400C,"ReceiverNotes","LT"], [0x0014,0x400E,"PreAmplifierEquipmentSequence","SQ"], [0x0014,0x400F,"PreAmplifierNotes","LT"], [0x0014,0x4010,"TransmitTransducerSequence","SQ"], [0x0014,0x4011,"ReceiveTransducerSequence","SQ"], [0x0014,0x4012,"NumberOfElements","US"], [0x0014,0x4013,"ElementShape","CS"], [0x0014,0x4014,"ElementDimensionA","DS"], [0x0014,0x4015,"ElementDimensionB","DS"], [0x0014,0x4016,"ElementPitch","DS"], [0x0014,0x4017,"MeasuredBeamDimensionA","DS"], [0x0014,0x4018,"MeasuredBeamDimensionB","DS"], [0x0014,0x4019,"LocationOfMeasuredBeamDiameter","DS"], [0x0014,0x401A,"NominalFrequency","DS"], [0x0014,0x401B,"MeasuredCenterFrequency","DS"], [0x0014,0x401C,"MeasuredBandwidth","DS"], [0x0014,0x4020,"PulserSettingsSequence","SQ"], [0x0014,0x4022,"PulseWidth","DS"], [0x0014,0x4024,"ExcitationFrequency","DS"], [0x0014,0x4026,"ModulationType","CS"], [0x0014,0x4028,"Damping","DS"], [0x0014,0x4030,"ReceiverSettingsSequence","SQ"], [0x0014,0x4031,"AcquiredSoundpathLength","DS"], [0x0014,0x4032,"AcquisitionCompressionType","CS"], [0x0014,0x4033,"AcquisitionSampleSize","IS"], [0x0014,0x4034,"RectifierSmoothing","DS"], [0x0014,0x4035,"DACSequence","SQ"], [0x0014,0x4036,"DACType","CS"], [0x0014,0x4038,"DACGainPoints","DS"], [0x0014,0x403A,"DACTimePoints","DS"], [0x0014,0x403C,"DACAmplitude","DS"], [0x0014,0x4040,"PreAmplifierSettingsSequence","SQ"], [0x0014,0x4050,"TransmitTransducerSettingsSequence","SQ"], [0x0014,0x4051,"ReceiveTransducerSettingsSequence","SQ"], [0x0014,0x4052,"IncidentAngle","DS"], [0x0014,0x4054,"CouplingTechnique","ST"], [0x0014,0x4056,"CouplingMedium","ST"], [0x0014,0x4057,"CouplingVelocity","DS"], [0x0014,0x4058,"CrystalCenterLocationX","DS"], [0x0014,0x4059,"CrystalCenterLocationZ","DS"], [0x0014,0x405A,"SoundPathLength","DS"], [0x0014,0x405C,"DelayLawIdentifier","ST"], [0x0014,0x4060,"GateSettingsSequence","SQ"], [0x0014,0x4062,"GateThreshold","DS"], [0x0014,0x4064,"VelocityOfSound","DS"], [0x0014,0x4070,"CalibrationSettingsSequence","SQ"], [0x0014,0x4072,"CalibrationProcedure","ST"], [0x0014,0x4074,"ProcedureVersion","SH"], [0x0014,0x4076,"ProcedureCreationDate","DA"], [0x0014,0x4078,"ProcedureExpirationDate","DA"], [0x0014,0x407A,"ProcedureLastModifiedDate","DA"], [0x0014,0x407C,"CalibrationTime","TM"], [0x0014,0x407E,"CalibrationDate","DA"], [0x0014,0x5002,"LINACEnergy","IS"], [0x0014,0x5004,"LINACOutput","IS"], [0x0018,0x0010,"ContrastBolusAgent","LO"], [0x0018,0x0012,"ContrastBolusAgentSequence","SQ"], [0x0018,0x0014,"ContrastBolusAdministrationRouteSequence","SQ"], [0x0018,0x0015,"BodyPartExamined","CS"], [0x0018,0x0020,"ScanningSequence","CS"], [0x0018,0x0021,"SequenceVariant","CS"], [0x0018,0x0022,"ScanOptions","CS"], [0x0018,0x0023,"MRAcquisitionType","CS"], [0x0018,0x0024,"SequenceName","SH"], [0x0018,0x0025,"AngioFlag","CS"], [0x0018,0x0026,"InterventionDrugInformationSequence","SQ"], [0x0018,0x0027,"InterventionDrugStopTime","TM"], [0x0018,0x0028,"InterventionDrugDose","DS"], [0x0018,0x0029,"InterventionDrugCodeSequence","SQ"], [0x0018,0x002A,"AdditionalDrugSequence","SQ"], [0x0018,0x0030,"Radionuclide","LO"], [0x0018,0x0031,"Radiopharmaceutical","LO"], [0x0018,0x0032,"EnergyWindowCenterline","DS"], [0x0018,0x0033,"EnergyWindowTotalWidth","DS"], [0x0018,0x0034,"InterventionDrugName","LO"], [0x0018,0x0035,"InterventionDrugStartTime","TM"], [0x0018,0x0036,"InterventionSequence","SQ"], [0x0018,0x0037,"TherapyType","CS"], [0x0018,0x0038,"InterventionStatus","CS"], [0x0018,0x0039,"TherapyDescription","CS"], [0x0018,0x003A,"InterventionDescription","ST"], [0x0018,0x0040,"CineRate","IS"], [0x0018,0x0042,"InitialCineRunState","CS"], [0x0018,0x0050,"SliceThickness","DS"], [0x0018,0x0060,"KVP","DS"], [0x0018,0x0070,"CountsAccumulated","IS"], [0x0018,0x0071,"AcquisitionTerminationCondition","CS"], [0x0018,0x0072,"EffectiveDuration","DS"], [0x0018,0x0073,"AcquisitionStartCondition","CS"], [0x0018,0x0074,"AcquisitionStartConditionData","IS"], [0x0018,0x0075,"AcquisitionTerminationConditionData","IS"], [0x0018,0x0080,"RepetitionTime","DS"], [0x0018,0x0081,"EchoTime","DS"], [0x0018,0x0082,"InversionTime","DS"], [0x0018,0x0083,"NumberOfAverages","DS"], [0x0018,0x0084,"ImagingFrequency","DS"], [0x0018,0x0085,"ImagedNucleus","SH"], [0x0018,0x0086,"EchoNumbers","IS"], [0x0018,0x0087,"MagneticFieldStrength","DS"], [0x0018,0x0088,"SpacingBetweenSlices","DS"], [0x0018,0x0089,"NumberOfPhaseEncodingSteps","IS"], [0x0018,0x0090,"DataCollectionDiameter","DS"], [0x0018,0x0091,"EchoTrainLength","IS"], [0x0018,0x0093,"PercentSampling","DS"], [0x0018,0x0094,"PercentPhaseFieldOfView","DS"], [0x0018,0x0095,"PixelBandwidth","DS"], [0x0018,0x1000,"DeviceSerialNumber","LO"], [0x0018,0x1002,"DeviceUID","UI"], [0x0018,0x1003,"DeviceID","LO"], [0x0018,0x1004,"PlateID","LO"], [0x0018,0x1005,"GeneratorID","LO"], [0x0018,0x1006,"GridID","LO"], [0x0018,0x1007,"CassetteID","LO"], [0x0018,0x1008,"GantryID","LO"], [0x0018,0x1010,"SecondaryCaptureDeviceID","LO"], [0x0018,0x1011,"HardcopyCreationDeviceID","LO"], [0x0018,0x1012,"DateOfSecondaryCapture","DA"], [0x0018,0x1014,"TimeOfSecondaryCapture","TM"], [0x0018,0x1016,"SecondaryCaptureDeviceManufacturer","LO"], [0x0018,0x1017,"HardcopyDeviceManufacturer","LO"], [0x0018,0x1018,"SecondaryCaptureDeviceManufacturerModelName","LO"], [0x0018,0x1019,"SecondaryCaptureDeviceSoftwareVersions","LO"], [0x0018,0x101A,"HardcopyDeviceSoftwareVersion","LO"], [0x0018,0x101B,"HardcopyDeviceManufacturerModelName","LO"], [0x0018,0x1020,"SoftwareVersions","LO"], [0x0018,0x1022,"VideoImageFormatAcquired","SH"], [0x0018,0x1023,"DigitalImageFormatAcquired","LO"], [0x0018,0x1030,"ProtocolName","LO"], [0x0018,0x1040,"ContrastBolusRoute","LO"], [0x0018,0x1041,"ContrastBolusVolume","DS"], [0x0018,0x1042,"ContrastBolusStartTime","TM"], [0x0018,0x1043,"ContrastBolusStopTime","TM"], [0x0018,0x1044,"ContrastBolusTotalDose","DS"], [0x0018,0x1045,"SyringeCounts","IS"], [0x0018,0x1046,"ContrastFlowRate","DS"], [0x0018,0x1047,"ContrastFlowDuration","DS"], [0x0018,0x1048,"ContrastBolusIngredient","CS"], [0x0018,0x1049,"ContrastBolusIngredientConcentration","DS"], [0x0018,0x1050,"SpatialResolution","DS"], [0x0018,0x1060,"TriggerTime","DS"], [0x0018,0x1061,"TriggerSourceOrType","LO"], [0x0018,0x1062,"NominalInterval","IS"], [0x0018,0x1063,"FrameTime","DS"], [0x0018,0x1064,"CardiacFramingType","LO"], [0x0018,0x1065,"FrameTimeVector","DS"], [0x0018,0x1066,"FrameDelay","DS"], [0x0018,0x1067,"ImageTriggerDelay","DS"], [0x0018,0x1068,"MultiplexGroupTimeOffset","DS"], [0x0018,0x1069,"TriggerTimeOffset","DS"], [0x0018,0x106A,"SynchronizationTrigger","CS"], [0x0018,0x106C,"SynchronizationChannel","US"], [0x0018,0x106E,"TriggerSamplePosition","UL"], [0x0018,0x1070,"RadiopharmaceuticalRoute","LO"], [0x0018,0x1071,"RadiopharmaceuticalVolume","DS"], [0x0018,0x1072,"RadiopharmaceuticalStartTime","TM"], [0x0018,0x1073,"RadiopharmaceuticalStopTime","TM"], [0x0018,0x1074,"RadionuclideTotalDose","DS"], [0x0018,0x1075,"RadionuclideHalfLife","DS"], [0x0018,0x1076,"RadionuclidePositronFraction","DS"], [0x0018,0x1077,"RadiopharmaceuticalSpecificActivity","DS"], [0x0018,0x1078,"RadiopharmaceuticalStartDateTime","DT"], [0x0018,0x1079,"RadiopharmaceuticalStopDateTime","DT"], [0x0018,0x1080,"BeatRejectionFlag","CS"], [0x0018,0x1081,"LowRRValue","IS"], [0x0018,0x1082,"HighRRValue","IS"], [0x0018,0x1083,"IntervalsAcquired","IS"], [0x0018,0x1084,"IntervalsRejected","IS"], [0x0018,0x1085,"PVCRejection","LO"], [0x0018,0x1086,"SkipBeats","IS"], [0x0018,0x1088,"HeartRate","IS"], [0x0018,0x1090,"CardiacNumberOfImages","IS"], [0x0018,0x1094,"TriggerWindow","IS"], [0x0018,0x1100,"ReconstructionDiameter","DS"], [0x0018,0x1110,"DistanceSourceToDetector","DS"], [0x0018,0x1111,"DistanceSourceToPatient","DS"], [0x0018,0x1114,"EstimatedRadiographicMagnificationFactor","DS"], [0x0018,0x1120,"GantryDetectorTilt","DS"], [0x0018,0x1121,"GantryDetectorSlew","DS"], [0x0018,0x1130,"TableHeight","DS"], [0x0018,0x1131,"TableTraverse","DS"], [0x0018,0x1134,"TableMotion","CS"], [0x0018,0x1135,"TableVerticalIncrement","DS"], [0x0018,0x1136,"TableLateralIncrement","DS"], [0x0018,0x1137,"TableLongitudinalIncrement","DS"], [0x0018,0x1138,"TableAngle","DS"], [0x0018,0x113A,"TableType","CS"], [0x0018,0x1140,"RotationDirection","CS"], [0x0018,0x1141,"AngularPosition","DS"], [0x0018,0x1142,"RadialPosition","DS"], [0x0018,0x1143,"ScanArc","DS"], [0x0018,0x1144,"AngularStep","DS"], [0x0018,0x1145,"CenterOfRotationOffset","DS"], [0x0018,0x1146,"RotationOffset","DS"], [0x0018,0x1147,"FieldOfViewShape","CS"], [0x0018,0x1149,"FieldOfViewDimensions","IS"], [0x0018,0x1150,"ExposureTime","IS"], [0x0018,0x1151,"XRayTubeCurrent","IS"], [0x0018,0x1152,"Exposure","IS"], [0x0018,0x1153,"ExposureInuAs","IS"], [0x0018,0x1154,"AveragePulseWidth","DS"], [0x0018,0x1155,"RadiationSetting","CS"], [0x0018,0x1156,"RectificationType","CS"], [0x0018,0x115A,"RadiationMode","CS"], [0x0018,0x115E,"ImageAndFluoroscopyAreaDoseProduct","DS"], [0x0018,0x1160,"FilterType","SH"], [0x0018,0x1161,"TypeOfFilters","LO"], [0x0018,0x1162,"IntensifierSize","DS"], [0x0018,0x1164,"ImagerPixelSpacing","DS"], [0x0018,0x1166,"Grid","CS"], [0x0018,0x1170,"GeneratorPower","IS"], [0x0018,0x1180,"CollimatorGridName","SH"], [0x0018,0x1181,"CollimatorType","CS"], [0x0018,0x1182,"FocalDistance","IS"], [0x0018,0x1183,"XFocusCenter","DS"], [0x0018,0x1184,"YFocusCenter","DS"], [0x0018,0x1190,"FocalSpots","DS"], [0x0018,0x1191,"AnodeTargetMaterial","CS"], [0x0018,0x11A0,"BodyPartThickness","DS"], [0x0018,0x11A2,"CompressionForce","DS"], [0x0018,0x1200,"DateOfLastCalibration","DA"], [0x0018,0x1201,"TimeOfLastCalibration","TM"], [0x0018,0x1210,"ConvolutionKernel","SH"], [0x0018,0x1240,"UpperLowerPixelValues","IS"], [0x0018,0x1242,"ActualFrameDuration","IS"], [0x0018,0x1243,"CountRate","IS"], [0x0018,0x1244,"PreferredPlaybackSequencing","US"], [0x0018,0x1250,"ReceiveCoilName","SH"], [0x0018,0x1251,"TransmitCoilName","SH"], [0x0018,0x1260,"PlateType","SH"], [0x0018,0x1261,"PhosphorType","LO"], [0x0018,0x1300,"ScanVelocity","DS"], [0x0018,0x1301,"WholeBodyTechnique","CS"], [0x0018,0x1302,"ScanLength","IS"], [0x0018,0x1310,"AcquisitionMatrix","US"], [0x0018,0x1312,"InPlanePhaseEncodingDirection","CS"], [0x0018,0x1314,"FlipAngle","DS"], [0x0018,0x1315,"VariableFlipAngleFlag","CS"], [0x0018,0x1316,"SAR","DS"], [0x0018,0x1318,"dBdt","DS"], [0x0018,0x1400,"AcquisitionDeviceProcessingDescription","LO"], [0x0018,0x1401,"AcquisitionDeviceProcessingCode","LO"], [0x0018,0x1402,"CassetteOrientation","CS"], [0x0018,0x1403,"CassetteSize","CS"], [0x0018,0x1404,"ExposuresOnPlate","US"], [0x0018,0x1405,"RelativeXRayExposure","IS"], [0x0018,0x1411,"ExposureIndex","DS"], [0x0018,0x1412,"TargetExposureIndex","DS"], [0x0018,0x1413,"DeviationIndex","DS"], [0x0018,0x1450,"ColumnAngulation","DS"], [0x0018,0x1460,"TomoLayerHeight","DS"], [0x0018,0x1470,"TomoAngle","DS"], [0x0018,0x1480,"TomoTime","DS"], [0x0018,0x1490,"TomoType","CS"], [0x0018,0x1491,"TomoClass","CS"], [0x0018,0x1495,"NumberOfTomosynthesisSourceImages","IS"], [0x0018,0x1500,"PositionerMotion","CS"], [0x0018,0x1508,"PositionerType","CS"], [0x0018,0x1510,"PositionerPrimaryAngle","DS"], [0x0018,0x1511,"PositionerSecondaryAngle","DS"], [0x0018,0x1520,"PositionerPrimaryAngleIncrement","DS"], [0x0018,0x1521,"PositionerSecondaryAngleIncrement","DS"], [0x0018,0x1530,"DetectorPrimaryAngle","DS"], [0x0018,0x1531,"DetectorSecondaryAngle","DS"], [0x0018,0x1600,"ShutterShape","CS"], [0x0018,0x1602,"ShutterLeftVerticalEdge","IS"], [0x0018,0x1604,"ShutterRightVerticalEdge","IS"], [0x0018,0x1606,"ShutterUpperHorizontalEdge","IS"], [0x0018,0x1608,"ShutterLowerHorizontalEdge","IS"], [0x0018,0x1610,"CenterOfCircularShutter","IS"], [0x0018,0x1612,"RadiusOfCircularShutter","IS"], [0x0018,0x1620,"VerticesOfThePolygonalShutter","IS"], [0x0018,0x1622,"ShutterPresentationValue","US"], [0x0018,0x1623,"ShutterOverlayGroup","US"], [0x0018,0x1624,"ShutterPresentationColorCIELabValue","US"], [0x0018,0x1700,"CollimatorShape","CS"], [0x0018,0x1702,"CollimatorLeftVerticalEdge","IS"], [0x0018,0x1704,"CollimatorRightVerticalEdge","IS"], [0x0018,0x1706,"CollimatorUpperHorizontalEdge","IS"], [0x0018,0x1708,"CollimatorLowerHorizontalEdge","IS"], [0x0018,0x1710,"CenterOfCircularCollimator","IS"], [0x0018,0x1712,"RadiusOfCircularCollimator","IS"], [0x0018,0x1720,"VerticesOfThePolygonalCollimator","IS"], [0x0018,0x1800,"AcquisitionTimeSynchronized","CS"], [0x0018,0x1801,"TimeSource","SH"], [0x0018,0x1802,"TimeDistributionProtocol","CS"], [0x0018,0x1803,"NTPSourceAddress","LO"], [0x0018,0x2001,"PageNumberVector","IS"], [0x0018,0x2002,"FrameLabelVector","SH"], [0x0018,0x2003,"FramePrimaryAngleVector","DS"], [0x0018,0x2004,"FrameSecondaryAngleVector","DS"], [0x0018,0x2005,"SliceLocationVector","DS"], [0x0018,0x2006,"DisplayWindowLabelVector","SH"], [0x0018,0x2010,"NominalScannedPixelSpacing","DS"], [0x0018,0x2020,"DigitizingDeviceTransportDirection","CS"], [0x0018,0x2030,"RotationOfScannedFilm","DS"], [0x0018,0x3100,"IVUSAcquisition","CS"], [0x0018,0x3101,"IVUSPullbackRate","DS"], [0x0018,0x3102,"IVUSGatedRate","DS"], [0x0018,0x3103,"IVUSPullbackStartFrameNumber","IS"], [0x0018,0x3104,"IVUSPullbackStopFrameNumber","IS"], [0x0018,0x3105,"LesionNumber","IS"], [0x0018,0x4000,"AcquisitionComments","LT"], [0x0018,0x5000,"OutputPower","SH"], [0x0018,0x5010,"TransducerData","LO"], [0x0018,0x5012,"FocusDepth","DS"], [0x0018,0x5020,"ProcessingFunction","LO"], [0x0018,0x5021,"PostprocessingFunction","LO"], [0x0018,0x5022,"MechanicalIndex","DS"], [0x0018,0x5024,"BoneThermalIndex","DS"], [0x0018,0x5026,"CranialThermalIndex","DS"], [0x0018,0x5027,"SoftTissueThermalIndex","DS"], [0x0018,0x5028,"SoftTissueFocusThermalIndex","DS"], [0x0018,0x5029,"SoftTissueSurfaceThermalIndex","DS"], [0x0018,0x5030,"DynamicRange","DS"], [0x0018,0x5040,"TotalGain","DS"], [0x0018,0x5050,"DepthOfScanField","IS"], [0x0018,0x5100,"PatientPosition","CS"], [0x0018,0x5101,"ViewPosition","CS"], [0x0018,0x5104,"ProjectionEponymousNameCodeSequence","SQ"], [0x0018,0x5210,"ImageTransformationMatrix","DS"], [0x0018,0x5212,"ImageTranslationVector","DS"], [0x0018,0x6000,"Sensitivity","DS"], [0x0018,0x6011,"SequenceOfUltrasoundRegions","SQ"], [0x0018,0x6012,"RegionSpatialFormat","US"], [0x0018,0x6014,"RegionDataType","US"], [0x0018,0x6016,"RegionFlags","UL"], [0x0018,0x6018,"RegionLocationMinX0","UL"], [0x0018,0x601A,"RegionLocationMinY0","UL"], [0x0018,0x601C,"RegionLocationMaxX1","UL"], [0x0018,0x601E,"RegionLocationMaxY1","UL"], [0x0018,0x6020,"ReferencePixelX0","SL"], [0x0018,0x6022,"ReferencePixelY0","SL"], [0x0018,0x6024,"PhysicalUnitsXDirection","US"], [0x0018,0x6026,"PhysicalUnitsYDirection","US"], [0x0018,0x6028,"ReferencePixelPhysicalValueX","FD"], [0x0018,0x602A,"ReferencePixelPhysicalValueY","FD"], [0x0018,0x602C,"PhysicalDeltaX","FD"], [0x0018,0x602E,"PhysicalDeltaY","FD"], [0x0018,0x6030,"TransducerFrequency","UL"], [0x0018,0x6031,"TransducerType","CS"], [0x0018,0x6032,"PulseRepetitionFrequency","UL"], [0x0018,0x6034,"DopplerCorrectionAngle","FD"], [0x0018,0x6036,"SteeringAngle","FD"], [0x0018,0x6038,"DopplerSampleVolumeXPositionRetired","UL"], [0x0018,0x6039,"DopplerSampleVolumeXPosition","SL"], [0x0018,0x603A,"DopplerSampleVolumeYPositionRetired","UL"], [0x0018,0x603B,"DopplerSampleVolumeYPosition","SL"], [0x0018,0x603C,"TMLinePositionX0Retired","UL"], [0x0018,0x603D,"TMLinePositionX0","SL"], [0x0018,0x603E,"TMLinePositionY0Retired","UL"], [0x0018,0x603F,"TMLinePositionY0","SL"], [0x0018,0x6040,"TMLinePositionX1Retired","UL"], [0x0018,0x6041,"TMLinePositionX1","SL"], [0x0018,0x6042,"TMLinePositionY1Retired","UL"], [0x0018,0x6043,"TMLinePositionY1","SL"], [0x0018,0x6044,"PixelComponentOrganization","US"], [0x0018,0x6046,"PixelComponentMask","UL"], [0x0018,0x6048,"PixelComponentRangeStart","UL"], [0x0018,0x604A,"PixelComponentRangeStop","UL"], [0x0018,0x604C,"PixelComponentPhysicalUnits","US"], [0x0018,0x604E,"PixelComponentDataType","US"], [0x0018,0x6050,"NumberOfTableBreakPoints","UL"], [0x0018,0x6052,"TableOfXBreakPoints","UL"], [0x0018,0x6054,"TableOfYBreakPoints","FD"], [0x0018,0x6056,"NumberOfTableEntries","UL"], [0x0018,0x6058,"TableOfPixelValues","UL"], [0x0018,0x605A,"TableOfParameterValues","FL"], [0x0018,0x6060,"RWaveTimeVector","FL"], [0x0018,0x7000,"DetectorConditionsNominalFlag","CS"], [0x0018,0x7001,"DetectorTemperature","DS"], [0x0018,0x7004,"DetectorType","CS"], [0x0018,0x7005,"DetectorConfiguration","CS"], [0x0018,0x7006,"DetectorDescription","LT"], [0x0018,0x7008,"DetectorMode","LT"], [0x0018,0x700A,"DetectorID","SH"], [0x0018,0x700C,"DateOfLastDetectorCalibration","DA"], [0x0018,0x700E,"TimeOfLastDetectorCalibration","TM"], [0x0018,0x7010,"ExposuresOnDetectorSinceLastCalibration","IS"], [0x0018,0x7011,"ExposuresOnDetectorSinceManufactured","IS"], [0x0018,0x7012,"DetectorTimeSinceLastExposure","DS"], [0x0018,0x7014,"DetectorActiveTime","DS"], [0x0018,0x7016,"DetectorActivationOffsetFromExposure","DS"], [0x0018,0x701A,"DetectorBinning","DS"], [0x0018,0x7020,"DetectorElementPhysicalSize","DS"], [0x0018,0x7022,"DetectorElementSpacing","DS"], [0x0018,0x7024,"DetectorActiveShape","CS"], [0x0018,0x7026,"DetectorActiveDimensions","DS"], [0x0018,0x7028,"DetectorActiveOrigin","DS"], [0x0018,0x702A,"DetectorManufacturerName","LO"], [0x0018,0x702B,"DetectorManufacturerModelName","LO"], [0x0018,0x7030,"FieldOfViewOrigin","DS"], [0x0018,0x7032,"FieldOfViewRotation","DS"], [0x0018,0x7034,"FieldOfViewHorizontalFlip","CS"], [0x0018,0x7036,"PixelDataAreaOriginRelativeToFOV","FL"], [0x0018,0x7038,"PixelDataAreaRotationAngleRelativeToFOV","FL"], [0x0018,0x7040,"GridAbsorbingMaterial","LT"], [0x0018,0x7041,"GridSpacingMaterial","LT"], [0x0018,0x7042,"GridThickness","DS"], [0x0018,0x7044,"GridPitch","DS"], [0x0018,0x7046,"GridAspectRatio","IS"], [0x0018,0x7048,"GridPeriod","DS"], [0x0018,0x704C,"GridFocalDistance","DS"], [0x0018,0x7050,"FilterMaterial","CS"], [0x0018,0x7052,"FilterThicknessMinimum","DS"], [0x0018,0x7054,"FilterThicknessMaximum","DS"], [0x0018,0x7056,"FilterBeamPathLengthMinimum","FL"], [0x0018,0x7058,"FilterBeamPathLengthMaximum","FL"], [0x0018,0x7060,"ExposureControlMode","CS"], [0x0018,0x7062,"ExposureControlModeDescription","LT"], [0x0018,0x7064,"ExposureStatus","CS"], [0x0018,0x7065,"PhototimerSetting","DS"], [0x0018,0x8150,"ExposureTimeInuS","DS"], [0x0018,0x8151,"XRayTubeCurrentInuA","DS"], [0x0018,0x9004,"ContentQualification","CS"], [0x0018,0x9005,"PulseSequenceName","SH"], [0x0018,0x9006,"MRImagingModifierSequence","SQ"], [0x0018,0x9008,"EchoPulseSequence","CS"], [0x0018,0x9009,"InversionRecovery","CS"], [0x0018,0x9010,"FlowCompensation","CS"], [0x0018,0x9011,"MultipleSpinEcho","CS"], [0x0018,0x9012,"MultiPlanarExcitation","CS"], [0x0018,0x9014,"PhaseContrast","CS"], [0x0018,0x9015,"TimeOfFlightContrast","CS"], [0x0018,0x9016,"Spoiling","CS"], [0x0018,0x9017,"SteadyStatePulseSequence","CS"], [0x0018,0x9018,"EchoPlanarPulseSequence","CS"], [0x0018,0x9019,"TagAngleFirstAxis","FD"], [0x0018,0x9020,"MagnetizationTransfer","CS"], [0x0018,0x9021,"T2Preparation","CS"], [0x0018,0x9022,"BloodSignalNulling","CS"], [0x0018,0x9024,"SaturationRecovery","CS"], [0x0018,0x9025,"SpectrallySelectedSuppression","CS"], [0x0018,0x9026,"SpectrallySelectedExcitation","CS"], [0x0018,0x9027,"SpatialPresaturation","CS"], [0x0018,0x9028,"Tagging","CS"], [0x0018,0x9029,"OversamplingPhase","CS"], [0x0018,0x9030,"TagSpacingFirstDimension","FD"], [0x0018,0x9032,"GeometryOfKSpaceTraversal","CS"], [0x0018,0x9033,"SegmentedKSpaceTraversal","CS"], [0x0018,0x9034,"RectilinearPhaseEncodeReordering","CS"], [0x0018,0x9035,"TagThickness","FD"], [0x0018,0x9036,"PartialFourierDirection","CS"], [0x0018,0x9037,"CardiacSynchronizationTechnique","CS"], [0x0018,0x9041,"ReceiveCoilManufacturerName","LO"], [0x0018,0x9042,"MRReceiveCoilSequence","SQ"], [0x0018,0x9043,"ReceiveCoilType","CS"], [0x0018,0x9044,"QuadratureReceiveCoil","CS"], [0x0018,0x9045,"MultiCoilDefinitionSequence","SQ"], [0x0018,0x9046,"MultiCoilConfiguration","LO"], [0x0018,0x9047,"MultiCoilElementName","SH"], [0x0018,0x9048,"MultiCoilElementUsed","CS"], [0x0018,0x9049,"MRTransmitCoilSequence","SQ"], [0x0018,0x9050,"TransmitCoilManufacturerName","LO"], [0x0018,0x9051,"TransmitCoilType","CS"], [0x0018,0x9052,"SpectralWidth","FD"], [0x0018,0x9053,"ChemicalShiftReference","FD"], [0x0018,0x9054,"VolumeLocalizationTechnique","CS"], [0x0018,0x9058,"MRAcquisitionFrequencyEncodingSteps","US"], [0x0018,0x9059,"Decoupling","CS"], [0x0018,0x9060,"DecoupledNucleus","CS"], [0x0018,0x9061,"DecouplingFrequency","FD"], [0x0018,0x9062,"DecouplingMethod","CS"], [0x0018,0x9063,"DecouplingChemicalShiftReference","FD"], [0x0018,0x9064,"KSpaceFiltering","CS"], [0x0018,0x9065,"TimeDomainFiltering","CS"], [0x0018,0x9066,"NumberOfZeroFills","US"], [0x0018,0x9067,"BaselineCorrection","CS"], [0x0018,0x9069,"ParallelReductionFactorInPlane","FD"], [0x0018,0x9070,"CardiacRRIntervalSpecified","FD"], [0x0018,0x9073,"AcquisitionDuration","FD"], [0x0018,0x9074,"FrameAcquisitionDateTime","DT"], [0x0018,0x9075,"DiffusionDirectionality","CS"], [0x0018,0x9076,"DiffusionGradientDirectionSequence","SQ"], [0x0018,0x9077,"ParallelAcquisition","CS"], [0x0018,0x9078,"ParallelAcquisitionTechnique","CS"], [0x0018,0x9079,"InversionTimes","FD"], [0x0018,0x9080,"MetaboliteMapDescription","ST"], [0x0018,0x9081,"PartialFourier","CS"], [0x0018,0x9082,"EffectiveEchoTime","FD"], [0x0018,0x9083,"MetaboliteMapCodeSequence","SQ"], [0x0018,0x9084,"ChemicalShiftSequence","SQ"], [0x0018,0x9085,"CardiacSignalSource","CS"], [0x0018,0x9087,"DiffusionBValue","FD"], [0x0018,0x9089,"DiffusionGradientOrientation","FD"], [0x0018,0x9090,"VelocityEncodingDirection","FD"], [0x0018,0x9091,"VelocityEncodingMinimumValue","FD"], [0x0018,0x9092,"VelocityEncodingAcquisitionSequence","SQ"], [0x0018,0x9093,"NumberOfKSpaceTrajectories","US"], [0x0018,0x9094,"CoverageOfKSpace","CS"], [0x0018,0x9095,"SpectroscopyAcquisitionPhaseRows","UL"], [0x0018,0x9096,"ParallelReductionFactorInPlaneRetired","FD"], [0x0018,0x9098,"TransmitterFrequency","FD"], [0x0018,0x9100,"ResonantNucleus","CS"], [0x0018,0x9101,"FrequencyCorrection","CS"], [0x0018,0x9103,"MRSpectroscopyFOVGeometrySequence","SQ"], [0x0018,0x9104,"SlabThickness","FD"], [0x0018,0x9105,"SlabOrientation","FD"], [0x0018,0x9106,"MidSlabPosition","FD"], [0x0018,0x9107,"MRSpatialSaturationSequence","SQ"], [0x0018,0x9112,"MRTimingAndRelatedParametersSequence","SQ"], [0x0018,0x9114,"MREchoSequence","SQ"], [0x0018,0x9115,"MRModifierSequence","SQ"], [0x0018,0x9117,"MRDiffusionSequence","SQ"], [0x0018,0x9118,"CardiacSynchronizationSequence","SQ"], [0x0018,0x9119,"MRAveragesSequence","SQ"], [0x0018,0x9125,"MRFOVGeometrySequence","SQ"], [0x0018,0x9126,"VolumeLocalizationSequence","SQ"], [0x0018,0x9127,"SpectroscopyAcquisitionDataColumns","UL"], [0x0018,0x9147,"DiffusionAnisotropyType","CS"], [0x0018,0x9151,"FrameReferenceDateTime","DT"], [0x0018,0x9152,"MRMetaboliteMapSequence","SQ"], [0x0018,0x9155,"ParallelReductionFactorOutOfPlane","FD"], [0x0018,0x9159,"SpectroscopyAcquisitionOutOfPlanePhaseSteps","UL"], [0x0018,0x9166,"BulkMotionStatus","CS"], [0x0018,0x9168,"ParallelReductionFactorSecondInPlane","FD"], [0x0018,0x9169,"CardiacBeatRejectionTechnique","CS"], [0x0018,0x9170,"RespiratoryMotionCompensationTechnique","CS"], [0x0018,0x9171,"RespiratorySignalSource","CS"], [0x0018,0x9172,"BulkMotionCompensationTechnique","CS"], [0x0018,0x9173,"BulkMotionSignalSource","CS"], [0x0018,0x9174,"ApplicableSafetyStandardAgency","CS"], [0x0018,0x9175,"ApplicableSafetyStandardDescription","LO"], [0x0018,0x9176,"OperatingModeSequence","SQ"], [0x0018,0x9177,"OperatingModeType","CS"], [0x0018,0x9178,"OperatingMode","CS"], [0x0018,0x9179,"SpecificAbsorptionRateDefinition","CS"], [0x0018,0x9180,"GradientOutputType","CS"], [0x0018,0x9181,"SpecificAbsorptionRateValue","FD"], [0x0018,0x9182,"GradientOutput","FD"], [0x0018,0x9183,"FlowCompensationDirection","CS"], [0x0018,0x9184,"TaggingDelay","FD"], [0x0018,0x9185,"RespiratoryMotionCompensationTechniqueDescription","ST"], [0x0018,0x9186,"RespiratorySignalSourceID","SH"], [0x0018,0x9195,"ChemicalShiftMinimumIntegrationLimitInHz","FD"], [0x0018,0x9196,"ChemicalShiftMaximumIntegrationLimitInHz","FD"], [0x0018,0x9197,"MRVelocityEncodingSequence","SQ"], [0x0018,0x9198,"FirstOrderPhaseCorrection","CS"], [0x0018,0x9199,"WaterReferencedPhaseCorrection","CS"], [0x0018,0x9200,"MRSpectroscopyAcquisitionType","CS"], [0x0018,0x9214,"RespiratoryCyclePosition","CS"], [0x0018,0x9217,"VelocityEncodingMaximumValue","FD"], [0x0018,0x9218,"TagSpacingSecondDimension","FD"], [0x0018,0x9219,"TagAngleSecondAxis","SS"], [0x0018,0x9220,"FrameAcquisitionDuration","FD"], [0x0018,0x9226,"MRImageFrameTypeSequence","SQ"], [0x0018,0x9227,"MRSpectroscopyFrameTypeSequence","SQ"], [0x0018,0x9231,"MRAcquisitionPhaseEncodingStepsInPlane","US"], [0x0018,0x9232,"MRAcquisitionPhaseEncodingStepsOutOfPlane","US"], [0x0018,0x9234,"SpectroscopyAcquisitionPhaseColumns","UL"], [0x0018,0x9236,"CardiacCyclePosition","CS"], [0x0018,0x9239,"SpecificAbsorptionRateSequence","SQ"], [0x0018,0x9240,"RFEchoTrainLength","US"], [0x0018,0x9241,"GradientEchoTrainLength","US"], [0x0018,0x9250,"ArterialSpinLabelingContrast","CS"], [0x0018,0x9251,"MRArterialSpinLabelingSequence","SQ"], [0x0018,0x9252,"ASLTechniqueDescription","LO"], [0x0018,0x9253,"ASLSlabNumber","US"], [0x0018,0x9254,"ASLSlabThickness","FD "], [0x0018,0x9255,"ASLSlabOrientation","FD "], [0x0018,0x9256,"ASLMidSlabPosition","FD "], [0x0018,0x9257,"ASLContext","CS"], [0x0018,0x9258,"ASLPulseTrainDuration","UL"], [0x0018,0x9259,"ASLCrusherFlag","CS"], [0x0018,0x925A,"ASLCrusherFlow","FD"], [0x0018,0x925B,"ASLCrusherDescription","LO"], [0x0018,0x925C,"ASLBolusCutoffFlag","CS"], [0x0018,0x925D,"ASLBolusCutoffTimingSequence","SQ"], [0x0018,0x925E,"ASLBolusCutoffTechnique","LO"], [0x0018,0x925F,"ASLBolusCutoffDelayTime","UL"], [0x0018,0x9260,"ASLSlabSequence","SQ"], [0x0018,0x9295,"ChemicalShiftMinimumIntegrationLimitInppm","FD"], [0x0018,0x9296,"ChemicalShiftMaximumIntegrationLimitInppm","FD"], [0x0018,0x9301,"CTAcquisitionTypeSequence","SQ"], [0x0018,0x9302,"AcquisitionType","CS"], [0x0018,0x9303,"TubeAngle","FD"], [0x0018,0x9304,"CTAcquisitionDetailsSequence","SQ"], [0x0018,0x9305,"RevolutionTime","FD"], [0x0018,0x9306,"SingleCollimationWidth","FD"], [0x0018,0x9307,"TotalCollimationWidth","FD"], [0x0018,0x9308,"CTTableDynamicsSequence","SQ"], [0x0018,0x9309,"TableSpeed","FD"], [0x0018,0x9310,"TableFeedPerRotation","FD"], [0x0018,0x9311,"SpiralPitchFactor","FD"], [0x0018,0x9312,"CTGeometrySequence","SQ"], [0x0018,0x9313,"DataCollectionCenterPatient","FD"], [0x0018,0x9314,"CTReconstructionSequence","SQ"], [0x0018,0x9315,"ReconstructionAlgorithm","CS"], [0x0018,0x9316,"ConvolutionKernelGroup","CS"], [0x0018,0x9317,"ReconstructionFieldOfView","FD"], [0x0018,0x9318,"ReconstructionTargetCenterPatient","FD"], [0x0018,0x9319,"ReconstructionAngle","FD"], [0x0018,0x9320,"ImageFilter","SH"], [0x0018,0x9321,"CTExposureSequence","SQ"], [0x0018,0x9322,"ReconstructionPixelSpacing","FD"], [0x0018,0x9323,"ExposureModulationType","CS"], [0x0018,0x9324,"EstimatedDoseSaving","FD"], [0x0018,0x9325,"CTXRayDetailsSequence","SQ"], [0x0018,0x9326,"CTPositionSequence","SQ"], [0x0018,0x9327,"TablePosition","FD"], [0x0018,0x9328,"ExposureTimeInms","FD"], [0x0018,0x9329,"CTImageFrameTypeSequence","SQ"], [0x0018,0x9330,"XRayTubeCurrentInmA","FD"], [0x0018,0x9332,"ExposureInmAs","FD"], [0x0018,0x9333,"ConstantVolumeFlag","CS"], [0x0018,0x9334,"FluoroscopyFlag","CS"], [0x0018,0x9335,"DistanceSourceToDataCollectionCenter","FD"], [0x0018,0x9337,"ContrastBolusAgentNumber","US"], [0x0018,0x9338,"ContrastBolusIngredientCodeSequence","SQ"], [0x0018,0x9340,"ContrastAdministrationProfileSequence","SQ"], [0x0018,0x9341,"ContrastBolusUsageSequence","SQ"], [0x0018,0x9342,"ContrastBolusAgentAdministered","CS"], [0x0018,0x9343,"ContrastBolusAgentDetected","CS"], [0x0018,0x9344,"ContrastBolusAgentPhase","CS"], [0x0018,0x9345,"CTDIvol","FD"], [0x0018,0x9346,"CTDIPhantomTypeCodeSequence","SQ"], [0x0018,0x9351,"CalciumScoringMassFactorPatient","FL"], [0x0018,0x9352,"CalciumScoringMassFactorDevice","FL"], [0x0018,0x9353,"EnergyWeightingFactor","FL"], [0x0018,0x9360,"CTAdditionalXRaySourceSequence","SQ"], [0x0018,0x9401,"ProjectionPixelCalibrationSequence","SQ"], [0x0018,0x9402,"DistanceSourceToIsocenter","FL"], [0x0018,0x9403,"DistanceObjectToTableTop","FL"], [0x0018,0x9404,"ObjectPixelSpacingInCenterOfBeam","FL"], [0x0018,0x9405,"PositionerPositionSequence","SQ"], [0x0018,0x9406,"TablePositionSequence","SQ"], [0x0018,0x9407,"CollimatorShapeSequence","SQ"], [0x0018,0x9410,"PlanesInAcquisition","CS"], [0x0018,0x9412,"XAXRFFrameCharacteristicsSequence","SQ"], [0x0018,0x9417,"FrameAcquisitionSequence","SQ"], [0x0018,0x9420,"XRayReceptorType","CS"], [0x0018,0x9423,"AcquisitionProtocolName","LO"], [0x0018,0x9424,"AcquisitionProtocolDescription","LT"], [0x0018,0x9425,"ContrastBolusIngredientOpaque","CS"], [0x0018,0x9426,"DistanceReceptorPlaneToDetectorHousing","FL"], [0x0018,0x9427,"IntensifierActiveShape","CS"], [0x0018,0x9428,"IntensifierActiveDimensions","FL"], [0x0018,0x9429,"PhysicalDetectorSize","FL"], [0x0018,0x9430,"PositionOfIsocenterProjection","FL"], [0x0018,0x9432,"FieldOfViewSequence","SQ"], [0x0018,0x9433,"FieldOfViewDescription","LO"], [0x0018,0x9434,"ExposureControlSensingRegionsSequence","SQ"], [0x0018,0x9435,"ExposureControlSensingRegionShape","CS"], [0x0018,0x9436,"ExposureControlSensingRegionLeftVerticalEdge","SS"], [0x0018,0x9437,"ExposureControlSensingRegionRightVerticalEdge","SS"], [0x0018,0x9438,"ExposureControlSensingRegionUpperHorizontalEdge","SS"], [0x0018,0x9439,"ExposureControlSensingRegionLowerHorizontalEdge","SS"], [0x0018,0x9440,"CenterOfCircularExposureControlSensingRegion","SS"], [0x0018,0x9441,"RadiusOfCircularExposureControlSensingRegion","US"], [0x0018,0x9442,"VerticesOfThePolygonalExposureControlSensingRegion","SS"], [0x0018,0x9447,"ColumnAngulationPatient","FL"], [0x0018,0x9449,"BeamAngle","FL"], [0x0018,0x9451,"FrameDetectorParametersSequence","SQ"], [0x0018,0x9452,"CalculatedAnatomyThickness","FL"], [0x0018,0x9455,"CalibrationSequence","SQ"], [0x0018,0x9456,"ObjectThicknessSequence","SQ"], [0x0018,0x9457,"PlaneIdentification","CS"], [0x0018,0x9461,"FieldOfViewDimensionsInFloat","FL"], [0x0018,0x9462,"IsocenterReferenceSystemSequence","SQ"], [0x0018,0x9463,"PositionerIsocenterPrimaryAngle","FL"], [0x0018,0x9464,"PositionerIsocenterSecondaryAngle","FL"], [0x0018,0x9465,"PositionerIsocenterDetectorRotationAngle","FL"], [0x0018,0x9466,"TableXPositionToIsocenter","FL"], [0x0018,0x9467,"TableYPositionToIsocenter","FL"], [0x0018,0x9468,"TableZPositionToIsocenter","FL"], [0x0018,0x9469,"TableHorizontalRotationAngle","FL"], [0x0018,0x9470,"TableHeadTiltAngle","FL"], [0x0018,0x9471,"TableCradleTiltAngle","FL"], [0x0018,0x9472,"FrameDisplayShutterSequence","SQ"], [0x0018,0x9473,"AcquiredImageAreaDoseProduct","FL"], [0x0018,0x9474,"CArmPositionerTabletopRelationship","CS"], [0x0018,0x9476,"XRayGeometrySequence","SQ"], [0x0018,0x9477,"IrradiationEventIdentificationSequence","SQ"], [0x0018,0x9504,"XRay3DFrameTypeSequence","SQ"], [0x0018,0x9506,"ContributingSourcesSequence","SQ"], [0x0018,0x9507,"XRay3DAcquisitionSequence","SQ"], [0x0018,0x9508,"PrimaryPositionerScanArc","FL"], [0x0018,0x9509,"SecondaryPositionerScanArc","FL"], [0x0018,0x9510,"PrimaryPositionerScanStartAngle","FL "], [0x0018,0x9511,"SecondaryPositionerScanStartAngle","FL"], [0x0018,0x9514,"PrimaryPositionerIncrement","FL"], [0x0018,0x9515,"SecondaryPositionerIncrement","FL"], [0x0018,0x9516,"StartAcquisitionDateTime","DT"], [0x0018,0x9517,"EndAcquisitionDateTime","DT"], [0x0018,0x9524,"ApplicationName","LO"], [0x0018,0x9525,"ApplicationVersion","LO"], [0x0018,0x9526,"ApplicationManufacturer","LO"], [0x0018,0x9527,"AlgorithmType","CS"], [0x0018,0x9528,"AlgorithmDescription","LO"], [0x0018,0x9530,"XRay3DReconstructionSequence","SQ"], [0x0018,0x9531,"ReconstructionDescription","LO"], [0x0018,0x9538,"PerProjectionAcquisitionSequence","SQ"], [0x0018,0x9601,"DiffusionBMatrixSequence","SQ"], [0x0018,0x9602,"DiffusionBValueXX","FD"], [0x0018,0x9603,"DiffusionBValueXY","FD"], [0x0018,0x9604,"DiffusionBValueXZ","FD"], [0x0018,0x9605,"DiffusionBValueYY","FD"], [0x0018,0x9606,"DiffusionBValueYZ","FD"], [0x0018,0x9607,"DiffusionBValueZZ","FD"], [0x0018,0x9701,"DecayCorrectionDateTime","DT"], [0x0018,0x9715,"StartDensityThreshold","FD"], [0x0018,0x9716,"StartRelativeDensityDifferenceThreshold","FD"], [0x0018,0x9717,"StartCardiacTriggerCountThreshold","FD"], [0x0018,0x9718,"StartRespiratoryTriggerCountThreshold","FD"], [0x0018,0x9719,"TerminationCountsThreshold","FD"], [0x0018,0x9720,"TerminationDensityThreshold","FD"], [0x0018,0x9721,"TerminationRelativeDensityThreshold","FD"], [0x0018,0x9722,"TerminationTimeThreshold","FD"], [0x0018,0x9723,"TerminationCardiacTriggerCountThreshold","FD"], [0x0018,0x9724,"TerminationRespiratoryTriggerCountThreshold","FD"], [0x0018,0x9725,"DetectorGeometry","CS"], [0x0018,0x9726,"TransverseDetectorSeparation","FD"], [0x0018,0x9727,"AxialDetectorDimension","FD"], [0x0018,0x9729,"RadiopharmaceuticalAgentNumber","US"], [0x0018,0x9732,"PETFrameAcquisitionSequence","SQ"], [0x0018,0x9733,"PETDetectorMotionDetailsSequence","SQ"], [0x0018,0x9734,"PETTableDynamicsSequence","SQ"], [0x0018,0x9735,"PETPositionSequence","SQ"], [0x0018,0x9736,"PETFrameCorrectionFactorsSequence","SQ"], [0x0018,0x9737,"RadiopharmaceuticalUsageSequence","SQ"], [0x0018,0x9738,"AttenuationCorrectionSource","CS"], [0x0018,0x9739,"NumberOfIterations","US"], [0x0018,0x9740,"NumberOfSubsets","US"], [0x0018,0x9749,"PETReconstructionSequence","SQ"], [0x0018,0x9751,"PETFrameTypeSequence","SQ"], [0x0018,0x9755,"TimeOfFlightInformationUsed","CS"], [0x0018,0x9756,"ReconstructionType","CS"], [0x0018,0x9758,"DecayCorrected","CS"], [0x0018,0x9759,"AttenuationCorrected","CS"], [0x0018,0x9760,"ScatterCorrected","CS"], [0x0018,0x9761,"DeadTimeCorrected","CS"], [0x0018,0x9762,"GantryMotionCorrected","CS"], [0x0018,0x9763,"PatientMotionCorrected","CS"], [0x0018,0x9764,"CountLossNormalizationCorrected","CS"], [0x0018,0x9765,"RandomsCorrected","CS"], [0x0018,0x9766,"NonUniformRadialSamplingCorrected","CS"], [0x0018,0x9767,"SensitivityCalibrated","CS"], [0x0018,0x9768,"DetectorNormalizationCorrection","CS"], [0x0018,0x9769,"IterativeReconstructionMethod","CS"], [0x0018,0x9770,"AttenuationCorrectionTemporalRelationship","CS"], [0x0018,0x9771,"PatientPhysiologicalStateSequence","SQ"], [0x0018,0x9772,"PatientPhysiologicalStateCodeSequence","SQ"], [0x0018,0x9801,"DepthsOfFocus","FD"], [0x0018,0x9803,"ExcludedIntervalsSequence","SQ"], [0x0018,0x9804,"ExclusionStartDatetime","DT"], [0x0018,0x9805,"ExclusionDuration","FD"], [0x0018,0x9806,"USImageDescriptionSequence","SQ"], [0x0018,0x9807,"ImageDataTypeSequence","SQ"], [0x0018,0x9808,"DataType","CS"], [0x0018,0x9809,"TransducerScanPatternCodeSequence","SQ"], [0x0018,0x980B,"AliasedDataType","CS"], [0x0018,0x980C,"PositionMeasuringDeviceUsed","CS"], [0x0018,0x980D,"TransducerGeometryCodeSequence","SQ"], [0x0018,0x980E,"TransducerBeamSteeringCodeSequence","SQ"], [0x0018,0x980F,"TransducerApplicationCodeSequence","SQ"], [0x0018,0xA001,"ContributingEquipmentSequence","SQ"], [0x0018,0xA002,"ContributionDateTime","DT"], [0x0018,0xA003,"ContributionDescription","ST"], [0x0020,0x000D,"StudyInstanceUID","UI"], [0x0020,0x000E,"SeriesInstanceUID","UI"], [0x0020,0x0010,"StudyID","SH"], [0x0020,0x0011,"SeriesNumber","IS"], [0x0020,0x0012,"AcquisitionNumber","IS"], [0x0020,0x0013,"InstanceNumber","IS"], [0x0020,0x0014,"IsotopeNumber","IS"], [0x0020,0x0015,"PhaseNumber","IS"], [0x0020,0x0016,"IntervalNumber","IS"], [0x0020,0x0017,"TimeSlotNumber","IS"], [0x0020,0x0018,"AngleNumber","IS"], [0x0020,0x0019,"ItemNumber","IS"], [0x0020,0x0020,"PatientOrientation","CS"], [0x0020,0x0022,"OverlayNumber","IS"], [0x0020,0x0024,"CurveNumber","IS"], [0x0020,0x0026,"LUTNumber","IS"], [0x0020,0x0030,"ImagePosition","DS"], [0x0020,0x0032,"ImagePositionPatient","DS"], [0x0020,0x0035,"ImageOrientation","DS"], [0x0020,0x0037,"ImageOrientationPatient","DS"], [0x0020,0x0050,"Location","DS"], [0x0020,0x0052,"FrameOfReferenceUID","UI"], [0x0020,0x0060,"Laterality","CS"], [0x0020,0x0062,"ImageLaterality","CS"], [0x0020,0x0070,"ImageGeometryType","LO"], [0x0020,0x0080,"MaskingImage","CS"], [0x0020,0x00AA,"ReportNumber","IS"], [0x0020,0x0100,"TemporalPositionIdentifier","IS"], [0x0020,0x0105,"NumberOfTemporalPositions","IS"], [0x0020,0x0110,"TemporalResolution","DS"], [0x0020,0x0200,"SynchronizationFrameOfReferenceUID","UI"], [0x0020,0x0242,"SOPInstanceUIDOfConcatenationSource","UI"], [0x0020,0x1000,"SeriesInStudy","IS"], [0x0020,0x1001,"AcquisitionsInSeries","IS"], [0x0020,0x1002,"ImagesInAcquisition","IS"], [0x0020,0x1003,"ImagesInSeries","IS"], [0x0020,0x1004,"AcquisitionsInStudy","IS"], [0x0020,0x1005,"ImagesInStudy","IS"], [0x0020,0x1020,"Reference","LO"], [0x0020,0x1040,"PositionReferenceIndicator","LO"], [0x0020,0x1041,"SliceLocation","DS"], [0x0020,0x1070,"OtherStudyNumbers","IS"], [0x0020,0x1200,"NumberOfPatientRelatedStudies","IS"], [0x0020,0x1202,"NumberOfPatientRelatedSeries","IS"], [0x0020,0x1204,"NumberOfPatientRelatedInstances","IS"], [0x0020,0x1206,"NumberOfStudyRelatedSeries","IS"], [0x0020,0x1208,"NumberOfStudyRelatedInstances","IS"], [0x0020,0x1209,"NumberOfSeriesRelatedInstances","IS"], [0x0020,0x3401,"ModifyingDeviceID","CS"], [0x0020,0x3402,"ModifiedImageID","CS"], [0x0020,0x3403,"ModifiedImageDate","DA"], [0x0020,0x3404,"ModifyingDeviceManufacturer","LO"], [0x0020,0x3405,"ModifiedImageTime","TM"], [0x0020,0x3406,"ModifiedImageDescription","LO"], [0x0020,0x4000,"ImageComments","LT"], [0x0020,0x5000,"OriginalImageIdentification","AT"], [0x0020,0x5002,"OriginalImageIdentificationNomenclature","LO"], [0x0020,0x9056,"StackID","SH"], [0x0020,0x9057,"InStackPositionNumber","UL"], [0x0020,0x9071,"FrameAnatomySequence","SQ"], [0x0020,0x9072,"FrameLaterality","CS"], [0x0020,0x9111,"FrameContentSequence","SQ"], [0x0020,0x9113,"PlanePositionSequence","SQ"], [0x0020,0x9116,"PlaneOrientationSequence","SQ"], [0x0020,0x9128,"TemporalPositionIndex","UL"], [0x0020,0x9153,"NominalCardiacTriggerDelayTime","FD"], [0x0020,0x9154,"NominalCardiacTriggerTimePriorToRPeak","FL"], [0x0020,0x9155,"ActualCardiacTriggerTimePriorToRPeak","FL"], [0x0020,0x9156,"FrameAcquisitionNumber","US"], [0x0020,0x9157,"DimensionIndexValues","UL"], [0x0020,0x9158,"FrameComments","LT"], [0x0020,0x9161,"ConcatenationUID","UI"], [0x0020,0x9162,"InConcatenationNumber","US"], [0x0020,0x9163,"InConcatenationTotalNumber","US"], [0x0020,0x9164,"DimensionOrganizationUID","UI"], [0x0020,0x9165,"DimensionIndexPointer","AT"], [0x0020,0x9167,"FunctionalGroupPointer","AT"], [0x0020,0x9213,"DimensionIndexPrivateCreator","LO"], [0x0020,0x9221,"DimensionOrganizationSequence","SQ"], [0x0020,0x9222,"DimensionIndexSequence","SQ"], [0x0020,0x9228,"ConcatenationFrameOffsetNumber","UL"], [0x0020,0x9238,"FunctionalGroupPrivateCreator","LO"], [0x0020,0x9241,"NominalPercentageOfCardiacPhase","FL"], [0x0020,0x9245,"NominalPercentageOfRespiratoryPhase","FL"], [0x0020,0x9246,"StartingRespiratoryAmplitude","FL"], [0x0020,0x9247,"StartingRespiratoryPhase","CS"], [0x0020,0x9248,"EndingRespiratoryAmplitude","FL"], [0x0020,0x9249,"EndingRespiratoryPhase","CS"], [0x0020,0x9250,"RespiratoryTriggerType","CS"], [0x0020,0x9251,"RRIntervalTimeNominal","FD"], [0x0020,0x9252,"ActualCardiacTriggerDelayTime","FD"], [0x0020,0x9253,"RespiratorySynchronizationSequence","SQ"], [0x0020,0x9254,"RespiratoryIntervalTime","FD"], [0x0020,0x9255,"NominalRespiratoryTriggerDelayTime","FD"], [0x0020,0x9256,"RespiratoryTriggerDelayThreshold","FD"], [0x0020,0x9257,"ActualRespiratoryTriggerDelayTime","FD"], [0x0020,0x9301,"ImagePositionVolume","FD"], [0x0020,0x9302,"ImageOrientationVolume","FD"], [0x0020,0x9307,"UltrasoundAcquisitionGeometry","CS"], [0x0020,0x9308,"ApexPosition","FD"], [0x0020,0x9309,"VolumeToTransducerMappingMatrix","FD"], [0x0020,0x930A,"VolumeToTableMappingMatrix","FD"], [0x0020,0x930C,"PatientFrameOfReferenceSource","CS"], [0x0020,0x930D,"TemporalPositionTimeOffset","FD"], [0x0020,0x930E,"PlanePositionVolumeSequence","SQ"], [0x0020,0x930F,"PlaneOrientationVolumeSequence","SQ"], [0x0020,0x9310,"TemporalPositionSequence","SQ"], [0x0020,0x9311,"DimensionOrganizationType","CS"], [0x0020,0x9312,"VolumeFrameOfReferenceUID","UI"], [0x0020,0x9313,"TableFrameOfReferenceUID","UI"], [0x0020,0x9421,"DimensionDescriptionLabel","LO"], [0x0020,0x9450,"PatientOrientationInFrameSequence","SQ"], [0x0020,0x9453,"FrameLabel","LO"], [0x0020,0x9518,"AcquisitionIndex","US"], [0x0020,0x9529,"ContributingSOPInstancesReferenceSequence","SQ"], [0x0020,0x9536,"ReconstructionIndex","US"], [0x0022,0x0001,"LightPathFilterPassThroughWavelength","US"], [0x0022,0x0002,"LightPathFilterPassBand","US"], [0x0022,0x0003,"ImagePathFilterPassThroughWavelength","US"], [0x0022,0x0004,"ImagePathFilterPassBand","US"], [0x0022,0x0005,"PatientEyeMovementCommanded","CS"], [0x0022,0x0006,"PatientEyeMovementCommandCodeSequence","SQ"], [0x0022,0x0007,"SphericalLensPower","FL"], [0x0022,0x0008,"CylinderLensPower","FL"], [0x0022,0x0009,"CylinderAxis","FL"], [0x0022,0x000A,"EmmetropicMagnification","FL"], [0x0022,0x000B,"IntraOcularPressure","FL"], [0x0022,0x000C,"HorizontalFieldOfView","FL"], [0x0022,0x000D,"PupilDilated","CS"], [0x0022,0x000E,"DegreeOfDilation","FL"], [0x0022,0x0010,"StereoBaselineAngle","FL"], [0x0022,0x0011,"StereoBaselineDisplacement","FL"], [0x0022,0x0012,"StereoHorizontalPixelOffset","FL"], [0x0022,0x0013,"StereoVerticalPixelOffset","FL"], [0x0022,0x0014,"StereoRotation","FL"], [0x0022,0x0015,"AcquisitionDeviceTypeCodeSequence","SQ"], [0x0022,0x0016,"IlluminationTypeCodeSequence","SQ"], [0x0022,0x0017,"LightPathFilterTypeStackCodeSequence","SQ"], [0x0022,0x0018,"ImagePathFilterTypeStackCodeSequence","SQ"], [0x0022,0x0019,"LensesCodeSequence","SQ"], [0x0022,0x001A,"ChannelDescriptionCodeSequence","SQ"], [0x0022,0x001B,"RefractiveStateSequence","SQ"], [0x0022,0x001C,"MydriaticAgentCodeSequence","SQ"], [0x0022,0x001D,"RelativeImagePositionCodeSequence","SQ"], [0x0022,0x001E,"CameraAngleOfView","FL"], [0x0022,0x0020,"StereoPairsSequence","SQ"], [0x0022,0x0021,"LeftImageSequence","SQ"], [0x0022,0x0022,"RightImageSequence","SQ"], [0x0022,0x0030,"AxialLengthOfTheEye","FL"], [0x0022,0x0031,"OphthalmicFrameLocationSequence","SQ"], [0x0022,0x0032,"ReferenceCoordinates","FL"], [0x0022,0x0035,"DepthSpatialResolution","FL"], [0x0022,0x0036,"MaximumDepthDistortion","FL"], [0x0022,0x0037,"AlongScanSpatialResolution","FL"], [0x0022,0x0038,"MaximumAlongScanDistortion","FL"], [0x0022,0x0039,"OphthalmicImageOrientation","CS"], [0x0022,0x0041,"DepthOfTransverseImage","FL"], [0x0022,0x0042,"MydriaticAgentConcentrationUnitsSequence","SQ"], [0x0022,0x0048,"AcrossScanSpatialResolution","FL"], [0x0022,0x0049,"MaximumAcrossScanDistortion","FL"], [0x0022,0x004E,"MydriaticAgentConcentration","DS"], [0x0022,0x0055,"IlluminationWaveLength","FL"], [0x0022,0x0056,"IlluminationPower","FL"], [0x0022,0x0057,"IlluminationBandwidth","FL"], [0x0022,0x0058,"MydriaticAgentSequence","SQ"], [0x0022,0x1007,"OphthalmicAxialMeasurementsRightEyeSequence","SQ"], [0x0022,0x1008,"OphthalmicAxialMeasurementsLeftEyeSequence","SQ"], [0x0022,0x1010,"OphthalmicAxialLengthMeasurementsType","CS"], [0x0022,0x1019,"OphthalmicAxialLength","FL"], [0x0022,0x1024,"LensStatusCodeSequence","SQ"], [0x0022,0x1025,"VitreousStatusCodeSequence","SQ"], [0x0022,0x1028,"IOLFormulaCodeSequence","SQ"], [0x0022,0x1029,"IOLFormulaDetail","LO"], [0x0022,0x1033,"KeratometerIndex","FL"], [0x0022,0x1035,"SourceOfOphthalmicAxialLengthCodeSequence","SQ"], [0x0022,0x1037,"TargetRefraction","FL"], [0x0022,0x1039,"RefractiveProcedureOccurred","CS"], [0x0022,0x1040,"RefractiveSurgeryTypeCodeSequence","SQ"], [0x0022,0x1044,"OphthalmicUltrasoundAxialMeasurementsTypeCodeSequence","SQ"], [0x0022,0x1050,"OphthalmicAxialLengthMeasurementsSequence","SQ"], [0x0022,0x1053,"IOLPower","FL"], [0x0022,0x1054,"PredictedRefractiveError","FL"], [0x0022,0x1059,"OphthalmicAxialLengthVelocity","FL"], [0x0022,0x1065,"LensStatusDescription","LO"], [0x0022,0x1066,"VitreousStatusDescription","LO"], [0x0022,0x1090,"IOLPowerSequence","SQ"], [0x0022,0x1092,"LensConstantSequence","SQ"], [0x0022,0x1093,"IOLManufacturer","LO"], [0x0022,0x1094,"LensConstantDescription","LO"], [0x0022,0x1096,"KeratometryMeasurementTypeCodeSequence","SQ"], [0x0022,0x1100,"ReferencedOphthalmicAxialMeasurementsSequence","SQ"], [0x0022,0x1101,"OphthalmicAxialLengthMeasurementsSegmentNameCodeSequence","SQ"], [0x0022,0x1103,"RefractiveErrorBeforeRefractiveSurgeryCodeSequence","SQ"], [0x0022,0x1121,"IOLPowerForExactEmmetropia","FL"], [0x0022,0x1122,"IOLPowerForExactTargetRefraction","FL"], [0x0022,0x1125,"AnteriorChamberDepthDefinitionCodeSequence","SQ"], [0x0022,0x1130,"LensThickness","FL"], [0x0022,0x1131,"AnteriorChamberDepth","FL"], [0x0022,0x1132,"SourceOfLensThicknessDataCodeSequence","SQ"], [0x0022,0x1133,"SourceOfAnteriorChamberDepthDataCodeSequence","SQ"], [0x0022,0x1135,"SourceOfRefractiveErrorDataCodeSequence","SQ"], [0x0022,0x1140,"OphthalmicAxialLengthMeasurementModified","CS"], [0x0022,0x1150,"OphthalmicAxialLengthDataSourceCodeSequence","SQ"], [0x0022,0x1153,"OphthalmicAxialLengthAcquisitionMethodCodeSequence","SQ"], [0x0022,0x1155,"SignalToNoiseRatio","FL"], [0x0022,0x1159,"OphthalmicAxialLengthDataSourceDescription","LO"], [0x0022,0x1210,"OphthalmicAxialLengthMeasurementsTotalLengthSequence","SQ"], [0x0022,0x1211,"OphthalmicAxialLengthMeasurementsSegmentalLengthSequence","SQ"], [0x0022,0x1212,"OphthalmicAxialLengthMeasurementsLengthSummationSequence","SQ"], [0x0022,0x1220,"UltrasoundOphthalmicAxialLengthMeasurementsSequence","SQ"], [0x0022,0x1225,"OpticalOphthalmicAxialLengthMeasurementsSequence","SQ"], [0x0022,0x1230,"UltrasoundSelectedOphthalmicAxialLengthSequence","SQ"], [0x0022,0x1250,"OphthalmicAxialLengthSelectionMethodCodeSequence","SQ"], [0x0022,0x1255,"OpticalSelectedOphthalmicAxialLengthSequence","SQ"], [0x0022,0x1257,"SelectedSegmentalOphthalmicAxialLengthSequence","SQ"], [0x0022,0x1260,"SelectedTotalOphthalmicAxialLengthSequence","SQ"], [0x0022,0x1262,"OphthalmicAxialLengthQualityMetricSequence","SQ"], [0x0022,0x1273,"OphthalmicAxialLengthQualityMetricTypeDescription","LO"], [0x0022,0x1300,"IntraocularLensCalculationsRightEyeSequence","SQ"], [0x0022,0x1310,"IntraocularLensCalculationsLeftEyeSequence","SQ"], [0x0022,0x1330,"ReferencedOphthalmicAxialLengthMeasurementQCImageSequence","SQ"], [0x0024,0x0010,"VisualFieldHorizontalExtent","FL"], [0x0024,0x0011,"VisualFieldVerticalExtent","FL"], [0x0024,0x0012,"VisualFieldShape","CS"], [0x0024,0x0016,"ScreeningTestModeCodeSequence","SQ"], [0x0024,0x0018,"MaximumStimulusLuminance","FL"], [0x0024,0x0020,"BackgroundLuminance","FL"], [0x0024,0x0021,"StimulusColorCodeSequence","SQ"], [0x0024,0x0024,"BackgroundIlluminationColorCodeSequence","SQ"], [0x0024,0x0025,"StimulusArea","FL"], [0x0024,0x0028,"StimulusPresentationTime","FL"], [0x0024,0x0032,"FixationSequence","SQ"], [0x0024,0x0033,"FixationMonitoringCodeSequence","SQ"], [0x0024,0x0034,"VisualFieldCatchTrialSequence","SQ"], [0x0024,0x0035,"FixationCheckedQuantity","US"], [0x0024,0x0036,"PatientNotProperlyFixatedQuantity","US"], [0x0024,0x0037,"PresentedVisualStimuliDataFlag","CS"], [0x0024,0x0038,"NumberOfVisualStimuli","US"], [0x0024,0x0039,"ExcessiveFixationLossesDataFlag","CS"], [0x0024,0x0040,"ExcessiveFixationLosses","CS"], [0x0024,0x0042,"StimuliRetestingQuantity","US"], [0x0024,0x0044,"CommentsOnPatientPerformanceOfVisualField","LT"], [0x0024,0x0045,"FalseNegativesEstimateFlag","CS"], [0x0024,0x0046,"FalseNegativesEstimate","FL"], [0x0024,0x0048,"NegativeCatchTrialsQuantity","US"], [0x0024,0x0050,"FalseNegativesQuantity","US"], [0x0024,0x0051,"ExcessiveFalseNegativesDataFlag","CS"], [0x0024,0x0052,"ExcessiveFalseNegatives","CS"], [0x0024,0x0053,"FalsePositivesEstimateFlag","CS"], [0x0024,0x0054,"FalsePositivesEstimate","FL"], [0x0024,0x0055,"CatchTrialsDataFlag","CS"], [0x0024,0x0056,"PositiveCatchTrialsQuantity","US"], [0x0024,0x0057,"TestPointNormalsDataFlag","CS"], [0x0024,0x0058,"TestPointNormalsSequence","SQ"], [0x0024,0x0059,"GlobalDeviationProbabilityNormalsFlag","CS"], [0x0024,0x0060,"FalsePositivesQuantity","US"], [0x0024,0x0061,"ExcessiveFalsePositivesDataFlag","CS"], [0x0024,0x0062,"ExcessiveFalsePositives","CS"], [0x0024,0x0063,"VisualFieldTestNormalsFlag","CS"], [0x0024,0x0064,"ResultsNormalsSequence","SQ"], [0x0024,0x0065,"AgeCorrectedSensitivityDeviationAlgorithmSequence","SQ"], [0x0024,0x0066,"GlobalDeviationFromNormal","FL"], [0x0024,0x0067,"GeneralizedDefectSensitivityDeviationAlgorithmSequence","SQ"], [0x0024,0x0068,"LocalizedDeviationfromNormal","FL"], [0x0024,0x0069,"PatientReliabilityIndicator","LO"], [0x0024,0x0070,"VisualFieldMeanSensitivity","FL"], [0x0024,0x0071,"GlobalDeviationProbability","FL"], [0x0024,0x0072,"LocalDeviationProbabilityNormalsFlag","CS"], [0x0024,0x0073,"LocalizedDeviationProbability","FL"], [0x0024,0x0074,"ShortTermFluctuationCalculated","CS"], [0x0024,0x0075,"ShortTermFluctuation","FL"], [0x0024,0x0076,"ShortTermFluctuationProbabilityCalculated","CS"], [0x0024,0x0077,"ShortTermFluctuationProbability","FL"], [0x0024,0x0078,"CorrectedLocalizedDeviationFromNormalCalculated","CS"], [0x0024,0x0079,"CorrectedLocalizedDeviationFromNormal","FL"], [0x0024,0x0080,"CorrectedLocalizedDeviationFromNormalProbabilityCalculated","CS"], [0x0024,0x0081,"CorrectedLocalizedDeviationFromNormalProbability","FL"], [0x0024,0x0083,"GlobalDeviationProbabilitySequence","SQ"], [0x0024,0x0085,"LocalizedDeviationProbabilitySequence","SQ"], [0x0024,0x0086,"FovealSensitivityMeasured","CS"], [0x0024,0x0087,"FovealSensitivity","FL"], [0x0024,0x0088,"VisualFieldTestDuration","FL"], [0x0024,0x0089,"VisualFieldTestPointSequence","SQ"], [0x0024,0x0090,"VisualFieldTestPointXCoordinate","FL"], [0x0024,0x0091,"VisualFieldTestPointYCoordinate","FL"], [0x0024,0x0092,"AgeCorrectedSensitivityDeviationValue","FL"], [0x0024,0x0093,"StimulusResults","CS"], [0x0024,0x0094,"SensitivityValue","FL"], [0x0024,0x0095,"RetestStimulusSeen","CS"], [0x0024,0x0096,"RetestSensitivityValue","FL"], [0x0024,0x0097,"VisualFieldTestPointNormalsSequence","SQ"], [0x0024,0x0098,"QuantifiedDefect","FL"], [0x0024,0x0100,"AgeCorrectedSensitivityDeviationProbabilityValue","FL"], [0x0024,0x0102,"GeneralizedDefectCorrectedSensitivityDeviationFlag ","CS"], [0x0024,0x0103,"GeneralizedDefectCorrectedSensitivityDeviationValue ","FL"], [0x0024,0x0104,"GeneralizedDefectCorrectedSensitivityDeviationProbabilityValue","FL"], [0x0024,0x0105,"MinimumSensitivityValue","FL "], [0x0024,0x0106,"BlindSpotLocalized","CS"], [0x0024,0x0107,"BlindSpotXCoordinate","FL"], [0x0024,0x0108,"BlindSpotYCoordinate ","FL"], [0x0024,0x0110,"VisualAcuityMeasurementSequence","SQ"], [0x0024,0x0112,"RefractiveParametersUsedOnPatientSequence","SQ"], [0x0024,0x0113,"MeasurementLaterality","CS"], [0x0024,0x0114,"OphthalmicPatientClinicalInformationLeftEyeSequence","SQ"], [0x0024,0x0115,"OphthalmicPatientClinicalInformationRightEyeSequence","SQ"], [0x0024,0x0117,"FovealPointNormativeDataFlag","CS"], [0x0024,0x0118,"FovealPointProbabilityValue","FL"], [0x0024,0x0120,"ScreeningBaselineMeasured","CS"], [0x0024,0x0122,"ScreeningBaselineMeasuredSequence","SQ"], [0x0024,0x0124,"ScreeningBaselineType","CS"], [0x0024,0x0126,"ScreeningBaselineValue","FL"], [0x0024,0x0202,"AlgorithmSource","LO"], [0x0024,0x0306,"DataSetName","LO"], [0x0024,0x0307,"DataSetVersion","LO"], [0x0024,0x0308,"DataSetSource","LO"], [0x0024,0x0309,"DataSetDescription","LO"], [0x0024,0x0317,"VisualFieldTestReliabilityGlobalIndexSequence","SQ"], [0x0024,0x0320,"VisualFieldGlobalResultsIndexSequence","SQ"], [0x0024,0x0325,"DataObservationSequence","SQ"], [0x0024,0x0338,"IndexNormalsFlag","CS"], [0x0024,0x0341,"IndexProbability","FL"], [0x0024,0x0344,"IndexProbabilitySequence","SQ"], [0x0028,0x0002,"SamplesPerPixel","US"], [0x0028,0x0003,"SamplesPerPixelUsed","US"], [0x0028,0x0004,"PhotometricInterpretation","CS"], [0x0028,0x0005,"ImageDimensions","US"], [0x0028,0x0006,"PlanarConfiguration","US"], [0x0028,0x0008,"NumberOfFrames","IS"], [0x0028,0x0009,"FrameIncrementPointer","AT"], [0x0028,0x000A,"FrameDimensionPointer","AT"], [0x0028,0x0010,"Rows","US"], [0x0028,0x0011,"Columns","US"], [0x0028,0x0012,"Planes","US"], [0x0028,0x0014,"UltrasoundColorDataPresent","US"], [0x0028,0x0030,"PixelSpacing","DS"], [0x0028,0x0031,"ZoomFactor","DS"], [0x0028,0x0032,"ZoomCenter","DS"], [0x0028,0x0034,"PixelAspectRatio","IS"], [0x0028,0x0040,"ImageFormat","CS"], [0x0028,0x0050,"ManipulatedImage","LO"], [0x0028,0x0051,"CorrectedImage","CS"], [0x0028,0x005F,"CompressionRecognitionCode","LO"], [0x0028,0x0060,"CompressionCode","CS"], [0x0028,0x0061,"CompressionOriginator","SH"], [0x0028,0x0062,"CompressionLabel","LO"], [0x0028,0x0063,"CompressionDescription","SH"], [0x0028,0x0065,"CompressionSequence","CS"], [0x0028,0x0066,"CompressionStepPointers","AT"], [0x0028,0x0068,"RepeatInterval","US"], [0x0028,0x0069,"BitsGrouped","US"], [0x0028,0x0070,"PerimeterTable","US"], [0x0028,0x0071,"PerimeterValue","SS"], [0x0028,0x0080,"PredictorRows","US"], [0x0028,0x0081,"PredictorColumns","US"], [0x0028,0x0082,"PredictorConstants","US"], [0x0028,0x0090,"BlockedPixels","CS"], [0x0028,0x0091,"BlockRows","US"], [0x0028,0x0092,"BlockColumns","US"], [0x0028,0x0093,"RowOverlap","US"], [0x0028,0x0094,"ColumnOverlap","US"], [0x0028,0x0100,"BitsAllocated","US"], [0x0028,0x0101,"BitsStored","US"], [0x0028,0x0102,"HighBit","US"], [0x0028,0x0103,"PixelRepresentation","US"], [0x0028,0x0104,"SmallestValidPixelValue","SS"], [0x0028,0x0105,"LargestValidPixelValue","SS"], [0x0028,0x0106,"SmallestImagePixelValue","SS"], [0x0028,0x0107,"LargestImagePixelValue","SS"], [0x0028,0x0108,"SmallestPixelValueInSeries","SS"], [0x0028,0x0109,"LargestPixelValueInSeries","SS"], [0x0028,0x0110,"SmallestImagePixelValueInPlane","SS"], [0x0028,0x0111,"LargestImagePixelValueInPlane","SS"], [0x0028,0x0120,"PixelPaddingValue","SS"], [0x0028,0x0121,"PixelPaddingRangeLimit","SS"], [0x0028,0x0200,"ImageLocation","US"], [0x0028,0x0300,"QualityControlImage","CS"], [0x0028,0x0301,"BurnedInAnnotation","CS"], [0x0028,0x0302,"RecognizableVisualFeatures","CS"], [0x0028,0x0303,"LongitudinalTemporalInformationModified","CS"], [0x0028,0x0400,"TransformLabel","LO"], [0x0028,0x0401,"TransformVersionNumber","LO"], [0x0028,0x0402,"NumberOfTransformSteps","US"], [0x0028,0x0403,"SequenceOfCompressedData","LO"], [0x0028,0x0404,"DetailsOfCoefficients","AT"], [0x0028,0x0700,"DCTLabel","LO"], [0x0028,0x0701,"DataBlockDescription","CS"], [0x0028,0x0702,"DataBlock","AT"], [0x0028,0x0710,"NormalizationFactorFormat","US"], [0x0028,0x0720,"ZonalMapNumberFormat","US"], [0x0028,0x0721,"ZonalMapLocation","AT"], [0x0028,0x0722,"ZonalMapFormat","US"], [0x0028,0x0730,"AdaptiveMapFormat","US"], [0x0028,0x0740,"CodeNumberFormat","US"], [0x0028,0x0A02,"PixelSpacingCalibrationType","CS"], [0x0028,0x0A04,"PixelSpacingCalibrationDescription","LO"], [0x0028,0x1040,"PixelIntensityRelationship","CS"], [0x0028,0x1041,"PixelIntensityRelationshipSign","SS"], [0x0028,0x1050,"WindowCenter","DS"], [0x0028,0x1051,"WindowWidth","DS"], [0x0028,0x1052,"RescaleIntercept","DS"], [0x0028,0x1053,"RescaleSlope","DS"], [0x0028,0x1054,"RescaleType","LO"], [0x0028,0x1055,"WindowCenterWidthExplanation","LO"], [0x0028,0x1056,"VOILUTFunction","CS"], [0x0028,0x1080,"GrayScale","CS"], [0x0028,0x1090,"RecommendedViewingMode","CS"], [0x0028,0x1100,"GrayLookupTableDescriptor","SS"], [0x0028,0x1101,"RedPaletteColorLookupTableDescriptor","SS"], [0x0028,0x1102,"GreenPaletteColorLookupTableDescriptor","SS"], [0x0028,0x1103,"BluePaletteColorLookupTableDescriptor","SS"], [0x0028,0x1104,"AlphaPaletteColorLookupTableDescriptor","US"], [0x0028,0x1111,"LargeRedPaletteColorLookupTableDescriptor","SS"], [0x0028,0x1112,"LargeGreenPaletteColorLookupTableDescriptor","SS"], [0x0028,0x1113,"LargeBluePaletteColorLookupTableDescriptor","SS"], [0x0028,0x1199,"PaletteColorLookupTableUID","UI"], [0x0028,0x1200,"GrayLookupTableData","OW"], [0x0028,0x1201,"RedPaletteColorLookupTableData","OW"], [0x0028,0x1202,"GreenPaletteColorLookupTableData","OW"], [0x0028,0x1203,"BluePaletteColorLookupTableData","OW"], [0x0028,0x1204,"AlphaPaletteColorLookupTableData","OW"], [0x0028,0x1211,"LargeRedPaletteColorLookupTableData","OW"], [0x0028,0x1212,"LargeGreenPaletteColorLookupTableData","OW"], [0x0028,0x1213,"LargeBluePaletteColorLookupTableData","OW"], [0x0028,0x1214,"LargePaletteColorLookupTableUID","UI"], [0x0028,0x1221,"SegmentedRedPaletteColorLookupTableData","OW"], [0x0028,0x1222,"SegmentedGreenPaletteColorLookupTableData","OW"], [0x0028,0x1223,"SegmentedBluePaletteColorLookupTableData","OW"], [0x0028,0x1300,"BreastImplantPresent","CS"], [0x0028,0x1350,"PartialView","CS"], [0x0028,0x1351,"PartialViewDescription","ST"], [0x0028,0x1352,"PartialViewCodeSequence","SQ"], [0x0028,0x135A,"SpatialLocationsPreserved","CS"], [0x0028,0x1401,"DataFrameAssignmentSequence","SQ"], [0x0028,0x1402,"DataPathAssignment","CS"], [0x0028,0x1403,"BitsMappedToColorLookupTable","US"], [0x0028,0x1404,"BlendingLUT1Sequence","SQ"], [0x0028,0x1405,"BlendingLUT1TransferFunction","CS"], [0x0028,0x1406,"BlendingWeightConstant","FD"], [0x0028,0x1407,"BlendingLookupTableDescriptor","US"], [0x0028,0x1408,"BlendingLookupTableData","OW"], [0x0028,0x140B,"EnhancedPaletteColorLookupTableSequence","SQ"], [0x0028,0x140C,"BlendingLUT2Sequence","SQ"], [0x0028,0x140D,"BlendingLUT2TransferFunction","CS"], [0x0028,0x140E,"DataPathID","CS"], [0x0028,0x140F,"RGBLUTTransferFunction","CS"], [0x0028,0x1410,"AlphaLUTTransferFunction","CS"], [0x0028,0x2000,"ICCProfile","OB"], [0x0028,0x2110,"LossyImageCompression","CS"], [0x0028,0x2112,"LossyImageCompressionRatio","DS"], [0x0028,0x2114,"LossyImageCompressionMethod","CS"], [0x0028,0x3000,"ModalityLUTSequence","SQ"], [0x0028,0x3002,"LUTDescriptor","SS"], [0x0028,0x3003,"LUTExplanation","LO"], [0x0028,0x3004,"ModalityLUTType","LO"], [0x0028,0x3006,"LUTData","OW"], [0x0028,0x3010,"VOILUTSequence","SQ"], [0x0028,0x3110,"SoftcopyVOILUTSequence","SQ"], [0x0028,0x4000,"ImagePresentationComments","LT"], [0x0028,0x5000,"BiPlaneAcquisitionSequence","SQ"], [0x0028,0x6010,"RepresentativeFrameNumber","US"], [0x0028,0x6020,"FrameNumbersOfInterest","US"], [0x0028,0x6022,"FrameOfInterestDescription","LO"], [0x0028,0x6023,"FrameOfInterestType","CS"], [0x0028,0x6030,"MaskPointers","US"], [0x0028,0x6040,"RWavePointer","US"], [0x0028,0x6100,"MaskSubtractionSequence","SQ"], [0x0028,0x6101,"MaskOperation","CS"], [0x0028,0x6102,"ApplicableFrameRange","US"], [0x0028,0x6110,"MaskFrameNumbers","US"], [0x0028,0x6112,"ContrastFrameAveraging","US"], [0x0028,0x6114,"MaskSubPixelShift","FL"], [0x0028,0x6120,"TIDOffset","SS"], [0x0028,0x6190,"MaskOperationExplanation","ST"], [0x0028,0x7FE0,"PixelDataProviderURL","UT"], [0x0028,0x9001,"DataPointRows","UL"], [0x0028,0x9002,"DataPointColumns","UL"], [0x0028,0x9003,"SignalDomainColumns","CS"], [0x0028,0x9099,"LargestMonochromePixelValue","US"], [0x0028,0x9108,"DataRepresentation","CS"], [0x0028,0x9110,"PixelMeasuresSequence","SQ"], [0x0028,0x9132,"FrameVOILUTSequence","SQ"], [0x0028,0x9145,"PixelValueTransformationSequence","SQ"], [0x0028,0x9235,"SignalDomainRows","CS"], [0x0028,0x9411,"DisplayFilterPercentage","FL"], [0x0028,0x9415,"FramePixelShiftSequence","SQ"], [0x0028,0x9416,"SubtractionItemID","US"], [0x0028,0x9422,"PixelIntensityRelationshipLUTSequence","SQ"], [0x0028,0x9443,"FramePixelDataPropertiesSequence","SQ"], [0x0028,0x9444,"GeometricalProperties","CS"], [0x0028,0x9445,"GeometricMaximumDistortion","FL"], [0x0028,0x9446,"ImageProcessingApplied","CS"], [0x0028,0x9454,"MaskSelectionMode","CS"], [0x0028,0x9474,"LUTFunction","CS"], [0x0028,0x9478,"MaskVisibilityPercentage","FL"], [0x0028,0x9501,"PixelShiftSequence","SQ"], [0x0028,0x9502,"RegionPixelShiftSequence","SQ"], [0x0028,0x9503,"VerticesOfTheRegion","SS"], [0x0028,0x9505,"MultiFramePresentationSequence","SQ"], [0x0028,0x9506,"PixelShiftFrameRange","US"], [0x0028,0x9507,"LUTFrameRange","US"], [0x0028,0x9520,"ImageToEquipmentMappingMatrix","DS"], [0x0028,0x9537,"EquipmentCoordinateSystemIdentification","CS"], [0x0032,0x000A,"StudyStatusID","CS"], [0x0032,0x000C,"StudyPriorityID","CS"], [0x0032,0x0012,"StudyIDIssuer","LO"], [0x0032,0x0032,"StudyVerifiedDate","DA"], [0x0032,0x0033,"StudyVerifiedTime","TM"], [0x0032,0x0034,"StudyReadDate","DA"], [0x0032,0x0035,"StudyReadTime","TM"], [0x0032,0x1000,"ScheduledStudyStartDate","DA"], [0x0032,0x1001,"ScheduledStudyStartTime","TM"], [0x0032,0x1010,"ScheduledStudyStopDate","DA"], [0x0032,0x1011,"ScheduledStudyStopTime","TM"], [0x0032,0x1020,"ScheduledStudyLocation","LO"], [0x0032,0x1021,"ScheduledStudyLocationAETitle","AE"], [0x0032,0x1030,"ReasonForStudy","LO"], [0x0032,0x1031,"RequestingPhysicianIdentificationSequence","SQ"], [0x0032,0x1032,"RequestingPhysician","PN"], [0x0032,0x1033,"RequestingService","LO"], [0x0032,0x1034,"RequestingServiceCodeSequence","SQ"], [0x0032,0x1040,"StudyArrivalDate","DA"], [0x0032,0x1041,"StudyArrivalTime","TM"], [0x0032,0x1050,"StudyCompletionDate","DA"], [0x0032,0x1051,"StudyCompletionTime","TM"], [0x0032,0x1055,"StudyComponentStatusID","CS"], [0x0032,0x1060,"RequestedProcedureDescription","LO"], [0x0032,0x1064,"RequestedProcedureCodeSequence","SQ"], [0x0032,0x1070,"RequestedContrastAgent","LO"], [0x0032,0x4000,"StudyComments","LT"], [0x0038,0x0004,"ReferencedPatientAliasSequence","SQ"], [0x0038,0x0008,"VisitStatusID","CS"], [0x0038,0x0010,"AdmissionID","LO"], [0x0038,0x0011,"IssuerOfAdmissionID","LO"], [0x0038,0x0014,"IssuerOfAdmissionIDSequence","SQ"], [0x0038,0x0016,"RouteOfAdmissions","LO"], [0x0038,0x001A,"ScheduledAdmissionDate","DA"], [0x0038,0x001B,"ScheduledAdmissionTime","TM"], [0x0038,0x001C,"ScheduledDischargeDate","DA"], [0x0038,0x001D,"ScheduledDischargeTime","TM"], [0x0038,0x001E,"ScheduledPatientInstitutionResidence","LO"], [0x0038,0x0020,"AdmittingDate","DA"], [0x0038,0x0021,"AdmittingTime","TM"], [0x0038,0x0030,"DischargeDate","DA"], [0x0038,0x0032,"DischargeTime","TM"], [0x0038,0x0040,"DischargeDiagnosisDescription","LO"], [0x0038,0x0044,"DischargeDiagnosisCodeSequence","SQ"], [0x0038,0x0050,"SpecialNeeds","LO"], [0x0038,0x0060,"ServiceEpisodeID","LO"], [0x0038,0x0061,"IssuerOfServiceEpisodeID","LO"], [0x0038,0x0062,"ServiceEpisodeDescription","LO"], [0x0038,0x0064,"IssuerOfServiceEpisodeIDSequence","SQ"], [0x0038,0x0100,"PertinentDocumentsSequence","SQ"], [0x0038,0x0300,"CurrentPatientLocation","LO"], [0x0038,0x0400,"PatientInstitutionResidence","LO"], [0x0038,0x0500,"PatientState","LO"], [0x0038,0x0502,"PatientClinicalTrialParticipationSequence","SQ"], [0x0038,0x4000,"VisitComments","LT"], [0x003A,0x0004,"WaveformOriginality","CS"], [0x003A,0x0005,"NumberOfWaveformChannels","US"], [0x003A,0x0010,"NumberOfWaveformSamples","UL"], [0x003A,0x001A,"SamplingFrequency","DS"], [0x003A,0x0020,"MultiplexGroupLabel","SH"], [0x003A,0x0200,"ChannelDefinitionSequence","SQ"], [0x003A,0x0202,"WaveformChannelNumber","IS"], [0x003A,0x0203,"ChannelLabel","SH"], [0x003A,0x0205,"ChannelStatus","CS"], [0x003A,0x0208,"ChannelSourceSequence","SQ"], [0x003A,0x0209,"ChannelSourceModifiersSequence","SQ"], [0x003A,0x020A,"SourceWaveformSequence","SQ"], [0x003A,0x020C,"ChannelDerivationDescription","LO"], [0x003A,0x0210,"ChannelSensitivity","DS"], [0x003A,0x0211,"ChannelSensitivityUnitsSequence","SQ"], [0x003A,0x0212,"ChannelSensitivityCorrectionFactor","DS"], [0x003A,0x0213,"ChannelBaseline","DS"], [0x003A,0x0214,"ChannelTimeSkew","DS"], [0x003A,0x0215,"ChannelSampleSkew","DS"], [0x003A,0x0218,"ChannelOffset","DS"], [0x003A,0x021A,"WaveformBitsStored","US"], [0x003A,0x0220,"FilterLowFrequency","DS"], [0x003A,0x0221,"FilterHighFrequency","DS"], [0x003A,0x0222,"NotchFilterFrequency","DS"], [0x003A,0x0223,"NotchFilterBandwidth","DS"], [0x003A,0x0230,"WaveformDataDisplayScale","FL"], [0x003A,0x0231,"WaveformDisplayBackgroundCIELabValue","US"], [0x003A,0x0240,"WaveformPresentationGroupSequence","SQ"], [0x003A,0x0241,"PresentationGroupNumber","US"], [0x003A,0x0242,"ChannelDisplaySequence","SQ"], [0x003A,0x0244,"ChannelRecommendedDisplayCIELabValue","US"], [0x003A,0x0245,"ChannelPosition","FL"], [0x003A,0x0246,"DisplayShadingFlag","CS"], [0x003A,0x0247,"FractionalChannelDisplayScale","FL"], [0x003A,0x0248,"AbsoluteChannelDisplayScale","FL"], [0x003A,0x0300,"MultiplexedAudioChannelsDescriptionCodeSequence","SQ"], [0x003A,0x0301,"ChannelIdentificationCode","IS"], [0x003A,0x0302,"ChannelMode","CS"], [0x0040,0x0001,"ScheduledStationAETitle","AE"], [0x0040,0x0002,"ScheduledProcedureStepStartDate","DA"], [0x0040,0x0003,"ScheduledProcedureStepStartTime","TM"], [0x0040,0x0004,"ScheduledProcedureStepEndDate","DA"], [0x0040,0x0005,"ScheduledProcedureStepEndTime","TM"], [0x0040,0x0006,"ScheduledPerformingPhysicianName","PN"], [0x0040,0x0007,"ScheduledProcedureStepDescription","LO"], [0x0040,0x0008,"ScheduledProtocolCodeSequence","SQ"], [0x0040,0x0009,"ScheduledProcedureStepID","SH"], [0x0040,0x000A,"StageCodeSequence","SQ"], [0x0040,0x000B,"ScheduledPerformingPhysicianIdentificationSequence","SQ"], [0x0040,0x0010,"ScheduledStationName","SH"], [0x0040,0x0011,"ScheduledProcedureStepLocation","SH"], [0x0040,0x0012,"PreMedication","LO"], [0x0040,0x0020,"ScheduledProcedureStepStatus","CS"], [0x0040,0x0026,"OrderPlacerIdentifierSequence","SQ"], [0x0040,0x0027,"OrderFillerIdentifierSequence","SQ"], [0x0040,0x0031,"LocalNamespaceEntityID","UT"], [0x0040,0x0032,"UniversalEntityID","UT"], [0x0040,0x0033,"UniversalEntityIDType","CS"], [0x0040,0x0035,"IdentifierTypeCode","CS"], [0x0040,0x0036,"AssigningFacilitySequence","SQ"], [0x0040,0x0039,"AssigningJurisdictionCodeSequence","SQ"], [0x0040,0x003A,"AssigningAgencyOrDepartmentCodeSequence","SQ"], [0x0040,0x0100,"ScheduledProcedureStepSequence","SQ"], [0x0040,0x0220,"ReferencedNonImageCompositeSOPInstanceSequence","SQ"], [0x0040,0x0241,"PerformedStationAETitle","AE"], [0x0040,0x0242,"PerformedStationName","SH"], [0x0040,0x0243,"PerformedLocation","SH"], [0x0040,0x0244,"PerformedProcedureStepStartDate","DA"], [0x0040,0x0245,"PerformedProcedureStepStartTime","TM"], [0x0040,0x0250,"PerformedProcedureStepEndDate","DA"], [0x0040,0x0251,"PerformedProcedureStepEndTime","TM"], [0x0040,0x0252,"PerformedProcedureStepStatus","CS"], [0x0040,0x0253,"PerformedProcedureStepID","SH"], [0x0040,0x0254,"PerformedProcedureStepDescription","LO"], [0x0040,0x0255,"PerformedProcedureTypeDescription","LO"], [0x0040,0x0260,"PerformedProtocolCodeSequence","SQ"], [0x0040,0x0261,"PerformedProtocolType","CS"], [0x0040,0x0270,"ScheduledStepAttributesSequence","SQ"], [0x0040,0x0275,"RequestAttributesSequence","SQ"], [0x0040,0x0280,"CommentsOnThePerformedProcedureStep","ST"], [0x0040,0x0281,"PerformedProcedureStepDiscontinuationReasonCodeSequence","SQ"], [0x0040,0x0293,"QuantitySequence","SQ"], [0x0040,0x0294,"Quantity","DS"], [0x0040,0x0295,"MeasuringUnitsSequence","SQ"], [0x0040,0x0296,"BillingItemSequence","SQ"], [0x0040,0x0300,"TotalTimeOfFluoroscopy","US"], [0x0040,0x0301,"TotalNumberOfExposures","US"], [0x0040,0x0302,"EntranceDose","US"], [0x0040,0x0303,"ExposedArea","US"], [0x0040,0x0306,"DistanceSourceToEntrance","DS"], [0x0040,0x0307,"DistanceSourceToSupport","DS"], [0x0040,0x030E,"ExposureDoseSequence","SQ"], [0x0040,0x0310,"CommentsOnRadiationDose","ST"], [0x0040,0x0312,"XRayOutput","DS"], [0x0040,0x0314,"HalfValueLayer","DS"], [0x0040,0x0316,"OrganDose","DS"], [0x0040,0x0318,"OrganExposed","CS"], [0x0040,0x0320,"BillingProcedureStepSequence","SQ"], [0x0040,0x0321,"FilmConsumptionSequence","SQ"], [0x0040,0x0324,"BillingSuppliesAndDevicesSequence","SQ"], [0x0040,0x0330,"ReferencedProcedureStepSequence","SQ"], [0x0040,0x0340,"PerformedSeriesSequence","SQ"], [0x0040,0x0400,"CommentsOnTheScheduledProcedureStep","LT"], [0x0040,0x0440,"ProtocolContextSequence","SQ"], [0x0040,0x0441,"ContentItemModifierSequence","SQ"], [0x0040,0x0500,"ScheduledSpecimenSequence","SQ"], [0x0040,0x050A,"SpecimenAccessionNumber","LO"], [0x0040,0x0512,"ContainerIdentifier","LO"], [0x0040,0x0513,"IssuerOfTheContainerIdentifierSequence","SQ"], [0x0040,0x0515,"AlternateContainerIdentifierSequence","SQ"], [0x0040,0x0518,"ContainerTypeCodeSequence","SQ"], [0x0040,0x051A,"ContainerDescription","LO"], [0x0040,0x0520,"ContainerComponentSequence","SQ"], [0x0040,0x0550,"SpecimenSequence","SQ"], [0x0040,0x0551,"SpecimenIdentifier","LO"], [0x0040,0x0552,"SpecimenDescriptionSequenceTrial","SQ"], [0x0040,0x0553,"SpecimenDescriptionTrial","ST"], [0x0040,0x0554,"SpecimenUID","UI"], [0x0040,0x0555,"AcquisitionContextSequence","SQ"], [0x0040,0x0556,"AcquisitionContextDescription","ST"], [0x0040,0x059A,"SpecimenTypeCodeSequence","SQ"], [0x0040,0x0560,"SpecimenDescriptionSequence","SQ"], [0x0040,0x0562,"IssuerOfTheSpecimenIdentifierSequence","SQ"], [0x0040,0x0600,"SpecimenShortDescription","LO"], [0x0040,0x0602,"SpecimenDetailedDescription","UT"], [0x0040,0x0610,"SpecimenPreparationSequence","SQ"], [0x0040,0x0612,"SpecimenPreparationStepContentItemSequence","SQ"], [0x0040,0x0620,"SpecimenLocalizationContentItemSequence","SQ"], [0x0040,0x06FA,"SlideIdentifier","LO"], [0x0040,0x071A,"ImageCenterPointCoordinatesSequence","SQ"], [0x0040,0x072A,"XOffsetInSlideCoordinateSystem","DS"], [0x0040,0x073A,"YOffsetInSlideCoordinateSystem","DS"], [0x0040,0x074A,"ZOffsetInSlideCoordinateSystem","DS"], [0x0040,0x08D8,"PixelSpacingSequence","SQ"], [0x0040,0x08DA,"CoordinateSystemAxisCodeSequence","SQ"], [0x0040,0x08EA,"MeasurementUnitsCodeSequence","SQ"], [0x0040,0x09F8,"VitalStainCodeSequenceTrial","SQ"], [0x0040,0x1001,"RequestedProcedureID","SH"], [0x0040,0x1002,"ReasonForTheRequestedProcedure","LO"], [0x0040,0x1003,"RequestedProcedurePriority","SH"], [0x0040,0x1004,"PatientTransportArrangements","LO"], [0x0040,0x1005,"RequestedProcedureLocation","LO"], [0x0040,0x1006,"PlacerOrderNumberProcedure","SH"], [0x0040,0x1007,"FillerOrderNumberProcedure","SH"], [0x0040,0x1008,"ConfidentialityCode","LO"], [0x0040,0x1009,"ReportingPriority","SH"], [0x0040,0x100A,"ReasonForRequestedProcedureCodeSequence","SQ"], [0x0040,0x1010,"NamesOfIntendedRecipientsOfResults","PN"], [0x0040,0x1011,"IntendedRecipientsOfResultsIdentificationSequence","SQ"], [0x0040,0x1012,"ReasonForPerformedProcedureCodeSequence","SQ"], [0x0040,0x1060,"RequestedProcedureDescriptionTrial","LO"], [0x0040,0x1101,"PersonIdentificationCodeSequence","SQ"], [0x0040,0x1102,"PersonAddress","ST"], [0x0040,0x1103,"PersonTelephoneNumbers","LO"], [0x0040,0x1400,"RequestedProcedureComments","LT"], [0x0040,0x2001,"ReasonForTheImagingServiceRequest","LO"], [0x0040,0x2004,"IssueDateOfImagingServiceRequest","DA"], [0x0040,0x2005,"IssueTimeOfImagingServiceRequest","TM"], [0x0040,0x2006,"PlacerOrderNumberImagingServiceRequestRetired","SH"], [0x0040,0x2007,"FillerOrderNumberImagingServiceRequestRetired","SH"], [0x0040,0x2008,"OrderEnteredBy","PN"], [0x0040,0x2009,"OrderEntererLocation","SH"], [0x0040,0x2010,"OrderCallbackPhoneNumber","SH"], [0x0040,0x2016,"PlacerOrderNumberImagingServiceRequest","LO"], [0x0040,0x2017,"FillerOrderNumberImagingServiceRequest","LO"], [0x0040,0x2400,"ImagingServiceRequestComments","LT"], [0x0040,0x3001,"ConfidentialityConstraintOnPatientDataDescription","LO"], [0x0040,0x4001,"GeneralPurposeScheduledProcedureStepStatus","CS"], [0x0040,0x4002,"GeneralPurposePerformedProcedureStepStatus","CS"], [0x0040,0x4003,"GeneralPurposeScheduledProcedureStepPriority","CS"], [0x0040,0x4004,"ScheduledProcessingApplicationsCodeSequence","SQ"], [0x0040,0x4005,"ScheduledProcedureStepStartDateTime","DT"], [0x0040,0x4006,"MultipleCopiesFlag","CS"], [0x0040,0x4007,"PerformedProcessingApplicationsCodeSequence","SQ"], [0x0040,0x4009,"HumanPerformerCodeSequence","SQ"], [0x0040,0x4010,"ScheduledProcedureStepModificationDateTime","DT"], [0x0040,0x4011,"ExpectedCompletionDateTime","DT"], [0x0040,0x4015,"ResultingGeneralPurposePerformedProcedureStepsSequence","SQ"], [0x0040,0x4016,"ReferencedGeneralPurposeScheduledProcedureStepSequence","SQ"], [0x0040,0x4018,"ScheduledWorkitemCodeSequence","SQ"], [0x0040,0x4019,"PerformedWorkitemCodeSequence","SQ"], [0x0040,0x4020,"InputAvailabilityFlag","CS"], [0x0040,0x4021,"InputInformationSequence","SQ"], [0x0040,0x4022,"RelevantInformationSequence","SQ"], [0x0040,0x4023,"ReferencedGeneralPurposeScheduledProcedureStepTransactionUID","UI"], [0x0040,0x4025,"ScheduledStationNameCodeSequence","SQ"], [0x0040,0x4026,"ScheduledStationClassCodeSequence","SQ"], [0x0040,0x4027,"ScheduledStationGeographicLocationCodeSequence","SQ"], [0x0040,0x4028,"PerformedStationNameCodeSequence","SQ"], [0x0040,0x4029,"PerformedStationClassCodeSequence","SQ"], [0x0040,0x4030,"PerformedStationGeographicLocationCodeSequence","SQ"], [0x0040,0x4031,"RequestedSubsequentWorkitemCodeSequence","SQ"], [0x0040,0x4032,"NonDICOMOutputCodeSequence","SQ"], [0x0040,0x4033,"OutputInformationSequence","SQ"], [0x0040,0x4034,"ScheduledHumanPerformersSequence","SQ"], [0x0040,0x4035,"ActualHumanPerformersSequence","SQ"], [0x0040,0x4036,"HumanPerformerOrganization","LO"], [0x0040,0x4037,"HumanPerformerName","PN"], [0x0040,0x4040,"RawDataHandling","CS"], [0x0040,0x4041,"InputReadinessState","CS"], [0x0040,0x4050,"PerformedProcedureStepStartDateTime","DT"], [0x0040,0x4051,"PerformedProcedureStepEndDateTime","DT"], [0x0040,0x4052,"ProcedureStepCancellationDateTime","DT"], [0x0040,0x8302,"EntranceDoseInmGy","DS"], [0x0040,0x9094,"ReferencedImageRealWorldValueMappingSequence","SQ"], [0x0040,0x9096,"RealWorldValueMappingSequence","SQ"], [0x0040,0x9098,"PixelValueMappingCodeSequence","SQ"], [0x0040,0x9210,"LUTLabel","SH"], [0x0040,0x9211,"RealWorldValueLastValueMapped","SS"], [0x0040,0x9212,"RealWorldValueLUTData","FD"], [0x0040,0x9216,"RealWorldValueFirstValueMapped","SS"], [0x0040,0x9224,"RealWorldValueIntercept","FD"], [0x0040,0x9225,"RealWorldValueSlope","FD"], [0x0040,0xA007,"FindingsFlagTrial","CS"], [0x0040,0xA010,"RelationshipType","CS"], [0x0040,0xA020,"FindingsSequenceTrial","SQ"], [0x0040,0xA021,"FindingsGroupUIDTrial","UI"], [0x0040,0xA022,"ReferencedFindingsGroupUIDTrial","UI"], [0x0040,0xA023,"FindingsGroupRecordingDateTrial","DA"], [0x0040,0xA024,"FindingsGroupRecordingTimeTrial","TM"], [0x0040,0xA026,"FindingsSourceCategoryCodeSequenceTrial","SQ"], [0x0040,0xA027,"VerifyingOrganization","LO"], [0x0040,0xA028,"DocumentingOrganizationIdentifierCodeSequenceTrial","SQ"], [0x0040,0xA030,"VerificationDateTime","DT"], [0x0040,0xA032,"ObservationDateTime","DT"], [0x0040,0xA040,"ValueType","CS"], [0x0040,0xA043,"ConceptNameCodeSequence","SQ"], [0x0040,0xA047,"MeasurementPrecisionDescriptionTrial","LO"], [0x0040,0xA050,"ContinuityOfContent","CS"], [0x0040,0xA057,"UrgencyOrPriorityAlertsTrial","CS"], [0x0040,0xA060,"SequencingIndicatorTrial","LO"], [0x0040,0xA066,"DocumentIdentifierCodeSequenceTrial","SQ"], [0x0040,0xA067,"DocumentAuthorTrial","PN"], [0x0040,0xA068,"DocumentAuthorIdentifierCodeSequenceTrial","SQ"], [0x0040,0xA070,"IdentifierCodeSequenceTrial","SQ"], [0x0040,0xA073,"VerifyingObserverSequence","SQ"], [0x0040,0xA074,"ObjectBinaryIdentifierTrial","OB"], [0x0040,0xA075,"VerifyingObserverName","PN"], [0x0040,0xA076,"DocumentingObserverIdentifierCodeSequenceTrial","SQ"], [0x0040,0xA078,"AuthorObserverSequence","SQ"], [0x0040,0xA07A,"ParticipantSequence","SQ"], [0x0040,0xA07C,"CustodialOrganizationSequence","SQ"], [0x0040,0xA080,"ParticipationType","CS"], [0x0040,0xA082,"ParticipationDateTime","DT"], [0x0040,0xA084,"ObserverType","CS"], [0x0040,0xA085,"ProcedureIdentifierCodeSequenceTrial","SQ"], [0x0040,0xA088,"VerifyingObserverIdentificationCodeSequence","SQ"], [0x0040,0xA089,"ObjectDirectoryBinaryIdentifierTrial","OB"], [0x0040,0xA090,"EquivalentCDADocumentSequence","SQ"], [0x0040,0xA0B0,"ReferencedWaveformChannels","US"], [0x0040,0xA110,"DateOfDocumentOrVerbalTransactionTrial","DA"], [0x0040,0xA112,"TimeOfDocumentCreationOrVerbalTransactionTrial","TM"], [0x0040,0xA120,"DateTime","DT"], [0x0040,0xA121,"Date","DA"], [0x0040,0xA122,"Time","TM"], [0x0040,0xA123,"PersonName","PN"], [0x0040,0xA124,"UID","UI"], [0x0040,0xA125,"ReportStatusIDTrial","CS"], [0x0040,0xA130,"TemporalRangeType","CS"], [0x0040,0xA132,"ReferencedSamplePositions","UL"], [0x0040,0xA136,"ReferencedFrameNumbers","US"], [0x0040,0xA138,"ReferencedTimeOffsets","DS"], [0x0040,0xA13A,"ReferencedDateTime","DT"], [0x0040,0xA160,"TextValue","UT"], [0x0040,0xA167,"ObservationCategoryCodeSequenceTrial","SQ"], [0x0040,0xA168,"ConceptCodeSequence","SQ"], [0x0040,0xA16A,"BibliographicCitationTrial","ST"], [0x0040,0xA170,"PurposeOfReferenceCodeSequence","SQ"], [0x0040,0xA171,"ObservationUIDTrial","UI"], [0x0040,0xA172,"ReferencedObservationUIDTrial","UI"], [0x0040,0xA173,"ReferencedObservationClassTrial","CS"], [0x0040,0xA174,"ReferencedObjectObservationClassTrial","CS"], [0x0040,0xA180,"AnnotationGroupNumber","US"], [0x0040,0xA192,"ObservationDateTrial","DA"], [0x0040,0xA193,"ObservationTimeTrial","TM"], [0x0040,0xA194,"MeasurementAutomationTrial","CS"], [0x0040,0xA195,"ModifierCodeSequence","SQ"], [0x0040,0xA224,"IdentificationDescriptionTrial","ST"], [0x0040,0xA290,"CoordinatesSetGeometricTypeTrial","CS"], [0x0040,0xA296,"AlgorithmCodeSequenceTrial","SQ"], [0x0040,0xA297,"AlgorithmDescriptionTrial","ST"], [0x0040,0xA29A,"PixelCoordinatesSetTrial","SL"], [0x0040,0xA300,"MeasuredValueSequence","SQ"], [0x0040,0xA301,"NumericValueQualifierCodeSequence","SQ"], [0x0040,0xA307,"CurrentObserverTrial","PN"], [0x0040,0xA30A,"NumericValue","DS"], [0x0040,0xA313,"ReferencedAccessionSequenceTrial","SQ"], [0x0040,0xA33A,"ReportStatusCommentTrial","ST"], [0x0040,0xA340,"ProcedureContextSequenceTrial","SQ"], [0x0040,0xA352,"VerbalSourceTrial","PN"], [0x0040,0xA353,"AddressTrial","ST"], [0x0040,0xA354,"TelephoneNumberTrial","LO"], [0x0040,0xA358,"VerbalSourceIdentifierCodeSequenceTrial","SQ"], [0x0040,0xA360,"PredecessorDocumentsSequence","SQ"], [0x0040,0xA370,"ReferencedRequestSequence","SQ"], [0x0040,0xA372,"PerformedProcedureCodeSequence","SQ"], [0x0040,0xA375,"CurrentRequestedProcedureEvidenceSequence","SQ"], [0x0040,0xA380,"ReportDetailSequenceTrial","SQ"], [0x0040,0xA385,"PertinentOtherEvidenceSequence","SQ"], [0x0040,0xA390,"HL7StructuredDocumentReferenceSequence","SQ"], [0x0040,0xA402,"ObservationSubjectUIDTrial","UI"], [0x0040,0xA403,"ObservationSubjectClassTrial","CS"], [0x0040,0xA404,"ObservationSubjectTypeCodeSequenceTrial","SQ"], [0x0040,0xA491,"CompletionFlag","CS"], [0x0040,0xA492,"CompletionFlagDescription","LO"], [0x0040,0xA493,"VerificationFlag","CS"], [0x0040,0xA494,"ArchiveRequested","CS"], [0x0040,0xA496,"PreliminaryFlag","CS"], [0x0040,0xA504,"ContentTemplateSequence","SQ"], [0x0040,0xA525,"IdenticalDocumentsSequence","SQ"], [0x0040,0xA600,"ObservationSubjectContextFlagTrial","CS"], [0x0040,0xA601,"ObserverContextFlagTrial","CS"], [0x0040,0xA603,"ProcedureContextFlagTrial","CS"], [0x0040,0xA730,"ContentSequence","SQ"], [0x0040,0xA731,"RelationshipSequenceTrial","SQ"], [0x0040,0xA732,"RelationshipTypeCodeSequenceTrial","SQ"], [0x0040,0xA744,"LanguageCodeSequenceTrial","SQ"], [0x0040,0xA992,"UniformResourceLocatorTrial","ST"], [0x0040,0xB020,"WaveformAnnotationSequence","SQ"], [0x0040,0xDB00,"TemplateIdentifier","CS"], [0x0040,0xDB06,"TemplateVersion","DT"], [0x0040,0xDB07,"TemplateLocalVersion","DT"], [0x0040,0xDB0B,"TemplateExtensionFlag","CS"], [0x0040,0xDB0C,"TemplateExtensionOrganizationUID","UI"], [0x0040,0xDB0D,"TemplateExtensionCreatorUID","UI"], [0x0040,0xDB73,"ReferencedContentItemIdentifier","UL"], [0x0040,0xE001,"HL7InstanceIdentifier","ST"], [0x0040,0xE004,"HL7DocumentEffectiveTime","DT"], [0x0040,0xE006,"HL7DocumentTypeCodeSequence","SQ"], [0x0040,0xE008,"DocumentClassCodeSequence","SQ"], [0x0040,0xE010,"RetrieveURI","UT"], [0x0040,0xE011,"RetrieveLocationUID","UI"], [0x0040,0xE020,"TypeOfInstances","CS"], [0x0040,0xE021,"DICOMRetrievalSequence","SQ"], [0x0040,0xE022,"DICOMMediaRetrievalSequence","SQ"], [0x0040,0xE023,"WADORetrievalSequence","SQ"], [0x0040,0xE024,"XDSRetrievalSequence","SQ"], [0x0040,0xE030,"RepositoryUniqueID","UI"], [0x0040,0xE031,"HomeCommunityID","UI"], [0x0042,0x0010,"DocumentTitle","ST"], [0x0042,0x0011,"EncapsulatedDocument","OB"], [0x0042,0x0012,"MIMETypeOfEncapsulatedDocument","LO"], [0x0042,0x0013,"SourceInstanceSequence","SQ"], [0x0042,0x0014,"ListOfMIMETypes","LO"], [0x0044,0x0001,"ProductPackageIdentifier","ST"], [0x0044,0x0002,"SubstanceAdministrationApproval","CS"], [0x0044,0x0003,"ApprovalStatusFurtherDescription","LT"], [0x0044,0x0004,"ApprovalStatusDateTime","DT"], [0x0044,0x0007,"ProductTypeCodeSequence","SQ"], [0x0044,0x0008,"ProductName","LO"], [0x0044,0x0009,"ProductDescription","LT"], [0x0044,0x000A,"ProductLotIdentifier","LO"], [0x0044,0x000B,"ProductExpirationDateTime","DT"], [0x0044,0x0010,"SubstanceAdministrationDateTime","DT"], [0x0044,0x0011,"SubstanceAdministrationNotes","LO"], [0x0044,0x0012,"SubstanceAdministrationDeviceID","LO"], [0x0044,0x0013,"ProductParameterSequence","SQ"], [0x0044,0x0019,"SubstanceAdministrationParameterSequence","SQ"], [0x0046,0x0012,"LensDescription","LO"], [0x0046,0x0014,"RightLensSequence","SQ"], [0x0046,0x0015,"LeftLensSequence","SQ"], [0x0046,0x0016,"UnspecifiedLateralityLensSequence","SQ"], [0x0046,0x0018,"CylinderSequence","SQ"], [0x0046,0x0028,"PrismSequence","SQ"], [0x0046,0x0030,"HorizontalPrismPower","FD"], [0x0046,0x0032,"HorizontalPrismBase","CS"], [0x0046,0x0034,"VerticalPrismPower","FD"], [0x0046,0x0036,"VerticalPrismBase","CS"], [0x0046,0x0038,"LensSegmentType","CS"], [0x0046,0x0040,"OpticalTransmittance","FD"], [0x0046,0x0042,"ChannelWidth","FD"], [0x0046,0x0044,"PupilSize","FD"], [0x0046,0x0046,"CornealSize","FD"], [0x0046,0x0050,"AutorefractionRightEyeSequence","SQ"], [0x0046,0x0052,"AutorefractionLeftEyeSequence","SQ"], [0x0046,0x0060,"DistancePupillaryDistance","FD"], [0x0046,0x0062,"NearPupillaryDistance","FD"], [0x0046,0x0063,"IntermediatePupillaryDistance","FD"], [0x0046,0x0064,"OtherPupillaryDistance","FD"], [0x0046,0x0070,"KeratometryRightEyeSequence","SQ"], [0x0046,0x0071,"KeratometryLeftEyeSequence","SQ"], [0x0046,0x0074,"SteepKeratometricAxisSequence","SQ"], [0x0046,0x0075,"RadiusOfCurvature","FD"], [0x0046,0x0076,"KeratometricPower","FD"], [0x0046,0x0077,"KeratometricAxis","FD"], [0x0046,0x0080,"FlatKeratometricAxisSequence","SQ"], [0x0046,0x0092,"BackgroundColor","CS"], [0x0046,0x0094,"Optotype","CS"], [0x0046,0x0095,"OptotypePresentation","CS"], [0x0046,0x0097,"SubjectiveRefractionRightEyeSequence","SQ"], [0x0046,0x0098,"SubjectiveRefractionLeftEyeSequence","SQ"], [0x0046,0x0100,"AddNearSequence","SQ"], [0x0046,0x0101,"AddIntermediateSequence","SQ"], [0x0046,0x0102,"AddOtherSequence","SQ"], [0x0046,0x0104,"AddPower","FD"], [0x0046,0x0106,"ViewingDistance","FD"], [0x0046,0x0121,"VisualAcuityTypeCodeSequence","SQ"], [0x0046,0x0122,"VisualAcuityRightEyeSequence","SQ"], [0x0046,0x0123,"VisualAcuityLeftEyeSequence","SQ"], [0x0046,0x0124,"VisualAcuityBothEyesOpenSequence","SQ"], [0x0046,0x0125,"ViewingDistanceType","CS"], [0x0046,0x0135,"VisualAcuityModifiers","SS"], [0x0046,0x0137,"DecimalVisualAcuity","FD"], [0x0046,0x0139,"OptotypeDetailedDefinition","LO"], [0x0046,0x0145,"ReferencedRefractiveMeasurementsSequence","SQ"], [0x0046,0x0146,"SpherePower","FD"], [0x0046,0x0147,"CylinderPower","FD"], [0x0048,0x0001,"ImagedVolumeWidth","FL"], [0x0048,0x0002,"ImagedVolumeHeight","FL"], [0x0048,0x0003,"ImagedVolumeDepth","FL"], [0x0048,0x0006,"TotalPixelMatrixColumns","UL"], [0x0048,0x0007,"TotalPixelMatrixRows","UL"], [0x0048,0x0008,"TotalPixelMatrixOriginSequence","SQ"], [0x0048,0x0010,"SpecimenLabelInImage","CS"], [0x0048,0x0011,"FocusMethod","CS"], [0x0048,0x0012,"ExtendedDepthOfField","CS"], [0x0048,0x0013,"NumberOfFocalPlanes","US"], [0x0048,0x0014,"DistanceBetweenFocalPlanes","FL"], [0x0048,0x0015,"RecommendedAbsentPixelCIELabValue","US"], [0x0048,0x0100,"IlluminatorTypeCodeSequence","SQ"], [0x0048,0x0102,"ImageOrientationSlide","DS"], [0x0048,0x0105,"OpticalPathSequence","SQ"], [0x0048,0x0106,"OpticalPathIdentifier","SH"], [0x0048,0x0107,"OpticalPathDescription","ST"], [0x0048,0x0108,"IlluminationColorCodeSequence","SQ"], [0x0048,0x0110,"SpecimenReferenceSequence","SQ"], [0x0048,0x0111,"CondenserLensPower","DS"], [0x0048,0x0112,"ObjectiveLensPower","DS"], [0x0048,0x0113,"ObjectiveLensNumericalAperture","DS"], [0x0048,0x0120,"PaletteColorLookupTableSequence","SQ"], [0x0048,0x0200,"ReferencedImageNavigationSequence","SQ"], [0x0048,0x0201,"TopLeftHandCornerOfLocalizerArea","US"], [0x0048,0x0202,"BottomRightHandCornerOfLocalizerArea","US"], [0x0048,0x0207,"OpticalPathIdentificationSequence","SQ"], [0x0048,0x021A,"PlanePositionSlideSequence","SQ"], [0x0048,0x021E,"RowPositionInTotalImagePixelMatrix","SL"], [0x0048,0x021F,"ColumnPositionInTotalImagePixelMatrix","SL"], [0x0048,0x0301,"PixelOriginInterpretation","CS"], [0x0050,0x0004,"CalibrationImage","CS"], [0x0050,0x0010,"DeviceSequence","SQ"], [0x0050,0x0012,"ContainerComponentTypeCodeSequence","SQ"], [0x0050,0x0013,"ContainerComponentThickness","FD"], [0x0050,0x0014,"DeviceLength","DS"], [0x0050,0x0015,"ContainerComponentWidth","FD"], [0x0050,0x0016,"DeviceDiameter","DS"], [0x0050,0x0017,"DeviceDiameterUnits","CS"], [0x0050,0x0018,"DeviceVolume","DS"], [0x0050,0x0019,"InterMarkerDistance","DS"], [0x0050,0x001A,"ContainerComponentMaterial","CS"], [0x0050,0x001B,"ContainerComponentID","LO"], [0x0050,0x001C,"ContainerComponentLength","FD"], [0x0050,0x001D,"ContainerComponentDiameter","FD"], [0x0050,0x001E,"ContainerComponentDescription","LO"], [0x0050,0x0020,"DeviceDescription","LO"], [0x0052,0x0001,"ContrastBolusIngredientPercentByVolume","FL"], [0x0052,0x0002,"OCTFocalDistance","FD"], [0x0052,0x0003,"BeamSpotSize","FD"], [0x0052,0x0004,"EffectiveRefractiveIndex","FD"], [0x0052,0x0006,"OCTAcquisitionDomain","CS"], [0x0052,0x0007,"OCTOpticalCenterWavelength","FD"], [0x0052,0x0008,"AxialResolution","FD"], [0x0052,0x0009,"RangingDepth","FD"], [0x0052,0x0011,"ALineRate","FD"], [0x0052,0x0012,"ALinesPerFrame","US"], [0x0052,0x0013,"CatheterRotationalRate","FD"], [0x0052,0x0014,"ALinePixelSpacing","FD"], [0x0052,0x0016,"ModeOfPercutaneousAccessSequence","SQ"], [0x0052,0x0025,"IntravascularOCTFrameTypeSequence","SQ"], [0x0052,0x0026,"OCTZOffsetApplied","CS"], [0x0052,0x0027,"IntravascularFrameContentSequence","SQ"], [0x0052,0x0028,"IntravascularLongitudinalDistance","FD"], [0x0052,0x0029,"IntravascularOCTFrameContentSequence","SQ"], [0x0052,0x0030,"OCTZOffsetCorrection","SS"], [0x0052,0x0031,"CatheterDirectionOfRotation","CS"], [0x0052,0x0033,"SeamLineLocation","FD"], [0x0052,0x0034,"FirstALineLocation","FD"], [0x0052,0x0036,"SeamLineIndex","US"], [0x0052,0x0038,"NumberOfPaddedAlines","US"], [0x0052,0x0039,"InterpolationType","CS"], [0x0052,0x003A,"RefractiveIndexApplied","CS"], [0x0054,0x0010,"EnergyWindowVector","US"], [0x0054,0x0011,"NumberOfEnergyWindows","US"], [0x0054,0x0012,"EnergyWindowInformationSequence","SQ"], [0x0054,0x0013,"EnergyWindowRangeSequence","SQ"], [0x0054,0x0014,"EnergyWindowLowerLimit","DS"], [0x0054,0x0015,"EnergyWindowUpperLimit","DS"], [0x0054,0x0016,"RadiopharmaceuticalInformationSequence","SQ"], [0x0054,0x0017,"ResidualSyringeCounts","IS"], [0x0054,0x0018,"EnergyWindowName","SH"], [0x0054,0x0020,"DetectorVector","US"], [0x0054,0x0021,"NumberOfDetectors","US"], [0x0054,0x0022,"DetectorInformationSequence","SQ"], [0x0054,0x0030,"PhaseVector","US"], [0x0054,0x0031,"NumberOfPhases","US"], [0x0054,0x0032,"PhaseInformationSequence","SQ"], [0x0054,0x0033,"NumberOfFramesInPhase","US"], [0x0054,0x0036,"PhaseDelay","IS"], [0x0054,0x0038,"PauseBetweenFrames","IS"], [0x0054,0x0039,"PhaseDescription","CS"], [0x0054,0x0050,"RotationVector","US"], [0x0054,0x0051,"NumberOfRotations","US"], [0x0054,0x0052,"RotationInformationSequence","SQ"], [0x0054,0x0053,"NumberOfFramesInRotation","US"], [0x0054,0x0060,"RRIntervalVector","US"], [0x0054,0x0061,"NumberOfRRIntervals","US"], [0x0054,0x0062,"GatedInformationSequence","SQ"], [0x0054,0x0063,"DataInformationSequence","SQ"], [0x0054,0x0070,"TimeSlotVector","US"], [0x0054,0x0071,"NumberOfTimeSlots","US"], [0x0054,0x0072,"TimeSlotInformationSequence","SQ"], [0x0054,0x0073,"TimeSlotTime","DS"], [0x0054,0x0080,"SliceVector","US"], [0x0054,0x0081,"NumberOfSlices","US"], [0x0054,0x0090,"AngularViewVector","US"], [0x0054,0x0100,"TimeSliceVector","US"], [0x0054,0x0101,"NumberOfTimeSlices","US"], [0x0054,0x0200,"StartAngle","DS"], [0x0054,0x0202,"TypeOfDetectorMotion","CS"], [0x0054,0x0210,"TriggerVector","IS"], [0x0054,0x0211,"NumberOfTriggersInPhase","US"], [0x0054,0x0220,"ViewCodeSequence","SQ"], [0x0054,0x0222,"ViewModifierCodeSequence","SQ"], [0x0054,0x0300,"RadionuclideCodeSequence","SQ"], [0x0054,0x0302,"AdministrationRouteCodeSequence","SQ"], [0x0054,0x0304,"RadiopharmaceuticalCodeSequence","SQ"], [0x0054,0x0306,"CalibrationDataSequence","SQ"], [0x0054,0x0308,"EnergyWindowNumber","US"], [0x0054,0x0400,"ImageID","SH"], [0x0054,0x0410,"PatientOrientationCodeSequence","SQ"], [0x0054,0x0412,"PatientOrientationModifierCodeSequence","SQ"], [0x0054,0x0414,"PatientGantryRelationshipCodeSequence","SQ"], [0x0054,0x0500,"SliceProgressionDirection","CS"], [0x0054,0x1000,"SeriesType","CS"], [0x0054,0x1001,"Units","CS"], [0x0054,0x1002,"CountsSource","CS"], [0x0054,0x1004,"ReprojectionMethod","CS"], [0x0054,0x1006,"SUVType","CS"], [0x0054,0x1100,"RandomsCorrectionMethod","CS"], [0x0054,0x1101,"AttenuationCorrectionMethod","LO"], [0x0054,0x1102,"DecayCorrection","CS"], [0x0054,0x1103,"ReconstructionMethod","LO"], [0x0054,0x1104,"DetectorLinesOfResponseUsed","LO"], [0x0054,0x1105,"ScatterCorrectionMethod","LO"], [0x0054,0x1200,"AxialAcceptance","DS"], [0x0054,0x1201,"AxialMash","IS"], [0x0054,0x1202,"TransverseMash","IS"], [0x0054,0x1203,"DetectorElementSize","DS"], [0x0054,0x1210,"CoincidenceWindowWidth","DS"], [0x0054,0x1220,"SecondaryCountsType","CS"], [0x0054,0x1300,"FrameReferenceTime","DS"], [0x0054,0x1310,"PrimaryPromptsCountsAccumulated","IS"], [0x0054,0x1311,"SecondaryCountsAccumulated","IS"], [0x0054,0x1320,"SliceSensitivityFactor","DS"], [0x0054,0x1321,"DecayFactor","DS"], [0x0054,0x1322,"DoseCalibrationFactor","DS"], [0x0054,0x1323,"ScatterFractionFactor","DS"], [0x0054,0x1324,"DeadTimeFactor","DS"], [0x0054,0x1330,"ImageIndex","US"], [0x0054,0x1400,"CountsIncluded","CS"], [0x0054,0x1401,"DeadTimeCorrectionFlag","CS"], [0x0060,0x3000,"HistogramSequence","SQ"], [0x0060,0x3002,"HistogramNumberOfBins","US"], [0x0060,0x3004,"HistogramFirstBinValue","SS"], [0x0060,0x3006,"HistogramLastBinValue","SS"], [0x0060,0x3008,"HistogramBinWidth","US"], [0x0060,0x3010,"HistogramExplanation","LO"], [0x0060,0x3020,"HistogramData","UL"], [0x0062,0x0001,"SegmentationType","CS"], [0x0062,0x0002,"SegmentSequence","SQ"], [0x0062,0x0003,"SegmentedPropertyCategoryCodeSequence","SQ"], [0x0062,0x0004,"SegmentNumber","US"], [0x0062,0x0005,"SegmentLabel","LO"], [0x0062,0x0006,"SegmentDescription","ST"], [0x0062,0x0008,"SegmentAlgorithmType","CS"], [0x0062,0x0009,"SegmentAlgorithmName","LO"], [0x0062,0x000A,"SegmentIdentificationSequence","SQ"], [0x0062,0x000B,"ReferencedSegmentNumber","US"], [0x0062,0x000C,"RecommendedDisplayGrayscaleValue","US"], [0x0062,0x000D,"RecommendedDisplayCIELabValue","US"], [0x0062,0x000E,"MaximumFractionalValue","US"], [0x0062,0x000F,"SegmentedPropertyTypeCodeSequence","SQ"], [0x0062,0x0010,"SegmentationFractionalType","CS"], [0x0064,0x0002,"DeformableRegistrationSequence","SQ"], [0x0064,0x0003,"SourceFrameOfReferenceUID","UI"], [0x0064,0x0005,"DeformableRegistrationGridSequence","SQ"], [0x0064,0x0007,"GridDimensions","UL"], [0x0064,0x0008,"GridResolution","FD"], [0x0064,0x0009,"VectorGridData","OF"], [0x0064,0x000F,"PreDeformationMatrixRegistrationSequence","SQ"], [0x0064,0x0010,"PostDeformationMatrixRegistrationSequence","SQ"], [0x0066,0x0001,"NumberOfSurfaces","UL"], [0x0066,0x0002,"SurfaceSequence","SQ"], [0x0066,0x0003,"SurfaceNumber","UL"], [0x0066,0x0004,"SurfaceComments","LT"], [0x0066,0x0009,"SurfaceProcessing","CS"], [0x0066,0x000A,"SurfaceProcessingRatio","FL"], [0x0066,0x000B,"SurfaceProcessingDescription","LO"], [0x0066,0x000C,"RecommendedPresentationOpacity","FL"], [0x0066,0x000D,"RecommendedPresentationType","CS"], [0x0066,0x000E,"FiniteVolume","CS"], [0x0066,0x0010,"Manifold","CS"], [0x0066,0x0011,"SurfacePointsSequence","SQ"], [0x0066,0x0012,"SurfacePointsNormalsSequence","SQ"], [0x0066,0x0013,"SurfaceMeshPrimitivesSequence","SQ"], [0x0066,0x0015,"NumberOfSurfacePoints","UL"], [0x0066,0x0016,"PointCoordinatesData","OF"], [0x0066,0x0017,"PointPositionAccuracy","FL"], [0x0066,0x0018,"MeanPointDistance","FL"], [0x0066,0x0019,"MaximumPointDistance","FL"], [0x0066,0x001A,"PointsBoundingBoxCoordinates","FL"], [0x0066,0x001B,"AxisOfRotation","FL"], [0x0066,0x001C,"CenterOfRotation","FL"], [0x0066,0x001E,"NumberOfVectors","UL"], [0x0066,0x001F,"VectorDimensionality","US"], [0x0066,0x0020,"VectorAccuracy","FL"], [0x0066,0x0021,"VectorCoordinateData","OF"], [0x0066,0x0023,"TrianglePointIndexList","OW"], [0x0066,0x0024,"EdgePointIndexList","OW"], [0x0066,0x0025,"VertexPointIndexList","OW"], [0x0066,0x0026,"TriangleStripSequence","SQ"], [0x0066,0x0027,"TriangleFanSequence","SQ"], [0x0066,0x0028,"LineSequence","SQ"], [0x0066,0x0029,"PrimitivePointIndexList","OW"], [0x0066,0x002A,"SurfaceCount","UL"], [0x0066,0x002B,"ReferencedSurfaceSequence","SQ"], [0x0066,0x002C,"ReferencedSurfaceNumber","UL"], [0x0066,0x002D,"SegmentSurfaceGenerationAlgorithmIdentificationSequence","SQ"], [0x0066,0x002E,"SegmentSurfaceSourceInstanceSequence","SQ"], [0x0066,0x002F,"AlgorithmFamilyCodeSequence","SQ"], [0x0066,0x0030,"AlgorithmNameCodeSequence","SQ"], [0x0066,0x0031,"AlgorithmVersion","LO"], [0x0066,0x0032,"AlgorithmParameters","LT"], [0x0066,0x0034,"FacetSequence","SQ"], [0x0066,0x0035,"SurfaceProcessingAlgorithmIdentificationSequence","SQ"], [0x0066,0x0036,"AlgorithmName","LO"], [0x0068,0x6210,"ImplantSize","LO"], [0x0068,0x6221,"ImplantTemplateVersion","LO"], [0x0068,0x6222,"ReplacedImplantTemplateSequence","SQ"], [0x0068,0x6223,"ImplantType","CS"], [0x0068,0x6224,"DerivationImplantTemplateSequence","SQ"], [0x0068,0x6225,"OriginalImplantTemplateSequence","SQ"], [0x0068,0x6226,"EffectiveDateTime","DT"], [0x0068,0x6230,"ImplantTargetAnatomySequence","SQ"], [0x0068,0x6260,"InformationFromManufacturerSequence","SQ"], [0x0068,0x6265,"NotificationFromManufacturerSequence","SQ"], [0x0068,0x6270,"InformationIssueDateTime","DT"], [0x0068,0x6280,"InformationSummary","ST"], [0x0068,0x62A0,"ImplantRegulatoryDisapprovalCodeSequence","SQ"], [0x0068,0x62A5,"OverallTemplateSpatialTolerance","FD"], [0x0068,0x62C0,"HPGLDocumentSequence","SQ"], [0x0068,0x62D0,"HPGLDocumentID","US"], [0x0068,0x62D5,"HPGLDocumentLabel","LO"], [0x0068,0x62E0,"ViewOrientationCodeSequence","SQ"], [0x0068,0x62F0,"ViewOrientationModifier","FD"], [0x0068,0x62F2,"HPGLDocumentScaling","FD"], [0x0068,0x6300,"HPGLDocument","OB"], [0x0068,0x6310,"HPGLContourPenNumber","US"], [0x0068,0x6320,"HPGLPenSequence","SQ"], [0x0068,0x6330,"HPGLPenNumber","US"], [0x0068,0x6340,"HPGLPenLabel","LO"], [0x0068,0x6345,"HPGLPenDescription","ST"], [0x0068,0x6346,"RecommendedRotationPoint","FD"], [0x0068,0x6347,"BoundingRectangle","FD"], [0x0068,0x6350,"ImplantTemplate3DModelSurfaceNumber","US"], [0x0068,0x6360,"SurfaceModelDescriptionSequence","SQ"], [0x0068,0x6380,"SurfaceModelLabel","LO"], [0x0068,0x6390,"SurfaceModelScalingFactor","FD"], [0x0068,0x63A0,"MaterialsCodeSequence","SQ"], [0x0068,0x63A4,"CoatingMaterialsCodeSequence","SQ"], [0x0068,0x63A8,"ImplantTypeCodeSequence","SQ"], [0x0068,0x63AC,"FixationMethodCodeSequence","SQ"], [0x0068,0x63B0,"MatingFeatureSetsSequence","SQ"], [0x0068,0x63C0,"MatingFeatureSetID","US"], [0x0068,0x63D0,"MatingFeatureSetLabel","LO"], [0x0068,0x63E0,"MatingFeatureSequence","SQ"], [0x0068,0x63F0,"MatingFeatureID","US"], [0x0068,0x6400,"MatingFeatureDegreeOfFreedomSequence","SQ"], [0x0068,0x6410,"DegreeOfFreedomID","US"], [0x0068,0x6420,"DegreeOfFreedomType","CS"], [0x0068,0x6430,"TwoDMatingFeatureCoordinatesSequence","SQ"], [0x0068,0x6440,"ReferencedHPGLDocumentID","US"], [0x0068,0x6450,"TwoDMatingPoint","FD"], [0x0068,0x6460,"TwoDMatingAxes","FD"], [0x0068,0x6470,"TwoDDegreeOfFreedomSequence","SQ"], [0x0068,0x6490,"ThreeDDegreeOfFreedomAxis","FD"], [0x0068,0x64A0,"RangeOfFreedom","FD"], [0x0068,0x64C0,"ThreeDMatingPoint","FD"], [0x0068,0x64D0,"ThreeDMatingAxes","FD"], [0x0068,0x64F0,"TwoDDegreeOfFreedomAxis","FD"], [0x0068,0x6500,"PlanningLandmarkPointSequence","SQ"], [0x0068,0x6510,"PlanningLandmarkLineSequence","SQ"], [0x0068,0x6520,"PlanningLandmarkPlaneSequence","SQ"], [0x0068,0x6530,"PlanningLandmarkID","US"], [0x0068,0x6540,"PlanningLandmarkDescription","LO"], [0x0068,0x6545,"PlanningLandmarkIdentificationCodeSequence","SQ"], [0x0068,0x6550,"TwoDPointCoordinatesSequence","SQ"], [0x0068,0x6560,"TwoDPointCoordinates","FD"], [0x0068,0x6590,"ThreeDPointCoordinates","FD"], [0x0068,0x65A0,"TwoDLineCoordinatesSequence","SQ"], [0x0068,0x65B0,"TwoDLineCoordinates","FD"], [0x0068,0x65D0,"ThreeDLineCoordinates","FD"], [0x0068,0x65E0,"TwoDPlaneCoordinatesSequence","SQ"], [0x0068,0x65F0,"TwoDPlaneIntersection","FD"], [0x0068,0x6610,"ThreeDPlaneOrigin","FD"], [0x0068,0x6620,"ThreeDPlaneNormal","FD"], [0x0070,0x0001,"GraphicAnnotationSequence","SQ"], [0x0070,0x0002,"GraphicLayer","CS"], [0x0070,0x0003,"BoundingBoxAnnotationUnits","CS"], [0x0070,0x0004,"AnchorPointAnnotationUnits","CS"], [0x0070,0x0005,"GraphicAnnotationUnits","CS"], [0x0070,0x0006,"UnformattedTextValue","ST"], [0x0070,0x0008,"TextObjectSequence","SQ"], [0x0070,0x0009,"GraphicObjectSequence","SQ"], [0x0070,0x0010,"BoundingBoxTopLeftHandCorner","FL"], [0x0070,0x0011,"BoundingBoxBottomRightHandCorner","FL"], [0x0070,0x0012,"BoundingBoxTextHorizontalJustification","CS"], [0x0070,0x0014,"AnchorPoint","FL"], [0x0070,0x0015,"AnchorPointVisibility","CS"], [0x0070,0x0020,"GraphicDimensions","US"], [0x0070,0x0021,"NumberOfGraphicPoints","US"], [0x0070,0x0022,"GraphicData","FL"], [0x0070,0x0023,"GraphicType","CS"], [0x0070,0x0024,"GraphicFilled","CS"], [0x0070,0x0040,"ImageRotationRetired","IS"], [0x0070,0x0041,"ImageHorizontalFlip","CS"], [0x0070,0x0042,"ImageRotation","US"], [0x0070,0x0050,"DisplayedAreaTopLeftHandCornerTrial","US"], [0x0070,0x0051,"DisplayedAreaBottomRightHandCornerTrial","US"], [0x0070,0x0052,"DisplayedAreaTopLeftHandCorner","SL"], [0x0070,0x0053,"DisplayedAreaBottomRightHandCorner","SL"], [0x0070,0x005A,"DisplayedAreaSelectionSequence","SQ"], [0x0070,0x0060,"GraphicLayerSequence","SQ"], [0x0070,0x0062,"GraphicLayerOrder","IS"], [0x0070,0x0066,"GraphicLayerRecommendedDisplayGrayscaleValue","US"], [0x0070,0x0067,"GraphicLayerRecommendedDisplayRGBValue","US"], [0x0070,0x0068,"GraphicLayerDescription","LO"], [0x0070,0x0080,"ContentLabel","CS"], [0x0070,0x0081,"ContentDescription","LO"], [0x0070,0x0082,"PresentationCreationDate","DA"], [0x0070,0x0083,"PresentationCreationTime","TM"], [0x0070,0x0084,"ContentCreatorName","PN"], [0x0070,0x0086,"ContentCreatorIdentificationCodeSequence","SQ"], [0x0070,0x0087,"AlternateContentDescriptionSequence","SQ"], [0x0070,0x0100,"PresentationSizeMode","CS"], [0x0070,0x0101,"PresentationPixelSpacing","DS"], [0x0070,0x0102,"PresentationPixelAspectRatio","IS"], [0x0070,0x0103,"PresentationPixelMagnificationRatio","FL"], [0x0070,0x0207,"GraphicGroupLabel","LO"], [0x0070,0x0208,"GraphicGroupDescription","ST"], [0x0070,0x0209,"CompoundGraphicSequence","SQ"], [0x0070,0x0226,"CompoundGraphicInstanceID","UL"], [0x0070,0x0227,"FontName","LO"], [0x0070,0x0228,"FontNameType","CS"], [0x0070,0x0229,"CSSFontName","LO"], [0x0070,0x0230,"RotationAngle","FD"], [0x0070,0x0231,"TextStyleSequence","SQ"], [0x0070,0x0232,"LineStyleSequence","SQ"], [0x0070,0x0233,"FillStyleSequence","SQ"], [0x0070,0x0234,"GraphicGroupSequence","SQ"], [0x0070,0x0241,"TextColorCIELabValue","US"], [0x0070,0x0242,"HorizontalAlignment","CS"], [0x0070,0x0243,"VerticalAlignment","CS"], [0x0070,0x0244,"ShadowStyle","CS"], [0x0070,0x0245,"ShadowOffsetX","FL"], [0x0070,0x0246,"ShadowOffsetY","FL"], [0x0070,0x0247,"ShadowColorCIELabValue","US"], [0x0070,0x0248,"Underlined","CS"], [0x0070,0x0249,"Bold","CS"], [0x0070,0x0250,"Italic","CS"], [0x0070,0x0251,"PatternOnColorCIELabValue","US"], [0x0070,0x0252,"PatternOffColorCIELabValue","US"], [0x0070,0x0253,"LineThickness","FL"], [0x0070,0x0254,"LineDashingStyle","CS"], [0x0070,0x0255,"LinePattern","UL"], [0x0070,0x0256,"FillPattern","OB"], [0x0070,0x0257,"FillMode","CS"], [0x0070,0x0258,"ShadowOpacity","FL"], [0x0070,0x0261,"GapLength","FL"], [0x0070,0x0262,"DiameterOfVisibility","FL"], [0x0070,0x0273,"RotationPoint","FL"], [0x0070,0x0274,"TickAlignment","CS"], [0x0070,0x0278,"ShowTickLabel","CS"], [0x0070,0x0279,"TickLabelAlignment","CS"], [0x0070,0x0282,"CompoundGraphicUnits","CS"], [0x0070,0x0284,"PatternOnOpacity","FL"], [0x0070,0x0285,"PatternOffOpacity","FL"], [0x0070,0x0287,"MajorTicksSequence","SQ"], [0x0070,0x0288,"TickPosition","FL"], [0x0070,0x0289,"TickLabel","SH"], [0x0070,0x0294,"CompoundGraphicType","CS"], [0x0070,0x0295,"GraphicGroupID","UL"], [0x0070,0x0306,"ShapeType","CS"], [0x0070,0x0308,"RegistrationSequence","SQ"], [0x0070,0x0309,"MatrixRegistrationSequence","SQ"], [0x0070,0x030A,"MatrixSequence","SQ"], [0x0070,0x030C,"FrameOfReferenceTransformationMatrixType","CS"], [0x0070,0x030D,"RegistrationTypeCodeSequence","SQ"], [0x0070,0x030F,"FiducialDescription","ST"], [0x0070,0x0310,"FiducialIdentifier","SH"], [0x0070,0x0311,"FiducialIdentifierCodeSequence","SQ"], [0x0070,0x0312,"ContourUncertaintyRadius","FD"], [0x0070,0x0314,"UsedFiducialsSequence","SQ"], [0x0070,0x0318,"GraphicCoordinatesDataSequence","SQ"], [0x0070,0x031A,"FiducialUID","UI"], [0x0070,0x031C,"FiducialSetSequence","SQ"], [0x0070,0x031E,"FiducialSequence","SQ"], [0x0070,0x0401,"GraphicLayerRecommendedDisplayCIELabValue","US"], [0x0070,0x0402,"BlendingSequence","SQ"], [0x0070,0x0403,"RelativeOpacity","FL"], [0x0070,0x0404,"ReferencedSpatialRegistrationSequence","SQ"], [0x0070,0x0405,"BlendingPosition","CS"], [0x0072,0x0002,"HangingProtocolName","SH"], [0x0072,0x0004,"HangingProtocolDescription","LO"], [0x0072,0x0006,"HangingProtocolLevel","CS"], [0x0072,0x0008,"HangingProtocolCreator","LO"], [0x0072,0x000A,"HangingProtocolCreationDateTime","DT"], [0x0072,0x000C,"HangingProtocolDefinitionSequence","SQ"], [0x0072,0x000E,"HangingProtocolUserIdentificationCodeSequence","SQ"], [0x0072,0x0010,"HangingProtocolUserGroupName","LO"], [0x0072,0x0012,"SourceHangingProtocolSequence","SQ"], [0x0072,0x0014,"NumberOfPriorsReferenced","US"], [0x0072,0x0020,"ImageSetsSequence","SQ"], [0x0072,0x0022,"ImageSetSelectorSequence","SQ"], [0x0072,0x0024,"ImageSetSelectorUsageFlag","CS"], [0x0072,0x0026,"SelectorAttribute","AT"], [0x0072,0x0028,"SelectorValueNumber","US"], [0x0072,0x0030,"TimeBasedImageSetsSequence","SQ"], [0x0072,0x0032,"ImageSetNumber","US"], [0x0072,0x0034,"ImageSetSelectorCategory","CS"], [0x0072,0x0038,"RelativeTime","US"], [0x0072,0x003A,"RelativeTimeUnits","CS"], [0x0072,0x003C,"AbstractPriorValue","SS"], [0x0072,0x003E,"AbstractPriorCodeSequence","SQ"], [0x0072,0x0040,"ImageSetLabel","LO"], [0x0072,0x0050,"SelectorAttributeVR","CS"], [0x0072,0x0052,"SelectorSequencePointer","AT"], [0x0072,0x0054,"SelectorSequencePointerPrivateCreator","LO"], [0x0072,0x0056,"SelectorAttributePrivateCreator","LO"], [0x0072,0x0060,"SelectorATValue","AT"], [0x0072,0x0062,"SelectorCSValue","CS"], [0x0072,0x0064,"SelectorISValue","IS"], [0x0072,0x0066,"SelectorLOValue","LO"], [0x0072,0x0068,"SelectorLTValue","LT"], [0x0072,0x006A,"SelectorPNValue","PN"], [0x0072,0x006C,"SelectorSHValue","SH"], [0x0072,0x006E,"SelectorSTValue","ST"], [0x0072,0x0070,"SelectorUTValue","UT"], [0x0072,0x0072,"SelectorDSValue","DS"], [0x0072,0x0074,"SelectorFDValue","FD"], [0x0072,0x0076,"SelectorFLValue","FL"], [0x0072,0x0078,"SelectorULValue","UL"], [0x0072,0x007A,"SelectorUSValue","US"], [0x0072,0x007C,"SelectorSLValue","SL"], [0x0072,0x007E,"SelectorSSValue","SS"], [0x0072,0x0080,"SelectorCodeSequenceValue","SQ"], [0x0072,0x0100,"NumberOfScreens","US"], [0x0072,0x0102,"NominalScreenDefinitionSequence","SQ"], [0x0072,0x0104,"NumberOfVerticalPixels","US"], [0x0072,0x0106,"NumberOfHorizontalPixels","US"], [0x0072,0x0108,"DisplayEnvironmentSpatialPosition","FD"], [0x0072,0x010A,"ScreenMinimumGrayscaleBitDepth","US"], [0x0072,0x010C,"ScreenMinimumColorBitDepth","US"], [0x0072,0x010E,"ApplicationMaximumRepaintTime","US"], [0x0072,0x0200,"DisplaySetsSequence","SQ"], [0x0072,0x0202,"DisplaySetNumber","US"], [0x0072,0x0203,"DisplaySetLabel","LO"], [0x0072,0x0204,"DisplaySetPresentationGroup","US"], [0x0072,0x0206,"DisplaySetPresentationGroupDescription","LO"], [0x0072,0x0208,"PartialDataDisplayHandling","CS"], [0x0072,0x0210,"SynchronizedScrollingSequence","SQ"], [0x0072,0x0212,"DisplaySetScrollingGroup","US"], [0x0072,0x0214,"NavigationIndicatorSequence","SQ"], [0x0072,0x0216,"NavigationDisplaySet","US"], [0x0072,0x0218,"ReferenceDisplaySets","US"], [0x0072,0x0300,"ImageBoxesSequence","SQ"], [0x0072,0x0302,"ImageBoxNumber","US"], [0x0072,0x0304,"ImageBoxLayoutType","CS"], [0x0072,0x0306,"ImageBoxTileHorizontalDimension","US"], [0x0072,0x0308,"ImageBoxTileVerticalDimension","US"], [0x0072,0x0310,"ImageBoxScrollDirection","CS"], [0x0072,0x0312,"ImageBoxSmallScrollType","CS"], [0x0072,0x0314,"ImageBoxSmallScrollAmount","US"], [0x0072,0x0316,"ImageBoxLargeScrollType","CS"], [0x0072,0x0318,"ImageBoxLargeScrollAmount","US"], [0x0072,0x0320,"ImageBoxOverlapPriority","US"], [0x0072,0x0330,"CineRelativeToRealTime","FD"], [0x0072,0x0400,"FilterOperationsSequence","SQ"], [0x0072,0x0402,"FilterByCategory","CS"], [0x0072,0x0404,"FilterByAttributePresence","CS"], [0x0072,0x0406,"FilterByOperator","CS"], [0x0072,0x0420,"StructuredDisplayBackgroundCIELabValue","US"], [0x0072,0x0421,"EmptyImageBoxCIELabValue","US"], [0x0072,0x0422,"StructuredDisplayImageBoxSequence","SQ"], [0x0072,0x0424,"StructuredDisplayTextBoxSequence","SQ"], [0x0072,0x0427,"ReferencedFirstFrameSequence","SQ"], [0x0072,0x0430,"ImageBoxSynchronizationSequence","SQ"], [0x0072,0x0432,"SynchronizedImageBoxList","US"], [0x0072,0x0434,"TypeOfSynchronization","CS"], [0x0072,0x0500,"BlendingOperationType","CS"], [0x0072,0x0510,"ReformattingOperationType","CS"], [0x0072,0x0512,"ReformattingThickness","FD"], [0x0072,0x0514,"ReformattingInterval","FD"], [0x0072,0x0516,"ReformattingOperationInitialViewDirection","CS"], [0x0072,0x0520,"ThreeDRenderingType","CS"], [0x0072,0x0600,"SortingOperationsSequence","SQ"], [0x0072,0x0602,"SortByCategory","CS"], [0x0072,0x0604,"SortingDirection","CS"], [0x0072,0x0700,"DisplaySetPatientOrientation","CS"], [0x0072,0x0702,"VOIType","CS"], [0x0072,0x0704,"PseudoColorType","CS"], [0x0072,0x0705,"PseudoColorPaletteInstanceReferenceSequence","SQ"], [0x0072,0x0706,"ShowGrayscaleInverted","CS"], [0x0072,0x0710,"ShowImageTrueSizeFlag","CS"], [0x0072,0x0712,"ShowGraphicAnnotationFlag","CS"], [0x0072,0x0714,"ShowPatientDemographicsFlag","CS"], [0x0072,0x0716,"ShowAcquisitionTechniquesFlag","CS"], [0x0072,0x0717,"DisplaySetHorizontalJustification","CS"], [0x0072,0x0718,"DisplaySetVerticalJustification","CS"], [0x0074,0x0120,"ContinuationStartMeterset","FD"], [0x0074,0x0121,"ContinuationEndMeterset","FD"], [0x0074,0x1000,"ProcedureStepState","CS"], [0x0074,0x1002,"ProcedureStepProgressInformationSequence","SQ"], [0x0074,0x1004,"ProcedureStepProgress","DS"], [0x0074,0x1006,"ProcedureStepProgressDescription","ST"], [0x0074,0x1008,"ProcedureStepCommunicationsURISequence","SQ"], [0x0074,0x100a,"ContactURI","ST"], [0x0074,0x100c,"ContactDisplayName","LO"], [0x0074,0x100e,"ProcedureStepDiscontinuationReasonCodeSequence","SQ"], [0x0074,0x1020,"BeamTaskSequence","SQ"], [0x0074,0x1022,"BeamTaskType","CS"], [0x0074,0x1024,"BeamOrderIndexTrial","IS"], [0x0074,0x1026,"TableTopVerticalAdjustedPosition","FD"], [0x0074,0x1027,"TableTopLongitudinalAdjustedPosition","FD"], [0x0074,0x1028,"TableTopLateralAdjustedPosition","FD"], [0x0074,0x102A,"PatientSupportAdjustedAngle","FD"], [0x0074,0x102B,"TableTopEccentricAdjustedAngle","FD"], [0x0074,0x102C,"TableTopPitchAdjustedAngle","FD"], [0x0074,0x102D,"TableTopRollAdjustedAngle","FD"], [0x0074,0x1030,"DeliveryVerificationImageSequence","SQ"], [0x0074,0x1032,"VerificationImageTiming","CS"], [0x0074,0x1034,"DoubleExposureFlag","CS"], [0x0074,0x1036,"DoubleExposureOrdering","CS"], [0x0074,0x1038,"DoubleExposureMetersetTrial","DS"], [0x0074,0x103A,"DoubleExposureFieldDeltaTrial","DS"], [0x0074,0x1040,"RelatedReferenceRTImageSequence","SQ"], [0x0074,0x1042,"GeneralMachineVerificationSequence","SQ"], [0x0074,0x1044,"ConventionalMachineVerificationSequence","SQ"], [0x0074,0x1046,"IonMachineVerificationSequence","SQ"], [0x0074,0x1048,"FailedAttributesSequence","SQ"], [0x0074,0x104A,"OverriddenAttributesSequence","SQ"], [0x0074,0x104C,"ConventionalControlPointVerificationSequence","SQ"], [0x0074,0x104E,"IonControlPointVerificationSequence","SQ"], [0x0074,0x1050,"AttributeOccurrenceSequence","SQ"], [0x0074,0x1052,"AttributeOccurrencePointer","AT"], [0x0074,0x1054,"AttributeItemSelector","UL"], [0x0074,0x1056,"AttributeOccurrencePrivateCreator","LO"], [0x0074,0x1057,"SelectorSequencePointerItems","IS"], [0x0074,0x1200,"ScheduledProcedureStepPriority","CS"], [0x0074,0x1202,"WorklistLabel","LO"], [0x0074,0x1204,"ProcedureStepLabel","LO"], [0x0074,0x1210,"ScheduledProcessingParametersSequence","SQ"], [0x0074,0x1212,"PerformedProcessingParametersSequence","SQ"], [0x0074,0x1216,"UnifiedProcedureStepPerformedProcedureSequence","SQ"], [0x0074,0x1220,"RelatedProcedureStepSequence","SQ"], [0x0074,0x1222,"ProcedureStepRelationshipType","LO"], [0x0074,0x1224,"ReplacedProcedureStepSequence","SQ"], [0x0074,0x1230,"DeletionLock","LO"], [0x0074,0x1234,"ReceivingAE","AE"], [0x0074,0x1236,"RequestingAE","AE"], [0x0074,0x1238,"ReasonForCancellation","LT"], [0x0074,0x1242,"SCPStatus","CS"], [0x0074,0x1244,"SubscriptionListStatus","CS"], [0x0074,0x1246,"UnifiedProcedureStepListStatus","CS"], [0x0074,0x1324,"BeamOrderIndex","UL"], [0x0074,0x1338,"DoubleExposureMeterset","FD"], [0x0074,0x133A,"DoubleExposureFieldDelta","FD"], [0x0076,0x0001,"ImplantAssemblyTemplateName","LO"], [0x0076,0x0003,"ImplantAssemblyTemplateIssuer","LO"], [0x0076,0x0006,"ImplantAssemblyTemplateVersion","LO"], [0x0076,0x0008,"ReplacedImplantAssemblyTemplateSequence","SQ"], [0x0076,0x000A,"ImplantAssemblyTemplateType","CS"], [0x0076,0x000C,"OriginalImplantAssemblyTemplateSequence","SQ"], [0x0076,0x000E,"DerivationImplantAssemblyTemplateSequence","SQ"], [0x0076,0x0010,"ImplantAssemblyTemplateTargetAnatomySequence","SQ"], [0x0076,0x0020,"ProcedureTypeCodeSequence","SQ"], [0x0076,0x0030,"SurgicalTechnique","LO"], [0x0076,0x0032,"ComponentTypesSequence","SQ"], [0x0076,0x0034,"ComponentTypeCodeSequence","CS"], [0x0076,0x0036,"ExclusiveComponentType","CS"], [0x0076,0x0038,"MandatoryComponentType","CS"], [0x0076,0x0040,"ComponentSequence","SQ"], [0x0076,0x0055,"ComponentID","US"], [0x0076,0x0060,"ComponentAssemblySequence","SQ"], [0x0076,0x0070,"Component1ReferencedID","US"], [0x0076,0x0080,"Component1ReferencedMatingFeatureSetID","US"], [0x0076,0x0090,"Component1ReferencedMatingFeatureID","US"], [0x0076,0x00A0,"Component2ReferencedID","US"], [0x0076,0x00B0,"Component2ReferencedMatingFeatureSetID","US"], [0x0076,0x00C0,"Component2ReferencedMatingFeatureID","US"], [0x0078,0x0001,"ImplantTemplateGroupName","LO"], [0x0078,0x0010,"ImplantTemplateGroupDescription","ST"], [0x0078,0x0020,"ImplantTemplateGroupIssuer","LO"], [0x0078,0x0024,"ImplantTemplateGroupVersion","LO"], [0x0078,0x0026,"ReplacedImplantTemplateGroupSequence","SQ"], [0x0078,0x0028,"ImplantTemplateGroupTargetAnatomySequence","SQ"], [0x0078,0x002A,"ImplantTemplateGroupMembersSequence","SQ"], [0x0078,0x002E,"ImplantTemplateGroupMemberID","US"], [0x0078,0x0050,"ThreeDImplantTemplateGroupMemberMatchingPoint","FD"], [0x0078,0x0060,"ThreeDImplantTemplateGroupMemberMatchingAxes","FD"], [0x0078,0x0070,"ImplantTemplateGroupMemberMatching2DCoordinatesSequence","SQ"], [0x0078,0x0090,"TwoDImplantTemplateGroupMemberMatchingPoint","FD"], [0x0078,0x00A0,"TwoDImplantTemplateGroupMemberMatchingAxes","FD"], [0x0078,0x00B0,"ImplantTemplateGroupVariationDimensionSequence","SQ"], [0x0078,0x00B2,"ImplantTemplateGroupVariationDimensionName","LO"], [0x0078,0x00B4,"ImplantTemplateGroupVariationDimensionRankSequence","SQ"], [0x0078,0x00B6,"ReferencedImplantTemplateGroupMemberID","US"], [0x0078,0x00B8,"ImplantTemplateGroupVariationDimensionRank","US"], [0x0088,0x0130,"StorageMediaFileSetID","SH"], [0x0088,0x0140,"StorageMediaFileSetUID","UI"], [0x0088,0x0200,"IconImageSequence","SQ"], [0x0088,0x0904,"TopicTitle","LO"], [0x0088,0x0906,"TopicSubject","ST"], [0x0088,0x0910,"TopicAuthor","LO"], [0x0088,0x0912,"TopicKeywords","LO"], [0x0100,0x0410,"SOPInstanceStatus","CS"], [0x0100,0x0420,"SOPAuthorizationDateTime","DT"], [0x0100,0x0424,"SOPAuthorizationComment","LT"], [0x0100,0x0426,"AuthorizationEquipmentCertificationNumber","LO"], [0x0400,0x0005,"MACIDNumber","US"], [0x0400,0x0010,"MACCalculationTransferSyntaxUID","UI"], [0x0400,0x0015,"MACAlgorithm","CS"], [0x0400,0x0020,"DataElementsSigned","AT"], [0x0400,0x0100,"DigitalSignatureUID","UI"], [0x0400,0x0105,"DigitalSignatureDateTime","DT"], [0x0400,0x0110,"CertificateType","CS"], [0x0400,0x0115,"CertificateOfSigner","OB"], [0x0400,0x0120,"Signature","OB"], [0x0400,0x0305,"CertifiedTimestampType","CS"], [0x0400,0x0310,"CertifiedTimestamp","OB"], [0x0400,0x0401,"DigitalSignaturePurposeCodeSequence","SQ"], [0x0400,0x0402,"ReferencedDigitalSignatureSequence","SQ"], [0x0400,0x0403,"ReferencedSOPInstanceMACSequence","SQ"], [0x0400,0x0404,"MAC","OB"], [0x0400,0x0500,"EncryptedAttributesSequence","SQ"], [0x0400,0x0510,"EncryptedContentTransferSyntaxUID","UI"], [0x0400,0x0520,"EncryptedContent","OB"], [0x0400,0x0550,"ModifiedAttributesSequence","SQ"], [0x0400,0x0561,"OriginalAttributesSequence","SQ"], [0x0400,0x0562,"AttributeModificationDateTime","DT"], [0x0400,0x0563,"ModifyingSystem","LO"], [0x0400,0x0564,"SourceOfPreviousValues","LO"], [0x0400,0x0565,"ReasonForTheAttributeModification","CS"], [0x2000,0x0010,"NumberOfCopies","IS"], [0x2000,0x001E,"PrinterConfigurationSequence","SQ"], [0x2000,0x0020,"PrintPriority","CS"], [0x2000,0x0030,"MediumType","CS"], [0x2000,0x0040,"FilmDestination","CS"], [0x2000,0x0050,"FilmSessionLabel","LO"], [0x2000,0x0060,"MemoryAllocation","IS"], [0x2000,0x0061,"MaximumMemoryAllocation","IS"], [0x2000,0x0062,"ColorImagePrintingFlag","CS"], [0x2000,0x0063,"CollationFlag","CS"], [0x2000,0x0065,"AnnotationFlag","CS"], [0x2000,0x0067,"ImageOverlayFlag","CS"], [0x2000,0x0069,"PresentationLUTFlag","CS"], [0x2000,0x006A,"ImageBoxPresentationLUTFlag","CS"], [0x2000,0x00A0,"MemoryBitDepth","US"], [0x2000,0x00A1,"PrintingBitDepth","US"], [0x2000,0x00A2,"MediaInstalledSequence","SQ"], [0x2000,0x00A4,"OtherMediaAvailableSequence","SQ"], [0x2000,0x00A8,"SupportedImageDisplayFormatsSequence","SQ"], [0x2000,0x0500,"ReferencedFilmBoxSequence","SQ"], [0x2000,0x0510,"ReferencedStoredPrintSequence","SQ"], [0x2010,0x0010,"ImageDisplayFormat","ST"], [0x2010,0x0030,"AnnotationDisplayFormatID","CS"], [0x2010,0x0040,"FilmOrientation","CS"], [0x2010,0x0050,"FilmSizeID","CS"], [0x2010,0x0052,"PrinterResolutionID","CS"], [0x2010,0x0054,"DefaultPrinterResolutionID","CS"], [0x2010,0x0060,"MagnificationType","CS"], [0x2010,0x0080,"SmoothingType","CS"], [0x2010,0x00A6,"DefaultMagnificationType","CS"], [0x2010,0x00A7,"OtherMagnificationTypesAvailable","CS"], [0x2010,0x00A8,"DefaultSmoothingType","CS"], [0x2010,0x00A9,"OtherSmoothingTypesAvailable","CS"], [0x2010,0x0100,"BorderDensity","CS"], [0x2010,0x0110,"EmptyImageDensity","CS"], [0x2010,0x0120,"MinDensity","US"], [0x2010,0x0130,"MaxDensity","US"], [0x2010,0x0140,"Trim","CS"], [0x2010,0x0150,"ConfigurationInformation","ST"], [0x2010,0x0152,"ConfigurationInformationDescription","LT"], [0x2010,0x0154,"MaximumCollatedFilms","IS"], [0x2010,0x015E,"Illumination","US"], [0x2010,0x0160,"ReflectedAmbientLight","US"], [0x2010,0x0376,"PrinterPixelSpacing","DS"], [0x2010,0x0500,"ReferencedFilmSessionSequence","SQ"], [0x2010,0x0510,"ReferencedImageBoxSequence","SQ"], [0x2010,0x0520,"ReferencedBasicAnnotationBoxSequence","SQ"], [0x2020,0x0010,"ImageBoxPosition","US"], [0x2020,0x0020,"Polarity","CS"], [0x2020,0x0030,"RequestedImageSize","DS"], [0x2020,0x0040,"RequestedDecimateCropBehavior","CS"], [0x2020,0x0050,"RequestedResolutionID","CS"], [0x2020,0x00A0,"RequestedImageSizeFlag","CS"], [0x2020,0x00A2,"DecimateCropResult","CS"], [0x2020,0x0110,"BasicGrayscaleImageSequence","SQ"], [0x2020,0x0111,"BasicColorImageSequence","SQ"], [0x2020,0x0130,"ReferencedImageOverlayBoxSequence","SQ"], [0x2020,0x0140,"ReferencedVOILUTBoxSequence","SQ"], [0x2030,0x0010,"AnnotationPosition","US"], [0x2030,0x0020,"TextString","LO"], [0x2040,0x0010,"ReferencedOverlayPlaneSequence","SQ"], [0x2040,0x0011,"ReferencedOverlayPlaneGroups","US"], [0x2040,0x0020,"OverlayPixelDataSequence","SQ"], [0x2040,0x0060,"OverlayMagnificationType","CS"], [0x2040,0x0070,"OverlaySmoothingType","CS"], [0x2040,0x0072,"OverlayOrImageMagnification","CS"], [0x2040,0x0074,"MagnifyToNumberOfColumns","US"], [0x2040,0x0080,"OverlayForegroundDensity","CS"], [0x2040,0x0082,"OverlayBackgroundDensity","CS"], [0x2040,0x0090,"OverlayMode","CS"], [0x2040,0x0100,"ThresholdDensity","CS"], [0x2040,0x0500,"ReferencedImageBoxSequenceRetired","SQ"], [0x2050,0x0010,"PresentationLUTSequence","SQ"], [0x2050,0x0020,"PresentationLUTShape","CS"], [0x2050,0x0500,"ReferencedPresentationLUTSequence","SQ"], [0x2100,0x0010,"PrintJobID","SH"], [0x2100,0x0020,"ExecutionStatus","CS"], [0x2100,0x0030,"ExecutionStatusInfo","CS"], [0x2100,0x0040,"CreationDate","DA"], [0x2100,0x0050,"CreationTime","TM"], [0x2100,0x0070,"Originator","AE"], [0x2100,0x0140,"DestinationAE","AE"], [0x2100,0x0160,"OwnerID","SH"], [0x2100,0x0170,"NumberOfFilms","IS"], [0x2100,0x0500,"ReferencedPrintJobSequencePullStoredPrint","SQ"], [0x2110,0x0010,"PrinterStatus","CS"], [0x2110,0x0020,"PrinterStatusInfo","CS"], [0x2110,0x0030,"PrinterName","LO"], [0x2110,0x0099,"PrintQueueID","SH"], [0x2120,0x0010,"QueueStatus","CS"], [0x2120,0x0050,"PrintJobDescriptionSequence","SQ"], [0x2120,0x0070,"ReferencedPrintJobSequence","SQ"], [0x2130,0x0010,"PrintManagementCapabilitiesSequence","SQ"], [0x2130,0x0015,"PrinterCharacteristicsSequence","SQ"], [0x2130,0x0030,"FilmBoxContentSequence","SQ"], [0x2130,0x0040,"ImageBoxContentSequence","SQ"], [0x2130,0x0050,"AnnotationContentSequence","SQ"], [0x2130,0x0060,"ImageOverlayBoxContentSequence","SQ"], [0x2130,0x0080,"PresentationLUTContentSequence","SQ"], [0x2130,0x00A0,"ProposedStudySequence","SQ"], [0x2130,0x00C0,"OriginalImageSequence","SQ"], [0x2200,0x0001,"LabelUsingInformationExtractedFromInstances","CS"], [0x2200,0x0002,"LabelText","UT"], [0x2200,0x0003,"LabelStyleSelection","CS"], [0x2200,0x0004,"MediaDisposition","LT"], [0x2200,0x0005,"BarcodeValue","LT"], [0x2200,0x0006,"BarcodeSymbology","CS"], [0x2200,0x0007,"AllowMediaSplitting","CS"], [0x2200,0x0008,"IncludeNonDICOMObjects","CS"], [0x2200,0x0009,"IncludeDisplayApplication","CS"], [0x2200,0x000A,"PreserveCompositeInstancesAfterMediaCreation","CS"], [0x2200,0x000B,"TotalNumberOfPiecesOfMediaCreated","US"], [0x2200,0x000C,"RequestedMediaApplicationProfile","LO"], [0x2200,0x000D,"ReferencedStorageMediaSequence","SQ"], [0x2200,0x000E,"FailureAttributes","AT"], [0x2200,0x000F,"AllowLossyCompression","CS"], [0x2200,0x0020,"RequestPriority","CS"], [0x3002,0x0002,"RTImageLabel","SH"], [0x3002,0x0003,"RTImageName","LO"], [0x3002,0x0004,"RTImageDescription","ST"], [0x3002,0x000A,"ReportedValuesOrigin","CS"], [0x3002,0x000C,"RTImagePlane","CS"], [0x3002,0x000D,"XRayImageReceptorTranslation","DS"], [0x3002,0x000E,"XRayImageReceptorAngle","DS"], [0x3002,0x0010,"RTImageOrientation","DS"], [0x3002,0x0011,"ImagePlanePixelSpacing","DS"], [0x3002,0x0012,"RTImagePosition","DS"], [0x3002,0x0020,"RadiationMachineName","SH"], [0x3002,0x0022,"RadiationMachineSAD","DS"], [0x3002,0x0024,"RadiationMachineSSD","DS"], [0x3002,0x0026,"RTImageSID","DS"], [0x3002,0x0028,"SourceToReferenceObjectDistance","DS"], [0x3002,0x0029,"FractionNumber","IS"], [0x3002,0x0030,"ExposureSequence","SQ"], [0x3002,0x0032,"MetersetExposure","DS"], [0x3002,0x0034,"DiaphragmPosition","DS"], [0x3002,0x0040,"FluenceMapSequence","SQ"], [0x3002,0x0041,"FluenceDataSource","CS"], [0x3002,0x0042,"FluenceDataScale","DS"], [0x3002,0x0050,"PrimaryFluenceModeSequence","SQ"], [0x3002,0x0051,"FluenceMode","CS"], [0x3002,0x0052,"FluenceModeID","SH"], [0x3004,0x0001,"DVHType","CS"], [0x3004,0x0002,"DoseUnits","CS"], [0x3004,0x0004,"DoseType","CS"], [0x3004,0x0006,"DoseComment","LO"], [0x3004,0x0008,"NormalizationPoint","DS"], [0x3004,0x000A,"DoseSummationType","CS"], [0x3004,0x000C,"GridFrameOffsetVector","DS"], [0x3004,0x000E,"DoseGridScaling","DS"], [0x3004,0x0010,"RTDoseROISequence","SQ"], [0x3004,0x0012,"DoseValue","DS"], [0x3004,0x0014,"TissueHeterogeneityCorrection","CS"], [0x3004,0x0040,"DVHNormalizationPoint","DS"], [0x3004,0x0042,"DVHNormalizationDoseValue","DS"], [0x3004,0x0050,"DVHSequence","SQ"], [0x3004,0x0052,"DVHDoseScaling","DS"], [0x3004,0x0054,"DVHVolumeUnits","CS"], [0x3004,0x0056,"DVHNumberOfBins","IS"], [0x3004,0x0058,"DVHData","DS"], [0x3004,0x0060,"DVHReferencedROISequence","SQ"], [0x3004,0x0062,"DVHROIContributionType","CS"], [0x3004,0x0070,"DVHMinimumDose","DS"], [0x3004,0x0072,"DVHMaximumDose","DS"], [0x3004,0x0074,"DVHMeanDose","DS"], [0x3006,0x0002,"StructureSetLabel","SH"], [0x3006,0x0004,"StructureSetName","LO"], [0x3006,0x0006,"StructureSetDescription","ST"], [0x3006,0x0008,"StructureSetDate","DA"], [0x3006,0x0009,"StructureSetTime","TM"], [0x3006,0x0010,"ReferencedFrameOfReferenceSequence","SQ"], [0x3006,0x0012,"RTReferencedStudySequence","SQ"], [0x3006,0x0014,"RTReferencedSeriesSequence","SQ"], [0x3006,0x0016,"ContourImageSequence","SQ"], [0x3006,0x0020,"StructureSetROISequence","SQ"], [0x3006,0x0022,"ROINumber","IS"], [0x3006,0x0024,"ReferencedFrameOfReferenceUID","UI"], [0x3006,0x0026,"ROIName","LO"], [0x3006,0x0028,"ROIDescription","ST"], [0x3006,0x002A,"ROIDisplayColor","IS"], [0x3006,0x002C,"ROIVolume","DS"], [0x3006,0x0030,"RTRelatedROISequence","SQ"], [0x3006,0x0033,"RTROIRelationship","CS"], [0x3006,0x0036,"ROIGenerationAlgorithm","CS"], [0x3006,0x0038,"ROIGenerationDescription","LO"], [0x3006,0x0039,"ROIContourSequence","SQ"], [0x3006,0x0040,"ContourSequence","SQ"], [0x3006,0x0042,"ContourGeometricType","CS"], [0x3006,0x0044,"ContourSlabThickness","DS"], [0x3006,0x0045,"ContourOffsetVector","DS"], [0x3006,0x0046,"NumberOfContourPoints","IS"], [0x3006,0x0048,"ContourNumber","IS"], [0x3006,0x0049,"AttachedContours","IS"], [0x3006,0x0050,"ContourData","DS"], [0x3006,0x0080,"RTROIObservationsSequence","SQ"], [0x3006,0x0082,"ObservationNumber","IS"], [0x3006,0x0084,"ReferencedROINumber","IS"], [0x3006,0x0085,"ROIObservationLabel","SH"], [0x3006,0x0086,"RTROIIdentificationCodeSequence","SQ"], [0x3006,0x0088,"ROIObservationDescription","ST"], [0x3006,0x00A0,"RelatedRTROIObservationsSequence","SQ"], [0x3006,0x00A4,"RTROIInterpretedType","CS"], [0x3006,0x00A6,"ROIInterpreter","PN"], [0x3006,0x00B0,"ROIPhysicalPropertiesSequence","SQ"], [0x3006,0x00B2,"ROIPhysicalProperty","CS"], [0x3006,0x00B4,"ROIPhysicalPropertyValue","DS"], [0x3006,0x00B6,"ROIElementalCompositionSequence","SQ"], [0x3006,0x00B7,"ROIElementalCompositionAtomicNumber","US"], [0x3006,0x00B8,"ROIElementalCompositionAtomicMassFraction","FL"], [0x3006,0x00C0,"FrameOfReferenceRelationshipSequence","SQ"], [0x3006,0x00C2,"RelatedFrameOfReferenceUID","UI"], [0x3006,0x00C4,"FrameOfReferenceTransformationType","CS"], [0x3006,0x00C6,"FrameOfReferenceTransformationMatrix","DS"], [0x3006,0x00C8,"FrameOfReferenceTransformationComment","LO"], [0x3008,0x0010,"MeasuredDoseReferenceSequence","SQ"], [0x3008,0x0012,"MeasuredDoseDescription","ST"], [0x3008,0x0014,"MeasuredDoseType","CS"], [0x3008,0x0016,"MeasuredDoseValue","DS"], [0x3008,0x0020,"TreatmentSessionBeamSequence","SQ"], [0x3008,0x0021,"TreatmentSessionIonBeamSequence","SQ"], [0x3008,0x0022,"CurrentFractionNumber","IS"], [0x3008,0x0024,"TreatmentControlPointDate","DA"], [0x3008,0x0025,"TreatmentControlPointTime","TM"], [0x3008,0x002A,"TreatmentTerminationStatus","CS"], [0x3008,0x002B,"TreatmentTerminationCode","SH"], [0x3008,0x002C,"TreatmentVerificationStatus","CS"], [0x3008,0x0030,"ReferencedTreatmentRecordSequence","SQ"], [0x3008,0x0032,"SpecifiedPrimaryMeterset","DS"], [0x3008,0x0033,"SpecifiedSecondaryMeterset","DS"], [0x3008,0x0036,"DeliveredPrimaryMeterset","DS"], [0x3008,0x0037,"DeliveredSecondaryMeterset","DS"], [0x3008,0x003A,"SpecifiedTreatmentTime","DS"], [0x3008,0x003B,"DeliveredTreatmentTime","DS"], [0x3008,0x0040,"ControlPointDeliverySequence","SQ"], [0x3008,0x0041,"IonControlPointDeliverySequence","SQ"], [0x3008,0x0042,"SpecifiedMeterset","DS"], [0x3008,0x0044,"DeliveredMeterset","DS"], [0x3008,0x0045,"MetersetRateSet","FL"], [0x3008,0x0046,"MetersetRateDelivered","FL"], [0x3008,0x0047,"ScanSpotMetersetsDelivered","FL"], [0x3008,0x0048,"DoseRateDelivered","DS"], [0x3008,0x0050,"TreatmentSummaryCalculatedDoseReferenceSequence","SQ"], [0x3008,0x0052,"CumulativeDoseToDoseReference","DS"], [0x3008,0x0054,"FirstTreatmentDate","DA"], [0x3008,0x0056,"MostRecentTreatmentDate","DA"], [0x3008,0x005A,"NumberOfFractionsDelivered","IS"], [0x3008,0x0060,"OverrideSequence","SQ"], [0x3008,0x0061,"ParameterSequencePointer","AT"], [0x3008,0x0062,"OverrideParameterPointer","AT"], [0x3008,0x0063,"ParameterItemIndex","IS"], [0x3008,0x0064,"MeasuredDoseReferenceNumber","IS"], [0x3008,0x0065,"ParameterPointer","AT"], [0x3008,0x0066,"OverrideReason","ST"], [0x3008,0x0068,"CorrectedParameterSequence","SQ"], [0x3008,0x006A,"CorrectionValue","FL"], [0x3008,0x0070,"CalculatedDoseReferenceSequence","SQ"], [0x3008,0x0072,"CalculatedDoseReferenceNumber","IS"], [0x3008,0x0074,"CalculatedDoseReferenceDescription","ST"], [0x3008,0x0076,"CalculatedDoseReferenceDoseValue","DS"], [0x3008,0x0078,"StartMeterset","DS"], [0x3008,0x007A,"EndMeterset","DS"], [0x3008,0x0080,"ReferencedMeasuredDoseReferenceSequence","SQ"], [0x3008,0x0082,"ReferencedMeasuredDoseReferenceNumber","IS"], [0x3008,0x0090,"ReferencedCalculatedDoseReferenceSequence","SQ"], [0x3008,0x0092,"ReferencedCalculatedDoseReferenceNumber","IS"], [0x3008,0x00A0,"BeamLimitingDeviceLeafPairsSequence","SQ"], [0x3008,0x00B0,"RecordedWedgeSequence","SQ"], [0x3008,0x00C0,"RecordedCompensatorSequence","SQ"], [0x3008,0x00D0,"RecordedBlockSequence","SQ"], [0x3008,0x00E0,"TreatmentSummaryMeasuredDoseReferenceSequence","SQ"], [0x3008,0x00F0,"RecordedSnoutSequence","SQ"], [0x3008,0x00F2,"RecordedRangeShifterSequence","SQ"], [0x3008,0x00F4,"RecordedLateralSpreadingDeviceSequence","SQ"], [0x3008,0x00F6,"RecordedRangeModulatorSequence","SQ"], [0x3008,0x0100,"RecordedSourceSequence","SQ"], [0x3008,0x0105,"SourceSerialNumber","LO"], [0x3008,0x0110,"TreatmentSessionApplicationSetupSequence","SQ"], [0x3008,0x0116,"ApplicationSetupCheck","CS"], [0x3008,0x0120,"RecordedBrachyAccessoryDeviceSequence","SQ"], [0x3008,0x0122,"ReferencedBrachyAccessoryDeviceNumber","IS"], [0x3008,0x0130,"RecordedChannelSequence","SQ"], [0x3008,0x0132,"SpecifiedChannelTotalTime","DS"], [0x3008,0x0134,"DeliveredChannelTotalTime","DS"], [0x3008,0x0136,"SpecifiedNumberOfPulses","IS"], [0x3008,0x0138,"DeliveredNumberOfPulses","IS"], [0x3008,0x013A,"SpecifiedPulseRepetitionInterval","DS"], [0x3008,0x013C,"DeliveredPulseRepetitionInterval","DS"], [0x3008,0x0140,"RecordedSourceApplicatorSequence","SQ"], [0x3008,0x0142,"ReferencedSourceApplicatorNumber","IS"], [0x3008,0x0150,"RecordedChannelShieldSequence","SQ"], [0x3008,0x0152,"ReferencedChannelShieldNumber","IS"], [0x3008,0x0160,"BrachyControlPointDeliveredSequence","SQ"], [0x3008,0x0162,"SafePositionExitDate","DA"], [0x3008,0x0164,"SafePositionExitTime","TM"], [0x3008,0x0166,"SafePositionReturnDate","DA"], [0x3008,0x0168,"SafePositionReturnTime","TM"], [0x3008,0x0200,"CurrentTreatmentStatus","CS"], [0x3008,0x0202,"TreatmentStatusComment","ST"], [0x3008,0x0220,"FractionGroupSummarySequence","SQ"], [0x3008,0x0223,"ReferencedFractionNumber","IS"], [0x3008,0x0224,"FractionGroupType","CS"], [0x3008,0x0230,"BeamStopperPosition","CS"], [0x3008,0x0240,"FractionStatusSummarySequence","SQ"], [0x3008,0x0250,"TreatmentDate","DA"], [0x3008,0x0251,"TreatmentTime","TM"], [0x300A,0x0002,"RTPlanLabel","SH"], [0x300A,0x0003,"RTPlanName","LO"], [0x300A,0x0004,"RTPlanDescription","ST"], [0x300A,0x0006,"RTPlanDate","DA"], [0x300A,0x0007,"RTPlanTime","TM"], [0x300A,0x0009,"TreatmentProtocols","LO"], [0x300A,0x000A,"PlanIntent","CS"], [0x300A,0x000B,"TreatmentSites","LO"], [0x300A,0x000C,"RTPlanGeometry","CS"], [0x300A,0x000E,"PrescriptionDescription","ST"], [0x300A,0x0010,"DoseReferenceSequence","SQ"], [0x300A,0x0012,"DoseReferenceNumber","IS"], [0x300A,0x0013,"DoseReferenceUID","UI"], [0x300A,0x0014,"DoseReferenceStructureType","CS"], [0x300A,0x0015,"NominalBeamEnergyUnit","CS"], [0x300A,0x0016,"DoseReferenceDescription","LO"], [0x300A,0x0018,"DoseReferencePointCoordinates","DS"], [0x300A,0x001A,"NominalPriorDose","DS"], [0x300A,0x0020,"DoseReferenceType","CS"], [0x300A,0x0021,"ConstraintWeight","DS"], [0x300A,0x0022,"DeliveryWarningDose","DS"], [0x300A,0x0023,"DeliveryMaximumDose","DS"], [0x300A,0x0025,"TargetMinimumDose","DS"], [0x300A,0x0026,"TargetPrescriptionDose","DS"], [0x300A,0x0027,"TargetMaximumDose","DS"], [0x300A,0x0028,"TargetUnderdoseVolumeFraction","DS"], [0x300A,0x002A,"OrganAtRiskFullVolumeDose","DS"], [0x300A,0x002B,"OrganAtRiskLimitDose","DS"], [0x300A,0x002C,"OrganAtRiskMaximumDose","DS"], [0x300A,0x002D,"OrganAtRiskOverdoseVolumeFraction","DS"], [0x300A,0x0040,"ToleranceTableSequence","SQ"], [0x300A,0x0042,"ToleranceTableNumber","IS"], [0x300A,0x0043,"ToleranceTableLabel","SH"], [0x300A,0x0044,"GantryAngleTolerance","DS"], [0x300A,0x0046,"BeamLimitingDeviceAngleTolerance","DS"], [0x300A,0x0048,"BeamLimitingDeviceToleranceSequence","SQ"], [0x300A,0x004A,"BeamLimitingDevicePositionTolerance","DS"], [0x300A,0x004B,"SnoutPositionTolerance","FL"], [0x300A,0x004C,"PatientSupportAngleTolerance","DS"], [0x300A,0x004E,"TableTopEccentricAngleTolerance","DS"], [0x300A,0x004F,"TableTopPitchAngleTolerance","FL"], [0x300A,0x0050,"TableTopRollAngleTolerance","FL"], [0x300A,0x0051,"TableTopVerticalPositionTolerance","DS"], [0x300A,0x0052,"TableTopLongitudinalPositionTolerance","DS"], [0x300A,0x0053,"TableTopLateralPositionTolerance","DS"], [0x300A,0x0055,"RTPlanRelationship","CS"], [0x300A,0x0070,"FractionGroupSequence","SQ"], [0x300A,0x0071,"FractionGroupNumber","IS"], [0x300A,0x0072,"FractionGroupDescription","LO"], [0x300A,0x0078,"NumberOfFractionsPlanned","IS"], [0x300A,0x0079,"NumberOfFractionPatternDigitsPerDay","IS"], [0x300A,0x007A,"RepeatFractionCycleLength","IS"], [0x300A,0x007B,"FractionPattern","LT"], [0x300A,0x0080,"NumberOfBeams","IS"], [0x300A,0x0082,"BeamDoseSpecificationPoint","DS"], [0x300A,0x0084,"BeamDose","DS"], [0x300A,0x0086,"BeamMeterset","DS"], [0x300A,0x0088,"BeamDosePointDepth","FL"], [0x300A,0x0089,"BeamDosePointEquivalentDepth","FL"], [0x300A,0x008A,"BeamDosePointSSD","FL"], [0x300A,0x00A0,"NumberOfBrachyApplicationSetups","IS"], [0x300A,0x00A2,"BrachyApplicationSetupDoseSpecificationPoint","DS"], [0x300A,0x00A4,"BrachyApplicationSetupDose","DS"], [0x300A,0x00B0,"BeamSequence","SQ"], [0x300A,0x00B2,"TreatmentMachineName","SH"], [0x300A,0x00B3,"PrimaryDosimeterUnit","CS"], [0x300A,0x00B4,"SourceAxisDistance","DS"], [0x300A,0x00B6,"BeamLimitingDeviceSequence","SQ"], [0x300A,0x00B8,"RTBeamLimitingDeviceType","CS"], [0x300A,0x00BA,"SourceToBeamLimitingDeviceDistance","DS"], [0x300A,0x00BB,"IsocenterToBeamLimitingDeviceDistance","FL"], [0x300A,0x00BC,"NumberOfLeafJawPairs","IS"], [0x300A,0x00BE,"LeafPositionBoundaries","DS"], [0x300A,0x00C0,"BeamNumber","IS"], [0x300A,0x00C2,"BeamName","LO"], [0x300A,0x00C3,"BeamDescription","ST"], [0x300A,0x00C4,"BeamType","CS"], [0x300A,0x00C6,"RadiationType","CS"], [0x300A,0x00C7,"HighDoseTechniqueType","CS"], [0x300A,0x00C8,"ReferenceImageNumber","IS"], [0x300A,0x00CA,"PlannedVerificationImageSequence","SQ"], [0x300A,0x00CC,"ImagingDeviceSpecificAcquisitionParameters","LO"], [0x300A,0x00CE,"TreatmentDeliveryType","CS"], [0x300A,0x00D0,"NumberOfWedges","IS"], [0x300A,0x00D1,"WedgeSequence","SQ"], [0x300A,0x00D2,"WedgeNumber","IS"], [0x300A,0x00D3,"WedgeType","CS"], [0x300A,0x00D4,"WedgeID","SH"], [0x300A,0x00D5,"WedgeAngle","IS"], [0x300A,0x00D6,"WedgeFactor","DS"], [0x300A,0x00D7,"TotalWedgeTrayWaterEquivalentThickness","FL"], [0x300A,0x00D8,"WedgeOrientation","DS"], [0x300A,0x00D9,"IsocenterToWedgeTrayDistance","FL"], [0x300A,0x00DA,"SourceToWedgeTrayDistance","DS"], [0x300A,0x00DB,"WedgeThinEdgePosition","FL"], [0x300A,0x00DC,"BolusID","SH"], [0x300A,0x00DD,"BolusDescription","ST"], [0x300A,0x00E0,"NumberOfCompensators","IS"], [0x300A,0x00E1,"MaterialID","SH"], [0x300A,0x00E2,"TotalCompensatorTrayFactor","DS"], [0x300A,0x00E3,"CompensatorSequence","SQ"], [0x300A,0x00E4,"CompensatorNumber","IS"], [0x300A,0x00E5,"CompensatorID","SH"], [0x300A,0x00E6,"SourceToCompensatorTrayDistance","DS"], [0x300A,0x00E7,"CompensatorRows","IS"], [0x300A,0x00E8,"CompensatorColumns","IS"], [0x300A,0x00E9,"CompensatorPixelSpacing","DS"], [0x300A,0x00EA,"CompensatorPosition","DS"], [0x300A,0x00EB,"CompensatorTransmissionData","DS"], [0x300A,0x00EC,"CompensatorThicknessData","DS"], [0x300A,0x00ED,"NumberOfBoli","IS"], [0x300A,0x00EE,"CompensatorType","CS"], [0x300A,0x00F0,"NumberOfBlocks","IS"], [0x300A,0x00F2,"TotalBlockTrayFactor","DS"], [0x300A,0x00F3,"TotalBlockTrayWaterEquivalentThickness","FL"], [0x300A,0x00F4,"BlockSequence","SQ"], [0x300A,0x00F5,"BlockTrayID","SH"], [0x300A,0x00F6,"SourceToBlockTrayDistance","DS"], [0x300A,0x00F7,"IsocenterToBlockTrayDistance","FL"], [0x300A,0x00F8,"BlockType","CS"], [0x300A,0x00F9,"AccessoryCode","LO"], [0x300A,0x00FA,"BlockDivergence","CS"], [0x300A,0x00FB,"BlockMountingPosition","CS"], [0x300A,0x00FC,"BlockNumber","IS"], [0x300A,0x00FE,"BlockName","LO"], [0x300A,0x0100,"BlockThickness","DS"], [0x300A,0x0102,"BlockTransmission","DS"], [0x300A,0x0104,"BlockNumberOfPoints","IS"], [0x300A,0x0106,"BlockData","DS"], [0x300A,0x0107,"ApplicatorSequence","SQ"], [0x300A,0x0108,"ApplicatorID","SH"], [0x300A,0x0109,"ApplicatorType","CS"], [0x300A,0x010A,"ApplicatorDescription","LO"], [0x300A,0x010C,"CumulativeDoseReferenceCoefficient","DS"], [0x300A,0x010E,"FinalCumulativeMetersetWeight","DS"], [0x300A,0x0110,"NumberOfControlPoints","IS"], [0x300A,0x0111,"ControlPointSequence","SQ"], [0x300A,0x0112,"ControlPointIndex","IS"], [0x300A,0x0114,"NominalBeamEnergy","DS"], [0x300A,0x0115,"DoseRateSet","DS"], [0x300A,0x0116,"WedgePositionSequence","SQ"], [0x300A,0x0118,"WedgePosition","CS"], [0x300A,0x011A,"BeamLimitingDevicePositionSequence","SQ"], [0x300A,0x011C,"LeafJawPositions","DS"], [0x300A,0x011E,"GantryAngle","DS"], [0x300A,0x011F,"GantryRotationDirection","CS"], [0x300A,0x0120,"BeamLimitingDeviceAngle","DS"], [0x300A,0x0121,"BeamLimitingDeviceRotationDirection","CS"], [0x300A,0x0122,"PatientSupportAngle","DS"], [0x300A,0x0123,"PatientSupportRotationDirection","CS"], [0x300A,0x0124,"TableTopEccentricAxisDistance","DS"], [0x300A,0x0125,"TableTopEccentricAngle","DS"], [0x300A,0x0126,"TableTopEccentricRotationDirection","CS"], [0x300A,0x0128,"TableTopVerticalPosition","DS"], [0x300A,0x0129,"TableTopLongitudinalPosition","DS"], [0x300A,0x012A,"TableTopLateralPosition","DS"], [0x300A,0x012C,"IsocenterPosition","DS"], [0x300A,0x012E,"SurfaceEntryPoint","DS"], [0x300A,0x0130,"SourceToSurfaceDistance","DS"], [0x300A,0x0134,"CumulativeMetersetWeight","DS"], [0x300A,0x0140,"TableTopPitchAngle","FL"], [0x300A,0x0142,"TableTopPitchRotationDirection","CS"], [0x300A,0x0144,"TableTopRollAngle","FL"], [0x300A,0x0146,"TableTopRollRotationDirection","CS"], [0x300A,0x0148,"HeadFixationAngle","FL"], [0x300A,0x014A,"GantryPitchAngle","FL"], [0x300A,0x014C,"GantryPitchRotationDirection","CS"], [0x300A,0x014E,"GantryPitchAngleTolerance","FL"], [0x300A,0x0180,"PatientSetupSequence","SQ"], [0x300A,0x0182,"PatientSetupNumber","IS"], [0x300A,0x0183,"PatientSetupLabel","LO"], [0x300A,0x0184,"PatientAdditionalPosition","LO"], [0x300A,0x0190,"FixationDeviceSequence","SQ"], [0x300A,0x0192,"FixationDeviceType","CS"], [0x300A,0x0194,"FixationDeviceLabel","SH"], [0x300A,0x0196,"FixationDeviceDescription","ST"], [0x300A,0x0198,"FixationDevicePosition","SH"], [0x300A,0x0199,"FixationDevicePitchAngle","FL"], [0x300A,0x019A,"FixationDeviceRollAngle","FL"], [0x300A,0x01A0,"ShieldingDeviceSequence","SQ"], [0x300A,0x01A2,"ShieldingDeviceType","CS"], [0x300A,0x01A4,"ShieldingDeviceLabel","SH"], [0x300A,0x01A6,"ShieldingDeviceDescription","ST"], [0x300A,0x01A8,"ShieldingDevicePosition","SH"], [0x300A,0x01B0,"SetupTechnique","CS"], [0x300A,0x01B2,"SetupTechniqueDescription","ST"], [0x300A,0x01B4,"SetupDeviceSequence","SQ"], [0x300A,0x01B6,"SetupDeviceType","CS"], [0x300A,0x01B8,"SetupDeviceLabel","SH"], [0x300A,0x01BA,"SetupDeviceDescription","ST"], [0x300A,0x01BC,"SetupDeviceParameter","DS"], [0x300A,0x01D0,"SetupReferenceDescription","ST"], [0x300A,0x01D2,"TableTopVerticalSetupDisplacement","DS"], [0x300A,0x01D4,"TableTopLongitudinalSetupDisplacement","DS"], [0x300A,0x01D6,"TableTopLateralSetupDisplacement","DS"], [0x300A,0x0200,"BrachyTreatmentTechnique","CS"], [0x300A,0x0202,"BrachyTreatmentType","CS"], [0x300A,0x0206,"TreatmentMachineSequence","SQ"], [0x300A,0x0210,"SourceSequence","SQ"], [0x300A,0x0212,"SourceNumber","IS"], [0x300A,0x0214,"SourceType","CS"], [0x300A,0x0216,"SourceManufacturer","LO"], [0x300A,0x0218,"ActiveSourceDiameter","DS"], [0x300A,0x021A,"ActiveSourceLength","DS"], [0x300A,0x0222,"SourceEncapsulationNominalThickness","DS"], [0x300A,0x0224,"SourceEncapsulationNominalTransmission","DS"], [0x300A,0x0226,"SourceIsotopeName","LO"], [0x300A,0x0228,"SourceIsotopeHalfLife","DS"], [0x300A,0x0229,"SourceStrengthUnits","CS"], [0x300A,0x022A,"ReferenceAirKermaRate","DS"], [0x300A,0x022B,"SourceStrength","DS"], [0x300A,0x022C,"SourceStrengthReferenceDate","DA"], [0x300A,0x022E,"SourceStrengthReferenceTime","TM"], [0x300A,0x0230,"ApplicationSetupSequence","SQ"], [0x300A,0x0232,"ApplicationSetupType","CS"], [0x300A,0x0234,"ApplicationSetupNumber","IS"], [0x300A,0x0236,"ApplicationSetupName","LO"], [0x300A,0x0238,"ApplicationSetupManufacturer","LO"], [0x300A,0x0240,"TemplateNumber","IS"], [0x300A,0x0242,"TemplateType","SH"], [0x300A,0x0244,"TemplateName","LO"], [0x300A,0x0250,"TotalReferenceAirKerma","DS"], [0x300A,0x0260,"BrachyAccessoryDeviceSequence","SQ"], [0x300A,0x0262,"BrachyAccessoryDeviceNumber","IS"], [0x300A,0x0263,"BrachyAccessoryDeviceID","SH"], [0x300A,0x0264,"BrachyAccessoryDeviceType","CS"], [0x300A,0x0266,"BrachyAccessoryDeviceName","LO"], [0x300A,0x026A,"BrachyAccessoryDeviceNominalThickness","DS"], [0x300A,0x026C,"BrachyAccessoryDeviceNominalTransmission","DS"], [0x300A,0x0280,"ChannelSequence","SQ"], [0x300A,0x0282,"ChannelNumber","IS"], [0x300A,0x0284,"ChannelLength","DS"], [0x300A,0x0286,"ChannelTotalTime","DS"], [0x300A,0x0288,"SourceMovementType","CS"], [0x300A,0x028A,"NumberOfPulses","IS"], [0x300A,0x028C,"PulseRepetitionInterval","DS"], [0x300A,0x0290,"SourceApplicatorNumber","IS"], [0x300A,0x0291,"SourceApplicatorID","SH"], [0x300A,0x0292,"SourceApplicatorType","CS"], [0x300A,0x0294,"SourceApplicatorName","LO"], [0x300A,0x0296,"SourceApplicatorLength","DS"], [0x300A,0x0298,"SourceApplicatorManufacturer","LO"], [0x300A,0x029C,"SourceApplicatorWallNominalThickness","DS"], [0x300A,0x029E,"SourceApplicatorWallNominalTransmission","DS"], [0x300A,0x02A0,"SourceApplicatorStepSize","DS"], [0x300A,0x02A2,"TransferTubeNumber","IS"], [0x300A,0x02A4,"TransferTubeLength","DS"], [0x300A,0x02B0,"ChannelShieldSequence","SQ"], [0x300A,0x02B2,"ChannelShieldNumber","IS"], [0x300A,0x02B3,"ChannelShieldID","SH"], [0x300A,0x02B4,"ChannelShieldName","LO"], [0x300A,0x02B8,"ChannelShieldNominalThickness","DS"], [0x300A,0x02BA,"ChannelShieldNominalTransmission","DS"], [0x300A,0x02C8,"FinalCumulativeTimeWeight","DS"], [0x300A,0x02D0,"BrachyControlPointSequence","SQ"], [0x300A,0x02D2,"ControlPointRelativePosition","DS"], [0x300A,0x02D4,"ControlPoint3DPosition","DS"], [0x300A,0x02D6,"CumulativeTimeWeight","DS"], [0x300A,0x02E0,"CompensatorDivergence","CS"], [0x300A,0x02E1,"CompensatorMountingPosition","CS"], [0x300A,0x02E2,"SourceToCompensatorDistance","DS"], [0x300A,0x02E3,"TotalCompensatorTrayWaterEquivalentThickness","FL"], [0x300A,0x02E4,"IsocenterToCompensatorTrayDistance","FL"], [0x300A,0x02E5,"CompensatorColumnOffset","FL"], [0x300A,0x02E6,"IsocenterToCompensatorDistances","FL"], [0x300A,0x02E7,"CompensatorRelativeStoppingPowerRatio","FL"], [0x300A,0x02E8,"CompensatorMillingToolDiameter","FL"], [0x300A,0x02EA,"IonRangeCompensatorSequence","SQ"], [0x300A,0x02EB,"CompensatorDescription","LT"], [0x300A,0x0302,"RadiationMassNumber","IS"], [0x300A,0x0304,"RadiationAtomicNumber","IS"], [0x300A,0x0306,"RadiationChargeState","SS"], [0x300A,0x0308,"ScanMode","CS"], [0x300A,0x030A,"VirtualSourceAxisDistances","FL"], [0x300A,0x030C,"SnoutSequence","SQ"], [0x300A,0x030D,"SnoutPosition","FL"], [0x300A,0x030F,"SnoutID","SH"], [0x300A,0x0312,"NumberOfRangeShifters","IS"], [0x300A,0x0314,"RangeShifterSequence","SQ"], [0x300A,0x0316,"RangeShifterNumber","IS"], [0x300A,0x0318,"RangeShifterID","SH"], [0x300A,0x0320,"RangeShifterType","CS"], [0x300A,0x0322,"RangeShifterDescription","LO"], [0x300A,0x0330,"NumberOfLateralSpreadingDevices","IS"], [0x300A,0x0332,"LateralSpreadingDeviceSequence","SQ"], [0x300A,0x0334,"LateralSpreadingDeviceNumber","IS"], [0x300A,0x0336,"LateralSpreadingDeviceID","SH"], [0x300A,0x0338,"LateralSpreadingDeviceType","CS"], [0x300A,0x033A,"LateralSpreadingDeviceDescription","LO"], [0x300A,0x033C,"LateralSpreadingDeviceWaterEquivalentThickness","FL"], [0x300A,0x0340,"NumberOfRangeModulators","IS"], [0x300A,0x0342,"RangeModulatorSequence","SQ"], [0x300A,0x0344,"RangeModulatorNumber","IS"], [0x300A,0x0346,"RangeModulatorID","SH"], [0x300A,0x0348,"RangeModulatorType","CS"], [0x300A,0x034A,"RangeModulatorDescription","LO"], [0x300A,0x034C,"BeamCurrentModulationID","SH"], [0x300A,0x0350,"PatientSupportType","CS"], [0x300A,0x0352,"PatientSupportID","SH"], [0x300A,0x0354,"PatientSupportAccessoryCode","LO"], [0x300A,0x0356,"FixationLightAzimuthalAngle","FL"], [0x300A,0x0358,"FixationLightPolarAngle","FL"], [0x300A,0x035A,"MetersetRate","FL"], [0x300A,0x0360,"RangeShifterSettingsSequence","SQ"], [0x300A,0x0362,"RangeShifterSetting","LO"], [0x300A,0x0364,"IsocenterToRangeShifterDistance","FL"], [0x300A,0x0366,"RangeShifterWaterEquivalentThickness","FL"], [0x300A,0x0370,"LateralSpreadingDeviceSettingsSequence","SQ"], [0x300A,0x0372,"LateralSpreadingDeviceSetting","LO"], [0x300A,0x0374,"IsocenterToLateralSpreadingDeviceDistance","FL"], [0x300A,0x0380,"RangeModulatorSettingsSequence","SQ"], [0x300A,0x0382,"RangeModulatorGatingStartValue","FL"], [0x300A,0x0384,"RangeModulatorGatingStopValue","FL"], [0x300A,0x0386,"RangeModulatorGatingStartWaterEquivalentThickness","FL"], [0x300A,0x0388,"RangeModulatorGatingStopWaterEquivalentThickness","FL"], [0x300A,0x038A,"IsocenterToRangeModulatorDistance","FL"], [0x300A,0x0390,"ScanSpotTuneID","SH"], [0x300A,0x0392,"NumberOfScanSpotPositions","IS"], [0x300A,0x0394,"ScanSpotPositionMap","FL"], [0x300A,0x0396,"ScanSpotMetersetWeights","FL"], [0x300A,0x0398,"ScanningSpotSize","FL"], [0x300A,0x039A,"NumberOfPaintings","IS"], [0x300A,0x03A0,"IonToleranceTableSequence","SQ"], [0x300A,0x03A2,"IonBeamSequence","SQ"], [0x300A,0x03A4,"IonBeamLimitingDeviceSequence","SQ"], [0x300A,0x03A6,"IonBlockSequence","SQ"], [0x300A,0x03A8,"IonControlPointSequence","SQ"], [0x300A,0x03AA,"IonWedgeSequence","SQ"], [0x300A,0x03AC,"IonWedgePositionSequence","SQ"], [0x300A,0x0401,"ReferencedSetupImageSequence","SQ"], [0x300A,0x0402,"SetupImageComment","ST"], [0x300A,0x0410,"MotionSynchronizationSequence","SQ"], [0x300A,0x0412,"ControlPointOrientation","FL"], [0x300A,0x0420,"GeneralAccessorySequence","SQ"], [0x300A,0x0421,"GeneralAccessoryID","SH"], [0x300A,0x0422,"GeneralAccessoryDescription","ST"], [0x300A,0x0423,"GeneralAccessoryType","CS"], [0x300A,0x0424,"GeneralAccessoryNumber","IS"], [0x300A,0x0431,"ApplicatorGeometrySequence","SQ"], [0x300A,0x0432,"ApplicatorApertureShape","CS"], [0x300A,0x0433,"ApplicatorOpening","FL"], [0x300A,0x0434,"ApplicatorOpeningX","FL"], [0x300A,0x0435,"ApplicatorOpeningY","FL"], [0x300A,0x0436,"SourceToApplicatorMountingPositionDistance","FL"], [0x300C,0x0002,"ReferencedRTPlanSequence","SQ"], [0x300C,0x0004,"ReferencedBeamSequence","SQ"], [0x300C,0x0006,"ReferencedBeamNumber","IS"], [0x300C,0x0007,"ReferencedReferenceImageNumber","IS"], [0x300C,0x0008,"StartCumulativeMetersetWeight","DS"], [0x300C,0x0009,"EndCumulativeMetersetWeight","DS"], [0x300C,0x000A,"ReferencedBrachyApplicationSetupSequence","SQ"], [0x300C,0x000C,"ReferencedBrachyApplicationSetupNumber","IS"], [0x300C,0x000E,"ReferencedSourceNumber","IS"], [0x300C,0x0020,"ReferencedFractionGroupSequence","SQ"], [0x300C,0x0022,"ReferencedFractionGroupNumber","IS"], [0x300C,0x0040,"ReferencedVerificationImageSequence","SQ"], [0x300C,0x0042,"ReferencedReferenceImageSequence","SQ"], [0x300C,0x0050,"ReferencedDoseReferenceSequence","SQ"], [0x300C,0x0051,"ReferencedDoseReferenceNumber","IS"], [0x300C,0x0055,"BrachyReferencedDoseReferenceSequence","SQ"], [0x300C,0x0060,"ReferencedStructureSetSequence","SQ"], [0x300C,0x006A,"ReferencedPatientSetupNumber","IS"], [0x300C,0x0080,"ReferencedDoseSequence","SQ"], [0x300C,0x00A0,"ReferencedToleranceTableNumber","IS"], [0x300C,0x00B0,"ReferencedBolusSequence","SQ"], [0x300C,0x00C0,"ReferencedWedgeNumber","IS"], [0x300C,0x00D0,"ReferencedCompensatorNumber","IS"], [0x300C,0x00E0,"ReferencedBlockNumber","IS"], [0x300C,0x00F0,"ReferencedControlPointIndex","IS"], [0x300C,0x00F2,"ReferencedControlPointSequence","SQ"], [0x300C,0x00F4,"ReferencedStartControlPointIndex","IS"], [0x300C,0x00F6,"ReferencedStopControlPointIndex","IS"], [0x300C,0x0100,"ReferencedRangeShifterNumber","IS"], [0x300C,0x0102,"ReferencedLateralSpreadingDeviceNumber","IS"], [0x300C,0x0104,"ReferencedRangeModulatorNumber","IS"], [0x300E,0x0002,"ApprovalStatus","CS"], [0x300E,0x0004,"ReviewDate","DA"], [0x300E,0x0005,"ReviewTime","TM"], [0x300E,0x0008,"ReviewerName","PN"], [0x4000,0x0010,"Arbitrary","LT"], [0x4000,0x4000,"TextComments","LT"], [0x4008,0x0040,"ResultsID","SH"], [0x4008,0x0042,"ResultsIDIssuer","LO"], [0x4008,0x0050,"ReferencedInterpretationSequence","SQ"], [0x4008,0x00FF,"ReportProductionStatusTrial","CS"], [0x4008,0x0100,"InterpretationRecordedDate","DA"], [0x4008,0x0101,"InterpretationRecordedTime","TM"], [0x4008,0x0102,"InterpretationRecorder","PN"], [0x4008,0x0103,"ReferenceToRecordedSound","LO"], [0x4008,0x0108,"InterpretationTranscriptionDate","DA"], [0x4008,0x0109,"InterpretationTranscriptionTime","TM"], [0x4008,0x010A,"InterpretationTranscriber","PN"], [0x4008,0x010B,"InterpretationText","ST"], [0x4008,0x010C,"InterpretationAuthor","PN"], [0x4008,0x0111,"InterpretationApproverSequence","SQ"], [0x4008,0x0112,"InterpretationApprovalDate","DA"], [0x4008,0x0113,"InterpretationApprovalTime","TM"], [0x4008,0x0114,"PhysicianApprovingInterpretation","PN"], [0x4008,0x0115,"InterpretationDiagnosisDescription","LT"], [0x4008,0x0117,"InterpretationDiagnosisCodeSequence","SQ"], [0x4008,0x0118,"ResultsDistributionListSequence","SQ"], [0x4008,0x0119,"DistributionName","PN"], [0x4008,0x011A,"DistributionAddress","LO"], [0x4008,0x0200,"InterpretationID","SH"], [0x4008,0x0202,"InterpretationIDIssuer","LO"], [0x4008,0x0210,"InterpretationTypeID","CS"], [0x4008,0x0212,"InterpretationStatusID","CS"], [0x4008,0x0300,"Impressions","ST"], [0x4008,0x4000,"ResultsComments","ST"], [0x4010,0x0001,"LowEnergyDetectors","CS"], [0x4010,0x0002,"HighEnergyDetectors","CS"], [0x4010,0x0004,"DetectorGeometrySequence","SQ"], [0x4010,0x1001,"ThreatROIVoxelSequence","SQ"], [0x4010,0x1004,"ThreatROIBase","FL"], [0x4010,0x1005,"ThreatROIExtents","FL"], [0x4010,0x1006,"ThreatROIBitmap","OB"], [0x4010,0x1007,"RouteSegmentID","SH"], [0x4010,0x1008,"GantryType","CS"], [0x4010,0x1009,"OOIOwnerType","CS"], [0x4010,0x100A,"RouteSegmentSequence","SQ"], [0x4010,0x1010,"PotentialThreatObjectID","US"], [0x4010,0x1011,"ThreatSequence","SQ"], [0x4010,0x1012,"ThreatCategory","CS"], [0x4010,0x1013,"ThreatCategoryDescription","LT"], [0x4010,0x1014,"ATDAbilityAssessment","CS"], [0x4010,0x1015,"ATDAssessmentFlag","CS"], [0x4010,0x1016,"ATDAssessmentProbability","FL"], [0x4010,0x1017,"Mass","FL"], [0x4010,0x1018,"Density","FL"], [0x4010,0x1019,"ZEffective","FL"], [0x4010,0x101A,"BoardingPassID","SH"], [0x4010,0x101B,"CenterOfMass","FL"], [0x4010,0x101C,"CenterOfPTO","FL"], [0x4010,0x101D,"BoundingPolygon","FL"], [0x4010,0x101E,"RouteSegmentStartLocationID","SH"], [0x4010,0x101F,"RouteSegmentEndLocationID","SH"], [0x4010,0x1020,"RouteSegmentLocationIDType","CS"], [0x4010,0x1021,"AbortReason","CS"], [0x4010,0x1023,"VolumeOfPTO","FL"], [0x4010,0x1024,"AbortFlag","CS"], [0x4010,0x1025,"RouteSegmentStartTime","DT"], [0x4010,0x1026,"RouteSegmentEndTime","DT"], [0x4010,0x1027,"TDRType","CS"], [0x4010,0x1028,"InternationalRouteSegment","CS"], [0x4010,0x1029,"ThreatDetectionAlgorithmandVersion","LO"], [0x4010,0x102A,"AssignedLocation","SH"], [0x4010,0x102B,"AlarmDecisionTime","DT"], [0x4010,0x1031,"AlarmDecision","CS"], [0x4010,0x1033,"NumberOfTotalObjects","US"], [0x4010,0x1034,"NumberOfAlarmObjects","US"], [0x4010,0x1037,"PTORepresentationSequence","SQ"], [0x4010,0x1038,"ATDAssessmentSequence","SQ"], [0x4010,0x1039,"TIPType","CS"], [0x4010,0x103A,"DICOSVersion","CS"], [0x4010,0x1041,"OOIOwnerCreationTime","DT"], [0x4010,0x1042,"OOIType","CS"], [0x4010,0x1043,"OOISize","FL"], [0x4010,0x1044,"AcquisitionStatus","CS"], [0x4010,0x1045,"BasisMaterialsCodeSequence","SQ"], [0x4010,0x1046,"PhantomType","CS"], [0x4010,0x1047,"OOIOwnerSequence","SQ"], [0x4010,0x1048,"ScanType","CS"], [0x4010,0x1051,"ItineraryID","LO"], [0x4010,0x1052,"ItineraryIDType","SH"], [0x4010,0x1053,"ItineraryIDAssigningAuthority","LO"], [0x4010,0x1054,"RouteID","SH"], [0x4010,0x1055,"RouteIDAssigningAuthority","SH"], [0x4010,0x1056,"InboundArrivalType","CS"], [0x4010,0x1058,"CarrierID","SH"], [0x4010,0x1059,"CarrierIDAssigningAuthority","CS"], [0x4010,0x1060,"SourceOrientation","FL"], [0x4010,0x1061,"SourcePosition","FL"], [0x4010,0x1062,"BeltHeight","FL"], [0x4010,0x1064,"AlgorithmRoutingCodeSequence","SQ"], [0x4010,0x1067,"TransportClassification","CS"], [0x4010,0x1068,"OOITypeDescriptor","LT"], [0x4010,0x1069,"TotalProcessingTime","FL"], [0x4010,0x106C,"DetectorCalibrationData","OB"] ]; /*** Static Methods ***/ daikon.Dictionary.getVR = function (group, element) { var vr = null, startIndex, ctr, num; startIndex = daikon.Dictionary.GROUP_INDICES[group]; if (!startIndex) { startIndex = daikon.Dictionary.GROUP_INDICES[daikon.Dictionary.GROUP_INDICES.length - 1]; } num = daikon.Dictionary.dict.length; for (ctr = startIndex; ctr < num; ctr += 1) { if ((daikon.Dictionary.dict[ctr][0] === group) && (daikon.Dictionary.dict[ctr][1] === element)) { vr = daikon.Dictionary.dict[ctr][3]; break; } else if (daikon.Dictionary.dict[ctr][0] > group) { break; } } if (vr === null) { num = daikon.Dictionary.dictPrivate.length; for (ctr = 0; ctr < num; ctr += 1) { if ((daikon.Dictionary.dictPrivate[ctr][0] === group) && (daikon.Dictionary.dictPrivate[ctr][1] === element)) { vr = daikon.Dictionary.dictPrivate[ctr][3]; break; } } if (vr === null) { vr = 'OB'; } } return vr; }; daikon.Dictionary.getDescription = function (group, element) { var des = null, startIndex, ctr, num; startIndex = daikon.Dictionary.GROUP_INDICES[group]; if (startIndex === undefined) { startIndex = daikon.Dictionary.GROUP_INDICES[daikon.Dictionary.GROUP_INDICES.length - 1]; } num = daikon.Dictionary.dict.length; for (ctr = startIndex; ctr < num; ctr += 1) { if ((daikon.Dictionary.dict[ctr][0] === group) && (daikon.Dictionary.dict[ctr][1] === element)) { des = daikon.Dictionary.dict[ctr][2]; break; } else if (daikon.Dictionary.dict[ctr][0] > group) { break; } } if (des === null) { num = daikon.Dictionary.dictPrivate.length; for (ctr = 0; ctr < num; ctr += 1) { if ((daikon.Dictionary.dictPrivate[ctr][0] === group) && (daikon.Dictionary.dictPrivate[ctr][1] === element)) { des = daikon.Dictionary.dictPrivate[ctr][2]; break; } } if (des === null) { des = 'PrivateData'; } } return des; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Dictionary; } /*jslint browser: true, node: true */ /*global require, module */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Tag = daikon.Tag || ((typeof require !== 'undefined') ? require('./tag.js') : null); daikon.Parser = daikon.Parser || ((typeof require !== 'undefined') ? require('./parser.js') : null); /*** Constructor ***/ daikon.Image = daikon.Image || function () { this.tags = {}; this.littleEndian = false; this.index = -1; }; /*** Static Pseudo-constants ***/ daikon.Image.SLICE_DIRECTION_UNKNOWN = -1; daikon.Image.SLICE_DIRECTION_AXIAL = 2; daikon.Image.SLICE_DIRECTION_CORONAL = 1; daikon.Image.SLICE_DIRECTION_SAGITTAL = 0; daikon.Image.SLICE_DIRECTION_OBLIQUE = 3; daikon.Image.OBLIQUITY_THRESHOLD_COSINE_VALUE = 0.8; daikon.Image.BYTE_TYPE_UNKNOWN = 0; daikon.Image.BYTE_TYPE_BINARY = 1; daikon.Image.BYTE_TYPE_INTEGER = 2; daikon.Image.BYTE_TYPE_INTEGER_UNSIGNED = 3; daikon.Image.BYTE_TYPE_FLOAT = 4; daikon.Image.BYTE_TYPE_COMPLEX = 5; daikon.Image.BYTE_TYPE_RGB = 6; /*** Static Methods ***/ daikon.Image.getSingleValueSafely = function (tag, index) { if (tag && tag.value) { return tag.value[index]; } return null; }; daikon.Image.getValueSafely = function (tag) { if (tag) { return tag.value; } return null; }; // originally from: http://public.kitware.com/pipermail/insight-users/2005-March/012246.html daikon.Image.getMajorAxisFromPatientRelativeDirectionCosine = function(x, y, z) { var axis, orientationX, orientationY, orientationZ, absX, absY, absZ; orientationX = (x < 0) ? "R" : "L"; orientationY = (y < 0) ? "A" : "P"; orientationZ = (z < 0) ? "F" : "H"; absX = Math.abs(x); absY = Math.abs(y); absZ = Math.abs(z); // The tests here really don't need to check the other dimensions, // just the threshold, since the sum of the squares should be == 1.0 // but just in case ... if ((absX > daikon.Image.OBLIQUITY_THRESHOLD_COSINE_VALUE) && (absX > absY) && (absX > absZ)) { axis = orientationX; } else if ((absY > daikon.Image.OBLIQUITY_THRESHOLD_COSINE_VALUE) && (absY > absX) && (absY > absZ)) { axis = orientationY; } else if ((absZ > daikon.Image.OBLIQUITY_THRESHOLD_COSINE_VALUE) && (absZ > absX) && (absZ > absY)) { axis = orientationZ; } else { axis = null; } return axis; }; /*** Prototype Methods ***/ daikon.Image.prototype.getCols = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_COLS[0], daikon.Tag.TAG_COLS[1]), 0); }; daikon.Image.prototype.getRows = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_ROWS[0], daikon.Tag.TAG_ROWS[1]), 0); }; daikon.Image.prototype.getSeriesDescription = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SERIES_DESCRIPTION[0], daikon.Tag.TAG_SERIES_DESCRIPTION[1]), 0); }; daikon.Image.prototype.getSeriesInstanceUID = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SERIES_INSTANCE_UID[0], daikon.Tag.TAG_SERIES_INSTANCE_UID[1]), 0); }; daikon.Image.prototype.getSeriesNumber = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SERIES_NUMBER[0], daikon.Tag.TAG_SERIES_NUMBER[1]), 0); }; daikon.Image.prototype.getEchoNumber = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_ECHO_NUMBER[0], daikon.Tag.TAG_ECHO_NUMBER[1]), 0); }; daikon.Image.prototype.getImagePosition = function () { return daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_POSITION[0], daikon.Tag.TAG_IMAGE_POSITION[1])); }; daikon.Image.prototype.getImagePositionSliceDir = function (sliceDir) { var imagePos = daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_POSITION[0], daikon.Tag.TAG_IMAGE_POSITION[1])); if (imagePos) { if (sliceDir >= 0) { return imagePos[sliceDir]; } } return 0; }; daikon.Image.prototype.getSliceLocation = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SLICE_LOCATION[0], daikon.Tag.TAG_SLICE_LOCATION[1]), 0); }; daikon.Image.prototype.getSliceLocationVector = function () { return daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_SLICE_LOCATION_VECTOR[0], daikon.Tag.TAG_SLICE_LOCATION_VECTOR[1])); }; daikon.Image.prototype.getImageNumber = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_NUM[0], daikon.Tag.TAG_IMAGE_NUM[1]), 0); }; daikon.Image.prototype.getTemporalPosition = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_TEMPORAL_POSITION[0], daikon.Tag.TAG_TEMPORAL_POSITION[1]), 0); }; daikon.Image.prototype.getTemporalNumber = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_NUMBER_TEMPORAL_POSITIONS[0], daikon.Tag.TAG_NUMBER_TEMPORAL_POSITIONS[1]), 0); }; daikon.Image.prototype.getSliceGap = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SLICE_GAP[0], daikon.Tag.TAG_SLICE_GAP[1]), 0); }; daikon.Image.prototype.getSliceThickness = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SLICE_THICKNESS[0], daikon.Tag.TAG_SLICE_THICKNESS[1]), 0); }; daikon.Image.prototype.getImageMax = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_MAX[0], daikon.Tag.TAG_IMAGE_MAX[1]), 0); }; daikon.Image.prototype.getImageMin = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_MIN[0], daikon.Tag.TAG_IMAGE_MIN[1]), 0); }; daikon.Image.prototype.getDataScaleSlope = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_DATA_SCALE_SLOPE[0], daikon.Tag.TAG_DATA_SCALE_SLOPE[1]), 0); }; daikon.Image.prototype.getDataScaleIntercept = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_DATA_SCALE_INTERCEPT[0], daikon.Tag.TAG_DATA_SCALE_INTERCEPT[1]), 0); }; daikon.Image.prototype.getDataScaleElscint = function () { var scale = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_DATA_SCALE_ELSCINT[0], daikon.Tag.TAG_DATA_SCALE_ELSCINT[1]), 0); if (!scale) { scale = 1; } var bandwidth = this.getPixelBandwidth(); scale = Math.sqrt(bandwidth) / (10 * scale); if (scale <= 0) { scale = 1; } return scale; }; daikon.Image.prototype.getWindowWidth = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_WINDOW_WIDTH[0], daikon.Tag.TAG_WINDOW_WIDTH[1]), 0); }; daikon.Image.prototype.getWindowCenter = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_WINDOW_CENTER[0], daikon.Tag.TAG_WINDOW_CENTER[1]), 0); }; daikon.Image.prototype.getPixelBandwidth = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PIXEL_BANDWIDTH[0], daikon.Tag.TAG_PIXEL_BANDWIDTH[1]), 0); }; daikon.Image.prototype.getSeriesId = function () { var des = this.getSeriesDescription(); var uid = this.getSeriesInstanceUID(); var num = this.getSeriesNumber(); var echo = this.getEchoNumber(); var orientation = this.getOrientation(); var id = ""; if (des !== null) { id += (" " + des); } if (uid !== null) { id += (" " + uid); } if (num !== null) { id += (" " + num); } if (echo !== null) { id += (" " + echo); } if (orientation !== null) { id += (" " + orientation); } return id; }; daikon.Image.prototype.getPixelSpacing = function () { return daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_PIXEL_SPACING[0], daikon.Tag.TAG_PIXEL_SPACING[1])); }; daikon.Image.prototype.getImageType = function () { return daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_TYPE[0], daikon.Tag.TAG_IMAGE_TYPE[1])); }; daikon.Image.prototype.getBitsStored = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_BITS_STORED[0], daikon.Tag.TAG_BITS_STORED[1]), 0); }; daikon.Image.prototype.getBitsAllocated = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_BITS_ALLOCATED[0], daikon.Tag.TAG_BITS_ALLOCATED[1]), 0); }; daikon.Image.prototype.getFrameTime = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_FRAME_TIME[0], daikon.Tag.TAG_FRAME_TIME[1]), 0); }; daikon.Image.prototype.getAcquisitionMatrix = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_ACQUISITION_MATRIX[0], daikon.Tag.TAG_ACQUISITION_MATRIX[1]), 0); }; daikon.Image.prototype.getTR = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_TR, daikon.Tag.TAG_TR[1]), 0); }; daikon.Image.prototype.putTag = function (tag) { this.tags[tag.id] = tag; }; daikon.Image.prototype.getTag = function (group, element) { return this.tags[daikon.Tag.createId(group, element)]; }; daikon.Image.prototype.getPixelData = function () { return this.tags[daikon.Tag.createId(daikon.Tag.TAG_PIXEL_DATA[0], daikon.Tag.TAG_PIXEL_DATA[1])]; }; daikon.Image.prototype.hasPixelData = function () { return (this.tags[daikon.Tag.createId(daikon.Tag.TAG_PIXEL_DATA[0], daikon.Tag.TAG_PIXEL_DATA[1])] !== undefined); }; daikon.Image.prototype.clearPixelData = function () { this.tags[daikon.Tag.createId(daikon.Tag.TAG_PIXEL_DATA[0], daikon.Tag.TAG_PIXEL_DATA[1])].value = null; }; daikon.Image.prototype.getOrientation = function () { var orientation = null, dirCos = daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_ORIENTATION[0], daikon.Tag.TAG_IMAGE_ORIENTATION[1])), ctr, spacing, rowSpacing, swapZ, bigRow = 0, bigCol = 0, biggest = 0, orient = ''; if (!dirCos || (dirCos.length !== 6)) { return null; } spacing = this.getPixelSpacing(); if (!spacing) { return null; } rowSpacing = spacing[0]; swapZ = true; for (ctr = 0; ctr < 3; ctr += 1) { if (Math.abs(dirCos[ctr]) > biggest) { biggest = Math.abs(dirCos[ctr]); bigRow = ctr; } } biggest = 0; for (; ctr < 6; ctr += 1) { if (Math.abs(dirCos[ctr]) > biggest) { biggest = Math.abs(dirCos[ctr]); bigCol = ctr; } } switch (bigRow) { case 0: orient += ('X'); if (bigCol === 4) { orient += ("YZ"); } else { orient += ("ZY"); } break; case 1: orient += ('Y'); if (bigCol === 3) { orient += ("XZ"); } else { orient += ("ZX"); } break; case 2: orient += ('Z'); if (bigCol === 3) { orient += ("XY"); } else { orient += ("YX"); } break; default: break; } switch (bigRow) { case 0: if (dirCos[bigRow] > 0.0) { orient += ('-'); } else { orient += ('+'); } if (bigCol === 4) { if (dirCos[bigCol] > 0.0) { orient += ('-'); } else { orient += ('+'); } } else { if (dirCos[bigCol] > 0.0) { orient += ('+'); } else { orient += ('-'); } } break; case 1: if (dirCos[bigRow] > 0.0) { orient += ('-'); } else { orient += ('+'); } if (bigCol === 3) { if (dirCos[bigCol] > 0.0) { orient += ('-'); } else { orient += ('+'); } } else { if (dirCos[bigCol] > 0.0) { orient += ('+'); } else { orient += ('-'); } } break; case 2: if (dirCos[bigRow] > 0.0) { orient += ('+'); } else { orient += ('-'); } //Has to be X or Y so opposite senses if (dirCos[bigCol] > 0.0) { orient += ('-'); } else { orient += ('+'); } break; default: break; } if (rowSpacing === 0.0) { orient += ('+'); orientation = orient; } else { if (swapZ) { switch (orient.charAt(2)) { case 'X': if (rowSpacing > 0.0) { orient += ('-'); } else { orient += ('+'); } break; case 'Y': case 'Z': if (rowSpacing > 0.0) { orient += ('+'); } else { orient += ('-'); } break; default: break; } } else { switch (orient.charAt(2)) { case 'X': if (rowSpacing > 0.0) { orient += ('+'); } else { orient += ('-'); } break; case 'Y': case 'Z': if (rowSpacing > 0.0) { orient += ('-'); } else { orient += ('+'); } break; default: break; } } orientation = orient; } return orientation; }; daikon.Image.prototype.isMosaic = function () { var imageType, labeledAsMosaic = false, canReadAsMosaic, ctr, matSize; imageType = this.getImageType(); if (imageType !== null) { for (ctr = 0; ctr < imageType.length; ctr += 1) { if (imageType[ctr].toUpperCase().indexOf("MOSAIC") !== -1) { labeledAsMosaic = true; break; } } } matSize = this.getAcquisitionMatrix(); canReadAsMosaic = (matSize > 0) && ((matSize < this.getRows()) || (matSize < this.getCols())); return labeledAsMosaic && canReadAsMosaic; }; /* if (isMosaic) { dcm.setMosaicCols(tempDicom[chosenFileIndex].getCols() / matSize[1]); dcm.setMosaicRows(tempDicom[chosenFileIndex].getRows() / matSize[0]); dcm.setMosaicWidth(tempDicom[chosenFileIndex].getCols()); dcm.setMosaicHeight(tempDicom[chosenFileIndex].getRows()); } */ daikon.Image.prototype.getMosaicCols = function() { return this.getCols() / this.getAcquisitionMatrix(); }; daikon.Image.prototype.getMosaicRows = function() { return this.getRows() / this.getAcquisitionMatrix(); }; daikon.Image.prototype.isElscint = function() { var dataScale = this.getDataScaleElscint(); return ((dataScale !== null) && (dataScale !== 0)); }; daikon.Image.prototype.isCompressed = function() { var transferSyntax = this.getTransferSyntax(); if (transferSyntax) { if (transferSyntax.indexOf(daikon.Parser.TRANSFER_SYNTAX_COMPRESSION_JPEG) !== -1) { return true; } else if (transferSyntax.indexOf(daikon.Parser.TRANSFER_SYNTAX_COMPRESSION_RLE) !== -1) { return true; } } return false; }; daikon.Image.prototype.getNumberOfFrames = function () { var value = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_NUMBER_OF_FRAMES[0], daikon.Tag.TAG_NUMBER_OF_FRAMES[1]), 0); if (value !== null) { return value; } return 1; }; daikon.Image.prototype.getNumberOfImplicitFrames = function () { var pixelData, length, size; pixelData = this.getPixelData(); length = pixelData.offsetEnd - pixelData.offsetValue; size = this.getCols() * this.getRows() * (parseInt(this.getBitsAllocated() / 8)); return parseInt(length / size); }; daikon.Image.prototype.getPixelRepresentation = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PIXEL_REPRESENTATION[0], daikon.Tag.TAG_PIXEL_REPRESENTATION[1]), 0); }; daikon.Image.prototype.getPhotometricInterpretation = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PHOTOMETRIC_INTERPRETATION[0], daikon.Tag.TAG_PHOTOMETRIC_INTERPRETATION[1]), 0); }; daikon.Image.prototype.getPatientName = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PATIENT_NAME[0], daikon.Tag.TAG_PATIENT_NAME[1]), 0); }; daikon.Image.prototype.getPatientID = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_PATIENT_ID[0], daikon.Tag.TAG_PATIENT_ID[1]), 0); }; daikon.Image.prototype.getStudyTime = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_STUDY_TIME[0], daikon.Tag.TAG_STUDY_TIME[1]), 0); }; daikon.Image.prototype.getTransferSyntax = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_TRANSFER_SYNTAX[0], daikon.Tag.TAG_TRANSFER_SYNTAX[1]), 0); }; daikon.Image.prototype.getStudyDate = function () { return daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_STUDY_DATE[0], daikon.Tag.TAG_STUDY_DATE[1]), 0); }; daikon.Image.prototype.getImageDescription = function () { var value, string = ""; value = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_STUDY_DES[0], daikon.Tag.TAG_STUDY_DES[1]), 0); if (value !== null) { string += (" " + value); } value = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_SERIES_DESCRIPTION[0], daikon.Tag.TAG_SERIES_DESCRIPTION[1]), 0); if (value !== null) { string += (" " + value); } value = daikon.Image.getSingleValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_COMMENTS[0], daikon.Tag.TAG_IMAGE_COMMENTS[1]), 0); if (value !== null) { string += (" " + value); } return string.trim(); }; daikon.Image.prototype.getDataType = function () { var interp, dataType; dataType = this.getPixelRepresentation(); if (dataType === null) { return daikon.Image.BYTE_TYPE_UNKNOWN; } interp = this.getPhotometricInterpretation(); if (interp !== null) { if (interp.trim() === "RGB") { return daikon.Image.BYTE_TYPE_RGB; } } if (dataType === 0) { return daikon.Image.BYTE_TYPE_INTEGER_UNSIGNED; } else if (dataType === 1) { return daikon.Image.BYTE_TYPE_INTEGER; } else { return daikon.Image.BYTE_TYPE_UNKNOWN; } }; // originally from: http://public.kitware.com/pipermail/insight-users/2005-March/012246.html daikon.Image.prototype.getAcquiredSliceDirection = function () { var dirCos, rowAxis, colAxis, label; dirCos = daikon.Image.getValueSafely(this.getTag(daikon.Tag.TAG_IMAGE_ORIENTATION[0], daikon.Tag.TAG_IMAGE_ORIENTATION[1])); if (!dirCos || (dirCos.length !== 6)) { return daikon.Image.SLICE_DIRECTION_UNKNOWN; } rowAxis = daikon.Image.getMajorAxisFromPatientRelativeDirectionCosine(dirCos[0], dirCos[1], dirCos[2]); colAxis = daikon.Image.getMajorAxisFromPatientRelativeDirectionCosine(dirCos[3], dirCos[4], dirCos[5]); if ((rowAxis !== null) && (colAxis !== null)) { if (((rowAxis === "R") || (rowAxis === "L")) && ((colAxis === "A") || (colAxis === "P"))) { label = daikon.Image.SLICE_DIRECTION_AXIAL; } else if (((colAxis === "R") || (colAxis === "L")) && ((rowAxis === "A") || (rowAxis === "P"))) { label = daikon.Image.SLICE_DIRECTION_AXIAL; } else if (((rowAxis === "R") || (rowAxis === "L")) && ((colAxis === "H") || (colAxis === "F"))) { label = daikon.Image.SLICE_DIRECTION_CORONAL; } else if (((colAxis === "R") || (colAxis === "L")) && ((rowAxis === "H") || (rowAxis === "F"))) { label = daikon.Image.SLICE_DIRECTION_CORONAL; } else if (((rowAxis === "A") || (rowAxis === "P")) && ((colAxis === "H") || (colAxis === "F"))) { label = daikon.Image.SLICE_DIRECTION_SAGITTAL; } else if (((colAxis === "A") || (colAxis === "P")) && ((rowAxis === "H") || (rowAxis === "F"))) { label = daikon.Image.SLICE_DIRECTION_SAGITTAL; } } else { label = daikon.Image.SLICE_DIRECTION_OBLIQUE; } return label; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Image; } /*jslint browser: true, node: true */ /*global require */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.OrderedMap = daikon.OrderedMap || ((typeof require !== 'undefined') ? require('./orderedmap.js') : null); /*** Constructor ***/ daikon.OrderedMapIterator = daikon.OrderedMapIterator || function (orderedMap) { this.orderedMap = orderedMap; this.index = 0; }; /*** Prototype Methods ***/ daikon.OrderedMapIterator.prototype.hasNext = function() { return (this.index < this.orderedMap.orderedKeys.length); }; daikon.OrderedMapIterator.prototype.next = function() { var item = this.orderedMap.get(this.orderedMap.orderedKeys[this.index]); this.index += 1; return item; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.OrderedMapIterator; } /*jslint browser: true, node: true */ /*global require */ "use strict"; // Based on: http://stackoverflow.com/questions/3549894/javascript-data-structure-for-fast-lookup-and-ordered-looping /*** Imports ***/ var daikon = daikon || {}; daikon.OrderedMapIterator = daikon.OrderedMapIterator || ((typeof require !== 'undefined') ? require('./iterator.js') : null); /*** Constructor ***/ daikon.OrderedMap = daikon.OrderedMap || function () { this.map = {}; this.orderedKeys = []; }; daikon.OrderedMap.prototype.put = function(key, value) { if (key in this.map) { // key already exists, replace value this.map[key] = value; } else { // insert new key and value this.orderedKeys.push(key); this.orderedKeys.sort(function(a, b) { return parseFloat(a) - parseFloat(b); }); this.map[key] = value; } }; daikon.OrderedMap.prototype.remove = function(key) { var index = this.orderedKeys.indexOf(key); if(index === -1) { throw new Error('key does not exist'); } this.orderedKeys.splice(index, 1); delete this.map[key]; }; daikon.OrderedMap.prototype.get = function(key) { if (key in this.map) { return this.map[key]; } return null; }; daikon.OrderedMap.prototype.iterator = function() { return new daikon.OrderedMapIterator(this); }; daikon.OrderedMap.prototype.getOrderedValues = function() { var orderedValues = [], it = this.iterator(); while (it.hasNext()) { orderedValues.push(it.next()); } return orderedValues; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.OrderedMap; } /*jslint browser: true, node: true */ /*global require */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Tag = daikon.Tag || ((typeof require !== 'undefined') ? require('./tag.js') : null); daikon.Utils = daikon.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null); daikon.Dictionary = daikon.Dictionary || ((typeof require !== 'undefined') ? require('./dictionary.js') : null); daikon.Image = daikon.Image || ((typeof require !== 'undefined') ? require('./image.js') : null); /*** Constructor ***/ daikon.Parser = daikon.Parser || function () { this.littleEndian = true; this.explicit = true; this.metaFound = false; this.metaFinished = false; this.metaFinishedOffset = -1; this.error = null; }; /*** Static Fields ***/ daikon.Parser.verbose = false; /*** Static Pseudo-constants ***/ daikon.Parser.MAGIC_COOKIE_OFFSET = 128; daikon.Parser.MAGIC_COOKIE = [68, 73, 67, 77]; daikon.Parser.VRS = ["AE", "AS", "AT", "CS", "DA", "DS", "DT", "FL", "FD", "IS", "LO", "LT", "OB", "OD", "OF", "OW", "PN", "SH", "SL", "SS", "ST", "TM", "UI", "UL", "UN", "US", "UT"]; daikon.Parser.DATA_VRS = ["OB", "OW", "OF", "SQ", "UT", "UN"]; daikon.Parser.RAW_DATA_VRS = ["OB", "OD", "OF", "OW", "UN"]; daikon.Parser.TRANSFER_SYNTAX_IMPLICIT_LITTLE = "1.2.840.10008.1.2"; daikon.Parser.TRANSFER_SYNTAX_EXPLICIT_LITTLE = "1.2.840.10008.1.2.1"; daikon.Parser.TRANSFER_SYNTAX_EXPLICIT_BIG = "1.2.840.10008.1.2.2"; daikon.Parser.TRANSFER_SYNTAX_COMPRESSION_JPEG = "1.2.840.10008.1.2.4"; daikon.Parser.TRANSFER_SYNTAX_COMPRESSION_RLE = "1.2.840.10008.1.2.5"; daikon.Parser.UNDEFINED_LENGTH = 0xFFFFFFFF; /*** Static Methods ***/ daikon.Parser.isMagicCookieFound = function (data) { var offset = daikon.Parser.MAGIC_COOKIE_OFFSET, magicCookieLength = daikon.Parser.MAGIC_COOKIE.length, ctr; for (ctr = 0; ctr < magicCookieLength; ctr += 1) { if (data.getUint8(offset + ctr) !== daikon.Parser.MAGIC_COOKIE[ctr]) { return false; } } return true; }; /*** Prototype Methods ***/ daikon.Parser.prototype.parse = function (data) { var image = null, offset, tag; try { image = new daikon.Image(); offset = this.findFirstTagOffset(data); tag = this.getNextTag(data, offset); while (tag !== null) { if (daikon.Parser.verbose) { console.log(tag.toString()); } image.putTag(tag); if (tag.isPixelData()) { break; } tag = this.getNextTag(data, tag.offsetEnd); } } catch (err) { this.error = err; } if (image !== null) { image.littleEndian = this.littleEndian; } return image; }; daikon.Parser.prototype.testForValidTag = function (data) { var offset, tag = null; try { offset = this.findFirstTagOffset(data); tag = this.getNextTag(data, offset, true); } catch (err) { this.error = err; } return tag; }; daikon.Parser.prototype.getNextTag = function (data, offset, testForTag) { var group = 0, element, value = null, offsetStart = offset, offsetValue, length = 0, little = true, vr = null, tag; if (offset >= data.byteLength) { return null; } if (this.metaFinished) { little = this.littleEndian; group = data.getUint16(offset, little); } else { group = data.getUint16(offset, true); if (((this.metaFinishedOffset !== -1) && (offset >= this.metaFinishedOffset)) || (group !== 0x0002)) { this.metaFinished = true; little = this.littleEndian; group = data.getUint16(offset, little); } else { little = true; } } if (!this.metaFound && (group === 0x0002)) { this.metaFound = true; } offset += 2; element = data.getUint16(offset, true); offset += 2; if ((group === 0) && (element === 0)) { console.log("here"); } if (this.explicit || !this.metaFinished) { vr = daikon.Utils.getStringAt(data, offset, 2); if (!this.metaFound && this.metaFinished && (daikon.Parser.VRS.indexOf(vr) === -1)) { vr = daikon.Dictionary.getVR(group, element); length = data.getUint32(offset, little); offset += 4; this.explicit = false; } else { offset += 2; if (daikon.Parser.DATA_VRS.indexOf(vr) !== -1) { offset += 2; // skip two empty bytes length = data.getUint32(offset, little); offset += 4; } else { length = data.getUint16(offset, little); offset += 2; } } } else { vr = daikon.Dictionary.getVR(group, element); length = data.getUint32(offset, little); if (length === daikon.Parser.UNDEFINED_LENGTH) { vr = 'SQ'; } offset += 4; } offsetValue = offset; if (vr === 'SQ') { value = this.parseSublist(data, offset, length); if (length === daikon.Parser.UNDEFINED_LENGTH) { length = value[value.length - 1].offsetEnd - offset; } } else if ((length > 0) && !testForTag) { value = data.buffer.slice(offset, offset + length); } offset += length; tag = new daikon.Tag(group, element, vr, value, offsetStart, offsetValue, offset, this.littleEndian); if (tag.isTransformSyntax()) { if (tag.value[0] === daikon.Parser.TRANSFER_SYNTAX_IMPLICIT_LITTLE) { this.explicit = false; this.littleEndian = true; } else if (tag.value[0] === daikon.Parser.TRANSFER_SYNTAX_EXPLICIT_LITTLE) { this.explicit = true; this.littleEndian = true; } else if (tag.value[0] === daikon.Parser.TRANSFER_SYNTAX_EXPLICIT_BIG) { this.explicit = true; this.littleEndian = false; } } else if (tag.isMetaLength()) { this.metaFinishedOffset = tag.value[0] + offset; } return tag; }; daikon.Parser.prototype.parseSublist = function (data, offset, length) { var sublistItem, offsetEnd = offset + length, tags = []; if (length === daikon.Parser.UNDEFINED_LENGTH) { sublistItem = this.parseSublistItem(data, offset); while (!sublistItem.isSequenceDelim()) { tags.push(sublistItem); offset = sublistItem.offsetEnd; sublistItem = this.parseSublistItem(data, offset); } tags.push(sublistItem); } else { while (offset < offsetEnd) { sublistItem = this.parseSublistItem(data, offset); tags.push(sublistItem); offset = sublistItem.offsetEnd; } } return tags; }; daikon.Parser.prototype.parseSublistItem = function (data, offset) { var group, element, length, offsetEnd, tag, offsetStart = offset, offsetValue, sublistItemTag, tags = []; group = data.getUint16(offset, this.littleEndian); offset += 2; element = data.getUint16(offset, this.littleEndian); offset += 2; length = data.getUint32(offset, this.littleEndian); offset += 4; offsetValue = offset; if (length === daikon.Parser.UNDEFINED_LENGTH) { tag = this.getNextTag(data, offset); while (!tag.isSublistItemDelim()) { tags.push(tag); offset = tag.offsetEnd; tag = this.getNextTag(data, offset); } tags.push(tag); offset = tag.offsetEnd; } else { offsetEnd = offset + length; while (offset < offsetEnd) { tag = this.getNextTag(data, offset); tags.push(tag); offset = tag.offsetEnd; } } sublistItemTag = new daikon.Tag(group, element, null, tags, offsetStart, offsetValue, offset, this.littleEndian); return sublistItemTag; }; daikon.Parser.prototype.findFirstTagOffset = function (data) { var offset = 0, magicCookieLength = daikon.Parser.MAGIC_COOKIE.length, searchOffsetMax = daikon.Parser.MAGIC_COOKIE_OFFSET * 2, found = false, ctr = 0, ctrIn = 0, ch = 0; if (daikon.Parser.isMagicCookieFound(data)) { offset = daikon.Parser.MAGIC_COOKIE_OFFSET + magicCookieLength; } else { for (ctr = 0; ctr < searchOffsetMax; ctr += 1) { ch = data.getUint8(offset); if (ch === daikon.Parser.MAGIC_COOKIE[0]) { found = true; for (ctrIn = 1; ctrIn < magicCookieLength; ctrIn += 1) { if (data.getUint8(ctr + ctrIn) !== daikon.Parser.MAGIC_COOKIE[ctrIn]) { found = false; } } if (found) { offset = ctr; break; } } } } return offset; }; daikon.Parser.prototype.hasError = function () { return (this.error !== null); }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Parser; } /*jslint browser: true, node: true */ /*global require, module */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Parser = daikon.Parser || ((typeof require !== 'undefined') ? require('./parser.js') : null); daikon.Image = daikon.Image || ((typeof require !== 'undefined') ? require('./image.js') : null); daikon.OrderedMap = daikon.OrderedMap || ((typeof require !== 'undefined') ? require('./orderedmap.js') : null); daikon.OrderedMapIterator = daikon.OrderedMapIterator || ((typeof require !== 'undefined') ? require('./iterator.js') : null); daikon.Utils = daikon.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null); /*** Constructor ***/ daikon.Series = daikon.Series || function () { this.images = []; this.imagesOriginalOrder = null; this.isMosaic = false; this.isElscint = false; this.isCompressed = false; this.numberOfFrames = 0; this.numberOfFramesInFile = 0; this.isMultiFrame = false; this.isMultiFrameVolume = false; this.isMultiFrameTimeseries = false; this.isImplicitTimeseries = false; this.sliceSense = false; this.sliceDir = daikon.Image.SLICE_DIRECTION_UNKNOWN; this.error = null; }; /*** Static fields ***/ daikon.Series.parserError = null; /*** Static Methods ***/ daikon.Series.parseImage = function (data) { var parser, image; parser = new daikon.Parser(); image = parser.parse(data); if (parser.hasError()) { daikon.Series.parserError = parser.error; return null; } return image; }; daikon.Series.getMosaicOffset = function (mosaicCols, mosaicColWidth, mosaicRowHeight, mosaicWidth, xLocVal, yLocVal, zLocVal) { var xLoc, yLoc, zLoc; xLoc = xLocVal; yLoc = yLocVal; zLoc = zLocVal; xLoc = ((zLoc % mosaicCols) * mosaicColWidth) + xLoc; yLoc = (((parseInt(zLoc / mosaicCols)) * mosaicRowHeight) + yLoc) * mosaicWidth; return (xLoc + yLoc); }; daikon.Series.orderDicoms = function (images, numFrames, sliceDir) { var hasImagePosition, hasSliceLocation, hasImageNumber, timeMap, timeIt, ctr, ctrIn, dg, ordered, imagesOrderedByTimeAndSpace; hasImagePosition = (images[0].getImagePosition() !== null); hasSliceLocation = (images[0].getSliceLocation() !== null); hasImageNumber = (images[0].getImageNumber() !== null); timeMap = daikon.Series.orderByTime(images, numFrames, sliceDir, hasImagePosition, hasSliceLocation); timeIt = timeMap.orderedKeys; imagesOrderedByTimeAndSpace = []; for (ctr = 0; ctr < timeIt.length; ctr += 1) { dg = timeMap.get(timeIt[ctr]); if (hasImagePosition) { ordered = daikon.Series.orderByImagePosition(dg, sliceDir); } else if (hasSliceLocation) { ordered = daikon.Series.orderBySliceLocation(dg); } else if (hasImageNumber) { ordered = daikon.Series.orderByImageNumber(dg); } else { ordered = dg; } for (ctrIn = 0; ctrIn < ordered.length; ctrIn += 1) { imagesOrderedByTimeAndSpace.push(ordered[ctrIn]); } } for (ctrIn = 0; ctrIn < imagesOrderedByTimeAndSpace.length; ctrIn += 1) { imagesOrderedByTimeAndSpace[ctrIn].index = ctrIn; } return imagesOrderedByTimeAndSpace; }; daikon.Series.orderByImagePosition = function (images, sliceDir) { var dicomMap, ctr; dicomMap = new daikon.OrderedMap(); for (ctr = 0; ctr < images.length; ctr += 1) { dicomMap.put(images[ctr].getImagePositionSliceDir(sliceDir), images[ctr]); } return dicomMap.getOrderedValues(); }; daikon.Series.orderBySliceLocation = function (images) { var dicomMap, ctr; dicomMap = new daikon.OrderedMap(); for (ctr = 0; ctr < images.length; ctr += 1) { dicomMap.put(images[ctr].getSliceLocation(), images[ctr]); } return dicomMap.getOrderedValues(); }; daikon.Series.orderByImageNumber = function (images) { var dicomMap, ctr; dicomMap = new daikon.OrderedMap(); for (ctr = 0; ctr < images.length; ctr += 1) { dicomMap.put(images[ctr].getImageNumber(), images[ctr]); } return dicomMap.getOrderedValues(); }; daikon.Series.hasMatchingSlice = function (dg, image, sliceDir, doImagePos, doSliceLoc) { var matchingNum = 0, ctr, current, imagePos, sliceLoc, imageNum; if (doImagePos) { matchingNum = image.getImagePositionSliceDir(sliceDir); } else if (doSliceLoc) { matchingNum = image.getSliceLocation(); } else { matchingNum = image.getImageNumber(); } for (ctr = 0; ctr < dg.length; ctr += 1) { current = dg[ctr]; if (doImagePos) { imagePos = current.getImagePositionSliceDir(sliceDir); if (imagePos === matchingNum) { return true; } } else if (doSliceLoc) { sliceLoc = current.getSliceLocation(); if (sliceLoc === matchingNum) { return true; } } else { imageNum = current.getImageNumber(); if (imageNum === matchingNum) { return true; } } } return false; }; daikon.Series.orderByTime = function (images, numFrames, sliceDir, hasImagePosition, hasSliceLocation) { var dicomMap, hasTemporalPosition, hasTemporalNumber, ctr, image, tempPos, dg, timeBySliceMap, imageNum, sliceMarker, slice, dicomsCopy, dicomsCopyIndex, sliceIt, timeIt, dgFound, it; dicomMap = new daikon.OrderedMap(); hasTemporalPosition = (numFrames > 1) && (images[0].getTemporalPosition() !== null); hasTemporalNumber = (numFrames > 1) && (images[0].getTemporalNumber() !== null) && (images[0].getTemporalNumber() === numFrames); if (hasTemporalPosition && hasTemporalNumber) { // explicit series for (ctr = 0; ctr < images.length; ctr += 1) { image = images[ctr]; tempPos = image.getTemporalPosition(); dg = dicomMap.get(tempPos); if (!dg) { dg = []; dicomMap.put(tempPos, dg); } dg.push(image); } } else { // implicit series // order data by slice then time timeBySliceMap = new daikon.OrderedMap(); for (ctr = 0; ctr < images.length; ctr += 1) { if (images[ctr] !== null) { imageNum = images[ctr].getImageNumber(); sliceMarker = ctr; if (hasImagePosition) { sliceMarker = images[ctr].getImagePositionSliceDir(sliceDir); } else if (hasSliceLocation) { sliceMarker = images[ctr].getSliceLocation(); } slice = timeBySliceMap.get(sliceMarker); if (slice === null) { slice = new daikon.OrderedMap(); timeBySliceMap.put(sliceMarker, slice); } slice.put(imageNum, images[ctr]); } } // copy into DICOM array (ordered by slice by time) dicomsCopy = []; dicomsCopyIndex = 0; sliceIt = timeBySliceMap.iterator(); while (sliceIt.hasNext()) { slice = sliceIt.next(); timeIt = slice.iterator(); while (timeIt.hasNext()) { dicomsCopy[dicomsCopyIndex] = timeIt.next(); dicomsCopyIndex += 1; } } // groups dicoms by timepoint for (ctr = 0; ctr < dicomsCopy.length; ctr += 1) { if (dicomsCopy[ctr] !== null) { dgFound = null; it = dicomMap.iterator(); while (it.hasNext()) { dg = it.next(); if (!daikon.Series.hasMatchingSlice(dg, dicomsCopy[ctr], sliceDir, hasImagePosition, hasSliceLocation)) { dgFound = dg; break; } } if (dgFound === null) { dgFound = []; dicomMap.put(dicomMap.orderedKeys.length, dgFound); } dgFound.push(dicomsCopy[ctr]); } } } return dicomMap; }; /*** Prototype Methods ***/ daikon.Series.prototype.getOrder = function () { var ctr, order = []; for (ctr = 0; ctr < this.imagesOriginalOrder.length; ctr += 1) { order[ctr] = this.imagesOriginalOrder[ctr].index; } return order; }; daikon.Series.prototype.toString = function () { return this.images[0].getSeriesId(); }; daikon.Series.prototype.getName = function () { var des = this.images[0].getSeriesDescription(); var uid = this.images[0].getSeriesInstanceUID(); if (des !== null) { return des; } if (uid !== null) { return uid; } return null; }; daikon.Series.prototype.addImage = function (image) { this.images.push(image); }; daikon.Series.prototype.matchesSeries = function (image) { if (this.images.length === 0) { return true; } return (this.images[0].getSeriesId() === image.getSeriesId()); }; daikon.Series.prototype.buildSeries = function () { var hasFrameTime, ctr, sliceLoc, orderedImages, sliceLocationFirst, sliceLocationLast, sliceLocDiff, sliceLocations, orientation, imagePos; this.isMosaic = this.images[0].isMosaic(); this.isElscint = this.images[0].isElscint(); this.isCompressed = this.images[0].isCompressed(); // check for multi-frame this.numberOfFrames = this.images[0].getNumberOfFrames(); this.numberOfFramesInFile = this.images[0].getNumberOfImplicitFrames(); this.isMultiFrame = (this.numberOfFrames > 1) || (this.isMosaic && (this.images[0].length > 1)); this.isMultiFrameVolume = false; this.isMultiFrameTimeseries = false; this.isImplicitTimeseries = false; if (this.isMultiFrame) { hasFrameTime = (this.images[0].getFrameTime() > 0); if (this.isMosaic) { this.isMultiFrameTimeseries = true; } else { if (hasFrameTime) { this.isMultiFrameTimeseries = true; } else if (this.numberOfFramesInFile > 1) { this.isMultiFrameTimeseries = true; this.numberOfFrames = this.images.length; } else { this.isMultiFrameVolume = true; } } } if (!this.isMosaic && (this.numberOfFrames <= 1)) { // check for implicit frame count imagePos = (this.images[0].getImagePosition() || []); sliceLoc = imagePos.toString(); this.numberOfFrames = 0; for (ctr = 0; ctr < this.images.length; ctr += 1) { imagePos = (this.images[ctr].getImagePosition() || []); if (imagePos.toString() === sliceLoc) { this.numberOfFrames += 1; } } if (this.numberOfFrames > 1) { this.isImplicitTimeseries = true; } } this.sliceDir = this.images[0].getAcquiredSliceDirection(); orderedImages = daikon.Series.orderDicoms(this.images, this.numberOfFrames, this.sliceDir); sliceLocationFirst = orderedImages[0].getImagePositionSliceDir(this.sliceDir); sliceLocationLast = orderedImages[orderedImages.length - 1].getImagePositionSliceDir(this.sliceDir); sliceLocDiff = sliceLocationLast - sliceLocationFirst; if (this.isMosaic) { this.sliceSense = true; } else if (this.isMultiFrame) { sliceLocations = orderedImages[0].getSliceLocationVector(); if (sliceLocations !== null) { orientation = orderedImages[0].getOrientation(); if (orientation.charAt(2) === 'Z') { this.sliceSense = (sliceLocations[0] - sliceLocations[sliceLocations.length - 1]) < 0; } else { this.sliceSense = (sliceLocations[0] - sliceLocations[sliceLocations.length - 1]) > 0; } } else { this.sliceSense = sliceLocationFirst < 0 ? false : true; // maybe??? } } else { /* * "The direction of the axes is defined fully by the patient's orientation. The x-axis is increasing to the left hand side of the patient. The * y-axis is increasing to the posterior side of the patient. The z-axis is increasing toward the head of the patient." */ if ((this.sliceDir === daikon.Image.SLICE_DIRECTION_SAGITTAL) || (this.sliceDir === daikon.Image.SLICE_DIRECTION_CORONAL)) { if (sliceLocDiff > 0) { this.sliceSense = false; } else { this.sliceSense = true; } } else { if (sliceLocDiff > 0) { this.sliceSense = true; } else { this.sliceSense = false; } } } this.imagesOriginalOrder = this.images; this.images = orderedImages; }; daikon.Series.prototype.concatenateImageData = function (progressMeter, onFinishedImageRead) { var buffer; if (this.isMosaic) { buffer = this.getMosaicData(this.images[0], this.images[0].getPixelData().value.buffer); this.images[0].clearPixelData(); } else { buffer = this.images[0].getPixelData().value.buffer; this.images[0].clearPixelData(); } setTimeout(this.concatenateNextImageData(buffer, progressMeter, 1, onFinishedImageRead), 0); }; daikon.Series.prototype.concatenateNextImageData = function (buffer, progressMeter, index, onFinishedImageRead) { if (index >= this.images.length) { if (progressMeter) { progressMeter.drawProgress(1, "Reading DICOM Images"); } onFinishedImageRead(buffer); } else { if (progressMeter) { progressMeter.drawProgress(index / this.images.length, "Reading DICOM Images"); } if (this.isMosaic) { buffer = daikon.Utils.concatArrayBuffers(buffer, this.getMosaicData(this.images[index], this.images[index].getPixelData().value.buffer)); this.images[index].clearPixelData(); } else { buffer = daikon.Utils.concatArrayBuffers(buffer, this.images[index].getPixelData().value.buffer); this.images[index].clearPixelData(); } setTimeout(daikon.Utils.bind(this, function() {this.concatenateNextImageData(buffer, progressMeter, index + 1, onFinishedImageRead);}), 0); } }; daikon.Series.prototype.getMosaicData = function (image, data) { var mosaicWidth, mosaicHeight, mosaicRows, mosaicCols, mosaicRowHeight, mosaicColWidth, numBytes, ctrS, ctrR, ctrC, numSlices, numRows, numCols, buffer, dataTyped, offset, ctr, index = 0; numBytes = parseInt(this.images[0].getBitsAllocated() / 8); numSlices = this.images[0].getMosaicCols() * this.images[0].getMosaicRows(); numRows = parseInt(this.images[0].getRows() / this.images[0].getMosaicRows()); numCols = parseInt(this.images[0].getCols() / this.images[0].getMosaicCols()); mosaicWidth = this.images[0].getCols(); mosaicHeight = this.images[0].getRows(); mosaicRows = this.images[0].getMosaicRows(); mosaicCols = this.images[0].getMosaicCols(); mosaicRowHeight = parseInt(mosaicHeight / mosaicRows); mosaicColWidth = parseInt(mosaicWidth / mosaicCols); buffer = new Uint8Array(new ArrayBuffer(numSlices * numRows * numCols * numBytes)); dataTyped = new Uint8Array(data); for (ctrS = 0; ctrS < numSlices; ctrS += 1) { for (ctrR = 0; ctrR < numRows; ctrR += 1) { for (ctrC = 0; ctrC < numCols; ctrC += 1) { offset = daikon.Series.getMosaicOffset(mosaicCols, mosaicColWidth, mosaicRowHeight, mosaicWidth, ctrC, ctrR, ctrS); for (ctr = 0; ctr < numBytes; ctr += 1) { buffer[index] = dataTyped[(offset * numBytes) + ctr]; index += 1; } } } } return buffer.buffer; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Series; } /*jslint browser: true, node: true */ /*global require */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Utils = daikon.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null); daikon.Dictionary = daikon.Dictionary || ((typeof require !== 'undefined') ? require('./dictionary.js') : null); /*** Constructor ***/ daikon.Tag = daikon.Tag || function (group, element, vr, value, offsetStart, offsetValue, offsetEnd, littleEndian) { this.group = group; this.element = element; this.vr = vr; this.offsetStart = offsetStart; this.offsetValue = offsetValue; this.offsetEnd = offsetEnd; this.sublist = false; this.id = daikon.Tag.createId(group, element); if (value instanceof Array) { this.value = value; this.sublist = true; } else if (value !== null) { this.value = daikon.Tag.convertValue(vr, new DataView(value), littleEndian); } else { this.value = null; } }; /*** Static Pseudo-constants ***/ daikon.Tag.VR_AE_MAX_LENGTH = 16; daikon.Tag.VR_AS_MAX_LENGTH = 4; daikon.Tag.VR_AT_MAX_LENGTH = 4; daikon.Tag.VR_CS_MAX_LENGTH = 16; daikon.Tag.VR_DA_MAX_LENGTH = 8; daikon.Tag.VR_DS_MAX_LENGTH = 16; daikon.Tag.VR_DT_MAX_LENGTH = 26; daikon.Tag.VR_FL_MAX_LENGTH = 4; daikon.Tag.VR_FD_MAX_LENGTH = 8; daikon.Tag.VR_IS_MAX_LENGTH = 12; daikon.Tag.VR_LO_MAX_LENGTH = 64; daikon.Tag.VR_LT_MAX_LENGTH = 10240; daikon.Tag.VR_OB_MAX_LENGTH = -1; daikon.Tag.VR_OD_MAX_LENGTH = -1; daikon.Tag.VR_OF_MAX_LENGTH = -1; daikon.Tag.VR_OW_MAX_LENGTH = -1; daikon.Tag.VR_PN_MAX_LENGTH = 64 * 5; daikon.Tag.VR_SH_MAX_LENGTH = 16; daikon.Tag.VR_SL_MAX_LENGTH = 4; daikon.Tag.VR_SS_MAX_LENGTH = 2; daikon.Tag.VR_ST_MAX_LENGTH = 1024; daikon.Tag.VR_TM_MAX_LENGTH = 16; daikon.Tag.VR_UI_MAX_LENGTH = 64; daikon.Tag.VR_UL_MAX_LENGTH = 4; daikon.Tag.VR_UN_MAX_LENGTH = -1; daikon.Tag.VR_US_MAX_LENGTH = 2; daikon.Tag.VR_UT_MAX_LENGTH = -1; // metadata daikon.Tag.TAG_TRANSFER_SYNTAX = [0x0002, 0x0010]; daikon.Tag.TAG_META_LENGTH = [0x0002, 0x0000]; // sublists daikon.Tag.TAG_SUBLIST_ITEM = [0xFFFE, 0xE000]; daikon.Tag.TAG_SUBLIST_ITEM_DELIM = [0xFFFE, 0xE00D]; daikon.Tag.TAG_SUBLIST_SEQ_DELIM = [0xFFFE, 0xE0DD]; // image dims daikon.Tag.TAG_ROWS = [0x0028, 0x0010]; daikon.Tag.TAG_COLS = [0x0028, 0x0011]; daikon.Tag.TAG_ACQUISITION_MATRIX = [0x0018, 0x1310]; daikon.Tag.TAG_NUMBER_OF_FRAMES = [0x0028, 0x0008]; daikon.Tag.TAG_NUMBER_TEMPORAL_POSITIONS = [0x0020, 0x0105]; // voxel dims daikon.Tag.TAG_PIXEL_SPACING = [0x0028, 0x0030]; daikon.Tag.TAG_SLICE_THICKNESS = [0x0018, 0x0050]; daikon.Tag.TAG_SLICE_GAP = [0x0018, 0x0088]; daikon.Tag.TAG_TR = [0x0018, 0x0080]; daikon.Tag.TAG_FRAME_TIME = [0x0018, 0x1063]; // datatype daikon.Tag.TAG_BITS_ALLOCATED = [0x0028, 0x0100]; daikon.Tag.TAG_BITS_STORED = [0x0028, 0x0101]; daikon.Tag.TAG_PIXEL_REPRESENTATION = [0x0028, 0x0103]; daikon.Tag.TAG_HIGH_BIT = [0x0028, 0x0102]; daikon.Tag.TAG_PHOTOMETRIC_INTERPRETATION = [0x0028, 0x0004]; daikon.Tag.TAG_SAMPLES_PER_PIXEL = [0x0028, 0x0002]; // data scale daikon.Tag.TAG_DATA_SCALE_SLOPE = [0x0028, 0x1053]; daikon.Tag.TAG_DATA_SCALE_INTERCEPT = [0x0028, 0x1052]; daikon.Tag.TAG_DATA_SCALE_ELSCINT = [0x0207, 0x101F]; daikon.Tag.TAG_PIXEL_BANDWIDTH = [0x0018, 0x0095]; // range daikon.Tag.TAG_IMAGE_MIN = [0x0028, 0x0106]; daikon.Tag.TAG_IMAGE_MAX = [0x0028, 0x0107]; daikon.Tag.TAG_WINDOW_CENTER = [0x0028, 0x1050]; daikon.Tag.TAG_WINDOW_WIDTH = [0x0028, 0x1051]; // descriptors daikon.Tag.TAG_PATIENT_NAME = [0x0010, 0x0010]; daikon.Tag.TAG_PATIENT_ID = [0x0010, 0x0020]; daikon.Tag.TAG_STUDY_DATE = [0x0008, 0x0020]; daikon.Tag.TAG_STUDY_TIME = [0x0008, 0x0030]; daikon.Tag.TAG_STUDY_DES = [0x0008, 0x1030]; daikon.Tag.TAG_IMAGE_TYPE = [0x0008, 0x0008]; daikon.Tag.TAG_IMAGE_COMMENTS = [0x0020, 0x4000]; daikon.Tag.TAG_SEQUENCE_NAME = [0x0018, 0x0024]; daikon.Tag.TAG_MODALITY = [0x0008, 0x0060]; // session ID daikon.Tag.TAG_FRAME_OF_REF_UID = [0x0020, 0x0052]; // study ID daikon.Tag.TAG_STUDY_UID = [0x0020, 0x000D]; // volume ID daikon.Tag.TAG_SERIES_DESCRIPTION = [0x0008, 0x103E]; daikon.Tag.TAG_SERIES_INSTANCE_UID = [0x0020, 0x000E]; daikon.Tag.TAG_SERIES_NUMBER = [0x0020, 0x0011]; daikon.Tag.TAG_ECHO_NUMBER = [0x0018, 0x0086]; daikon.Tag.TAG_TEMPORAL_POSITION = [0x0020, 0x0100]; // slice ID daikon.Tag.TAG_IMAGE_NUM = [0x0020, 0x0013]; daikon.Tag.TAG_SLICE_LOCATION = [0x0020, 0x1041]; // orientation daikon.Tag.TAG_IMAGE_ORIENTATION = [0x0020, 0x0037]; daikon.Tag.TAG_IMAGE_POSITION = [0x0020, 0x0032]; daikon.Tag.TAG_SLICE_LOCATION_VECTOR = [0x0018, 0x2005]; // pixel data daikon.Tag.TAG_PIXEL_DATA = [0x7FE0, 0x0010]; /*** Static methods ***/ daikon.Tag.createId = function (group, element) { var groupStr = daikon.Utils.dec2hex(group), elemStr = daikon.Utils.dec2hex(element); return groupStr + elemStr; }; daikon.Tag.getUnsignedInteger16 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 2; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getUint16(ctr * 2, littleEndian); } return data; }; daikon.Tag.getSignedInteger16 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 2; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getInt16(ctr * 2, littleEndian); } return data; }; daikon.Tag.getFloat32 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 4; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getFloat32(ctr * 4, littleEndian); } return data; }; daikon.Tag.getSignedInteger32 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 4; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getInt32(ctr * 4, littleEndian); } return data; }; daikon.Tag.getUnsignedInteger32 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 4; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getUint32(ctr * 4, littleEndian); } return data; }; daikon.Tag.getFloat64 = function (rawData, littleEndian) { var data, mul, ctr; mul = rawData.byteLength / 8; data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = rawData.getFloat64(ctr * 8, littleEndian); } return data; }; daikon.Tag.getDoubleElscint = function (rawData) { var data = [], reordered = [], ctr; for (ctr = 0; ctr < 8; ctr += 1) { data[ctr] = rawData.getUint8(ctr); } reordered[0] = data[3]; reordered[1] = data[2]; reordered[2] = data[1]; reordered[3] = data[0]; reordered[4] = data[7]; reordered[5] = data[6]; reordered[6] = data[5]; reordered[7] = data[4]; data = [daikon.Utils.bytesToDouble(reordered)]; return data; }; daikon.Tag.getFixedLengthStringValue = function (rawData, maxLength) { var data, mul, ctr; mul = Math.floor(rawData.byteLength / maxLength); data = []; for (ctr = 0; ctr < mul; ctr += 1) { data[ctr] = daikon.Utils.getStringAt(rawData, ctr * maxLength, maxLength); } return data; }; daikon.Tag.getStringValue = function (rawData) { var data = daikon.Utils.getStringAt(rawData, 0, rawData.byteLength).split('\\'), ctr; for (ctr = 0; ctr < data.length; ctr += 1) { data[ctr] = daikon.Utils.trim(data[ctr]); } return data; }; daikon.Tag.getDateStringValue = function (rawData) { var dotFormat = (daikon.Tag.getSingleStringValue(rawData)[0].indexOf('.') !== -1), stringData = daikon.Tag.getFixedLengthStringValue(rawData, dotFormat ? 10 : daikon.Tag.VR_DA_MAX_LENGTH), parts = null, data = [], ctr; for (ctr = 0; ctr < stringData.length; ctr += 1) { if (dotFormat) { parts = stringData[ctr].split('.'); data[ctr] = new Date(daikon.Utils.safeParseInt(parts[0]), daikon.Utils.safeParseInt(parts[1]) - 1, daikon.Utils.safeParseInt(parts[2])); } else if (stringData[ctr].length === 8) { data[ctr] = new Date(daikon.Utils.safeParseInt(stringData[ctr].substring(0, 4)), daikon.Utils.safeParseInt(stringData[ctr].substring(4, 6)) - 1, daikon.Utils.safeParseInt(stringData[ctr].substring(6, 8))); } else { data[ctr] = Date.parse(stringData[ctr]); } } return data; }; daikon.Tag.getDateTimeStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], ctr, year = null, month = null, date = null, hours = null, minutes = null, seconds = null; for (ctr = 0; ctr < stringData.length; ctr += 1) { if (stringData[ctr].length >= 4) { year = parseInt(stringData[ctr].substring(0, 4), 10); // required if (stringData[ctr].length >= 6) { month = daikon.Utils.safeParseInt(stringData[ctr].substring(4, 6)) - 1; } if (stringData[ctr].length >= 8) { date = daikon.Utils.safeParseInt(stringData[ctr].substring(6, 8)); } if (stringData[ctr].length >= 10) { hours = daikon.Utils.safeParseInt(stringData[ctr].substring(8, 10)); } if (stringData[ctr].length >= 12) { minutes = daikon.Utils.safeParseInt(stringData[ctr].substring(10, 12)); } if (stringData[ctr].length >= 14) { seconds = daikon.Utils.safeParseInt(stringData[ctr].substring(12, 14)); } data[ctr] = new Date(year, month, date, hours, minutes, seconds); } else { data[ctr] = Date.parse(stringData[ctr]); } } return data; }; daikon.Tag.getTimeStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], parts = null, ctr, hours = 0, minutes = 0, seconds = 0; for (ctr = 0; ctr < stringData.length; ctr += 1) { if (stringData[ctr].indexOf(':') !== -1) { parts = stringData[ctr].split(':'); hours = daikon.Utils.safeParseInt(parts[0]); if (parts.length > 1) { minutes = daikon.Utils.safeParseInt(parts[1]); } if (parts.length > 2) { seconds = daikon.Utils.safeParseFloat(parts[2]); } } else { if (stringData[ctr].length >= 2) { hours = daikon.Utils.safeParseInt(stringData[ctr].substring(0, 2)); } if (stringData[ctr].length >= 4) { minutes = daikon.Utils.safeParseInt(stringData[ctr].substring(2, 4)); } if (stringData[ctr].length >= 6) { seconds = daikon.Utils.safeParseFloat(stringData[ctr].substring(4)); } } data[ctr] = Math.round((hours * 60 * 60 * 1000) + (minutes * 60 * 1000) + (seconds * 1000)); } return data; }; daikon.Tag.getDoubleStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], ctr; for (ctr = 0; ctr < stringData.length; ctr += 1) { data[ctr] = parseFloat(stringData[ctr]); } return data; }; daikon.Tag.getIntegerStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], ctr; for (ctr = 0; ctr < stringData.length; ctr += 1) { data[ctr] = parseInt(stringData[ctr], 10); } return data; }; daikon.Tag.getSingleStringValue = function (rawData) { return [daikon.Utils.trim(daikon.Utils.getStringAt(rawData, 0, rawData.byteLength))]; }; daikon.Tag.getPersonNameStringValue = function (rawData) { var stringData = daikon.Tag.getStringValue(rawData), data = [], ctr; for (ctr = 0; ctr < stringData.length; ctr += 1) { data[ctr] = stringData[ctr].replace('^', ' '); } return data; }; daikon.Tag.convertValue = function (vr, rawData, littleEndian) { var data = null; if (vr === 'AE') { data = daikon.Tag.getSingleStringValue(rawData, daikon.Tag.VR_AE_MAX_LENGTH); } else if (vr === 'AS') { data = daikon.Tag.getFixedLengthStringValue(rawData, daikon.Tag.VR_AS_MAX_LENGTH); } else if (vr === 'AT') { data = daikon.Tag.getUnsignedInteger16(rawData, littleEndian); } else if (vr === 'CS') { data = daikon.Tag.getStringValue(rawData); } else if (vr === 'DA') { data = daikon.Tag.getDateStringValue(rawData); } else if (vr === 'DS') { data = daikon.Tag.getDoubleStringValue(rawData); } else if (vr === 'DT') { data = daikon.Tag.getDateTimeStringValue(rawData); } else if (vr === 'FL') { data = daikon.Tag.getFloat32(rawData, littleEndian); } else if (vr === 'FD') { data = daikon.Tag.getFloat64(rawData, littleEndian); } else if (vr === 'FE') { // special Elscint double (see dictionary) data = daikon.Tag.getDoubleElscint(rawData, littleEndian); } else if (vr === 'IS') { data = daikon.Tag.getIntegerStringValue(rawData); } else if (vr === 'LO') { data = daikon.Tag.getStringValue(rawData); } else if (vr === 'LT') { data = daikon.Tag.getSingleStringValue(rawData); } else if (vr === 'OB') { data = rawData; } else if (vr === 'OD') { data = rawData; } else if (vr === 'OF') { data = rawData; } else if (vr === 'OW') { data = rawData; } else if (vr === 'PN') { data = daikon.Tag.getPersonNameStringValue(rawData); } else if (vr === 'SH') { data = daikon.Tag.getStringValue(rawData); } else if (vr === 'SL') { data = daikon.Tag.getSignedInteger32(rawData, littleEndian); } else if (vr === 'SQ') { data = null; } else if (vr === 'SS') { data = daikon.Tag.getSignedInteger16(rawData, littleEndian); } else if (vr === 'ST') { data = daikon.Tag.getSingleStringValue(rawData); } else if (vr === 'TM') { data = daikon.Tag.getTimeStringValue(rawData); } else if (vr === 'UI') { data = daikon.Tag.getStringValue(rawData); } else if (vr === 'UL') { data = daikon.Tag.getUnsignedInteger32(rawData, littleEndian); } else if (vr === 'UN') { data = rawData; } else if (vr === 'US') { data = daikon.Tag.getUnsignedInteger16(rawData, littleEndian); } else if (vr === 'UT') { data = daikon.Tag.getSingleStringValue(rawData); } return data; }; /*** Prototype Methods ***/ daikon.Tag.prototype.toString = function (level) { var valueStr = '', ctr, groupStr = daikon.Utils.dec2hex(this.group), elemStr = daikon.Utils.dec2hex(this.element), tagStr = '(' + groupStr + ',' + elemStr + ')', des = '', padding; if (level === undefined) { level = 0; } padding = ""; for (ctr = 0; ctr < level; ctr += 1) { padding += " "; } if (this.sublist) { for (ctr = 0; ctr < this.value.length; ctr += 1) { valueStr += ('\n' + (this.value[ctr].toString(level + 1))); } } else if (this.vr === 'SQ') { valueStr = ''; } else if (this.isPixelData()) { valueStr = ''; } else if (!this.value) { valueStr = ''; } else { valueStr = '[' + this.value + ']'; } if (this.isSublistItem()) { tagStr = "Sequence Item"; } else if (this.isSublistItemDelim()) { tagStr = "Sequence Item Delimiter"; } else if (this.isSequenceDelim()) { tagStr = "Sequence Delimiter"; } else if (this.isPixelData()) { tagStr = "Pixel Data"; } else { des = daikon.Utils.convertCamcelCaseToTitleCase(daikon.Dictionary.getDescription(this.group, this.element)); } return padding + tagStr + ' ' + des + ' ' + valueStr; }; daikon.Tag.prototype.isTransformSyntax = function () { return (this.group === daikon.Tag.TAG_TRANSFER_SYNTAX[0]) && (this.element === daikon.Tag.TAG_TRANSFER_SYNTAX[1]); }; daikon.Tag.prototype.isPixelData = function () { return (this.group === daikon.Tag.TAG_PIXEL_DATA[0]) && (this.element === daikon.Tag.TAG_PIXEL_DATA[1]); }; daikon.Tag.prototype.isSublistItem = function () { return (this.group === daikon.Tag.TAG_SUBLIST_ITEM[0]) && (this.element === daikon.Tag.TAG_SUBLIST_ITEM[1]); }; daikon.Tag.prototype.isSublistItemDelim = function () { return (this.group === daikon.Tag.TAG_SUBLIST_ITEM_DELIM[0]) && (this.element === daikon.Tag.TAG_SUBLIST_ITEM_DELIM[1]); }; daikon.Tag.prototype.isSequenceDelim = function () { return (this.group === daikon.Tag.TAG_SUBLIST_SEQ_DELIM[0]) && (this.element === daikon.Tag.TAG_SUBLIST_SEQ_DELIM[1]); }; daikon.Tag.prototype.isMetaLength = function () { return (this.group === daikon.Tag.TAG_META_LENGTH[0]) && (this.element === daikon.Tag.TAG_META_LENGTH[1]); }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Tag; } /*jslint browser: true, node: true */ /*global require, module */ "use strict"; /*** Imports ***/ var daikon = daikon || {}; daikon.Utils = daikon.Utils || {}; /*** Static methods ***/ daikon.Utils.dec2hex = function (i) { return (i + 0x10000).toString(16).substr(-4).toUpperCase(); }; daikon.Utils.getStringAt = function (dataview, start, length) { var str = "", ctr, ch; for (ctr = 0; ctr < length; ctr += 1) { ch = dataview.getUint8(start + ctr); if (ch !== 0) { str += String.fromCharCode(ch); } } return str; }; daikon.Utils.trim = function (str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); }; daikon.Utils.stripLeadingZeros = function (str) { return str.replace(/^[0]+/g, ""); }; daikon.Utils.safeParseInt = function (str) { str = daikon.Utils.stripLeadingZeros(str); if (str.length > 0) { return parseInt(str, 10); } return 0; }; daikon.Utils.convertCamcelCaseToTitleCase = function (str) { var result = str.replace(/([A-Z][a-z])/g, " $1"); return daikon.Utils.trim(result.charAt(0).toUpperCase() + result.slice(1)); }; daikon.Utils.safeParseFloat = function (str) { str = daikon.Utils.stripLeadingZeros(str); if (str.length > 0) { return parseFloat(str); } return 0; }; // http://stackoverflow.com/questions/8361086/convert-byte-array-to-numbers-in-javascript daikon.Utils.bytesToDouble = function (data) { var sign = (data[0] & 1<<7)>>7; var exponent = (((data[0] & 127) << 4) | (data[1]&(15<<4))>>4); if(exponent == 0) return 0; if(exponent == 0x7ff) return (sign) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; var mul = Math.pow(2,exponent - 1023 - 52); var mantissa = data[7]+ data[6]*Math.pow(2,8*1)+ data[5]*Math.pow(2,8*2)+ data[4]*Math.pow(2,8*3)+ data[3]*Math.pow(2,8*4)+ data[2]*Math.pow(2,8*5)+ (data[1]&15)*Math.pow(2,8*6)+ Math.pow(2,52); return Math.pow(-1,sign)*mantissa*mul; }; daikon.Utils.concatArrayBuffers = function (buffer1, buffer2) { var tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength); tmp.set(new Uint8Array(buffer1), 0); tmp.set(new Uint8Array(buffer2), buffer1.byteLength); return tmp.buffer; }; daikon.Utils.bind = function (scope, fn, args, appendArgs) { if (arguments.length === 2) { return function () { return fn.apply(scope, arguments); }; } var method = fn, slice = Array.prototype.slice; return function () { var callArgs = args || arguments; if (appendArgs === true) { callArgs = slice.call(arguments, 0); callArgs = callArgs.concat(args); } else if (typeof appendArgs === 'number') { callArgs = slice.call(arguments, 0); // copy arguments first Ext.Array.insert(callArgs, appendArgs, args); } return method.apply(scope || window, callArgs); }; }; /*** Exports ***/ var moduleType = typeof module; if ((moduleType !== 'undefined') && module.exports) { module.exports = daikon.Utils; }
new build of daikon
lib/daikon.js
new build of daikon
<ide><path>ib/daikon.js <ide> /*** Imports ***/ <ide> var daikon = daikon || {}; <ide> daikon.Dictionary = daikon.Dictionary || {}; <add>daikon.Utils = daikon.Utils || ((typeof require !== 'undefined') ? require('./utilities.js') : null); <ide> <ide> <ide> /*** Static Pseudo-constants ***/ <ide> <del>daikon.Dictionary.GROUP_INDICES = []; <del>daikon.Dictionary.GROUP_INDICES[0x0002] = 0; <del>daikon.Dictionary.GROUP_INDICES[0x0004] = 10; <del>daikon.Dictionary.GROUP_INDICES[0x0008] = 27; <del>daikon.Dictionary.GROUP_INDICES[0x0010] = 197; <del>daikon.Dictionary.GROUP_INDICES[0x0012] = 248; <del>daikon.Dictionary.GROUP_INDICES[0x0014] = 267; <del>daikon.Dictionary.GROUP_INDICES[0x0018] = 394; <del>daikon.Dictionary.GROUP_INDICES[0x0020] = 1096; <del>daikon.Dictionary.GROUP_INDICES[0x0022] = 1212; <del>daikon.Dictionary.GROUP_INDICES[0x0024] = 1317; <del>daikon.Dictionary.GROUP_INDICES[0x0028] = 1418; <del>daikon.Dictionary.GROUP_INDICES[0x0032] = 1598; <del>daikon.Dictionary.GROUP_INDICES[0x0038] = 1625; <del>daikon.Dictionary.GROUP_INDICES[0x003A] = 1653; <del>daikon.Dictionary.GROUP_INDICES[0x0040] = 1691; <del>daikon.Dictionary.GROUP_INDICES[0x0042] = 1992; <del>daikon.Dictionary.GROUP_INDICES[0x0046] = 2011; <del>daikon.Dictionary.GROUP_INDICES[0x0048] = 2060; <del>daikon.Dictionary.GROUP_INDICES[0x0050] = 2091; <del>daikon.Dictionary.GROUP_INDICES[0x0052] = 2107; <del>daikon.Dictionary.GROUP_INDICES[0x0054] = 2133; <del>daikon.Dictionary.GROUP_INDICES[0x0060] = 2213; <del>daikon.Dictionary.GROUP_INDICES[0x0062] = 2220; <del>daikon.Dictionary.GROUP_INDICES[0x0064] = 2235; <del>daikon.Dictionary.GROUP_INDICES[0x0066] = 2243; <del>daikon.Dictionary.GROUP_INDICES[0x0068] = 2288; <del>daikon.Dictionary.GROUP_INDICES[0x0070] = 2358; <del>daikon.Dictionary.GROUP_INDICES[0x0072] = 2464; <del>daikon.Dictionary.GROUP_INDICES[0x0074] = 2571; <del>daikon.Dictionary.GROUP_INDICES[0x0076] = 2629; <del>daikon.Dictionary.GROUP_INDICES[0x0078] = 2652; <del>daikon.Dictionary.GROUP_INDICES[0x0088] = 2670; <del>daikon.Dictionary.GROUP_INDICES[0x0100] = 2677; <del>daikon.Dictionary.GROUP_INDICES[0x0400] = 2681; <del> <del>daikon.Dictionary.dictPrivate = [ <del> [0x0207,0x101F,"ElscintDataScale","FE"] // uses special Elscint double type (see Tag class) <del>]; <del> <del>daikon.Dictionary.dict = [ <del> [0x0002,0x0000,"Group0002Length","UL"], <del> [0x0002,0x0001,"FileMetaInformationVersion","OB"], <del> [0x0002,0x0002,"MediaStoredSOPClassUID","UI"], <del> [0x0002,0x0003,"MediaStoredSOPInstanceUID","UI"], <del> [0x0002,0x0010,"TransferSyntaxUID","UI"], <del> [0x0002,0x0012,"ImplementationClassUID","UI"], <del> [0x0002,0x0013,"ImplementationVersionName","SH"], <del> [0x0002,0x0016,"SourceApplicationEntityTitle","AE"], <del> [0x0002,0x0100,"PrivateInformationCreatorUID","UI"], <del> [0x0002,0x0102,"PrivateInformation","OB"], <del> [0x0004,0x0000,"Group0004Length","UL"], <del> [0x0004,0x1130,"FilesetID","CS"], <del> [0x0004,0x1141,"FilesetDescriptorFileFileID","CS"], <del> [0x0004,0x1142,"FilesetDescriptorFileFormat","CS"], <del> [0x0004,0x1200,"RootDirectoryEntitysFirstDirectoryRecordOffset","UL"], <del> [0x0004,0x1202,"RootDirectoryEntitysLastDirectoryRecordOffset","UL"], <del> [0x0004,0x1212,"File-setConsistenceFlag","US"], <del> [0x0004,0x1220,"DirectoryRecordSequence","SQ"], <del> [0x0004,0x1400,"NextDirectoryRecordOffset","UL"], <del> [0x0004,0x1410,"RecordInuseFlag","US"], <del> [0x0004,0x1420,"ReferencedLowerlevelDirectoryEntityOffset","UL"], <del> [0x0004,0x1430,"DirectoryRecordType","CS"], <del> [0x0004,0x1432,"PrivateRecordUID","UI"], <del> [0x0004,0x1500,"ReferencedFileID","CS"], <del> [0x0004,0x1510,"ReferencedSOPClassUIDInFile","UI"], <del> [0x0004,0x1511,"ReferencedSOPInstanceUIDInFile","UI"], <del> [0x0004,0x1600,"NumberOfReferences","UL"], <del> [0x0008,0x0001,"LengthToEnd","UL"], <del> [0x0008,0x0005,"SpecificCharacterSet","CS"], <del> [0x0008,0x0006,"LanguageCodeSequence","SQ"], <del> [0x0008,0x0008,"ImageType","CS"], <del> [0x0008,0x0010,"RecognitionCode","SH"], <del> [0x0008,0x0012,"InstanceCreationDate","DA"], <del> [0x0008,0x0013,"InstanceCreationTime","TM"], <del> [0x0008,0x0014,"InstanceCreatorUID","UI"], <del> [0x0008,0x0016,"SOPClassUID","UI"], <del> [0x0008,0x0018,"SOPInstanceUID","UI"], <del> [0x0008,0x001A,"RelatedGeneralSOPClassUID","UI"], <del> [0x0008,0x001B,"OriginalSpecializedSOPClassUID","UI"], <del> [0x0008,0x0020,"StudyDate","DA"], <del> [0x0008,0x0021,"SeriesDate","DA"], <del> [0x0008,0x0022,"AcquisitionDate","DA"], <del> [0x0008,0x0023,"ContentDate","DA"], <del> [0x0008,0x0024,"OverlayDate","DA"], <del> [0x0008,0x0025,"CurveDate","DA"], <del> [0x0008,0x002A,"AcquisitionDateTime","DT"], <del> [0x0008,0x0030,"StudyTime","TM"], <del> [0x0008,0x0031,"SeriesTime","TM"], <del> [0x0008,0x0032,"AcquisitionTime","TM"], <del> [0x0008,0x0033,"ContentTime","TM"], <del> [0x0008,0x0034,"OverlayTime","TM"], <del> [0x0008,0x0035,"CurveTime","TM"], <del> [0x0008,0x0040,"DataSetType","US"], <del> [0x0008,0x0041,"DataSetSubtype","LO"], <del> [0x0008,0x0042,"NuclearMedicineSeriesType","CS"], <del> [0x0008,0x0050,"AccessionNumber","SH"], <del> [0x0008,0x0051,"IssuerOfAccessionNumberSequence","SQ"], <del> [0x0008,0x0052,"QueryRetrieveLevel","CS"], <del> [0x0008,0x0054,"RetrieveAETitle","AE"], <del> [0x0008,0x0056,"InstanceAvailability","CS"], <del> [0x0008,0x0058,"FailedSOPInstanceUIDList","UI"], <del> [0x0008,0x0060,"Modality","CS"], <del> [0x0008,0x0061,"ModalitiesInStudy","CS"], <del> [0x0008,0x0062,"SOPClassesInStudy","UI"], <del> [0x0008,0x0064,"ConversionType","CS"], <del> [0x0008,0x0068,"PresentationIntentType","CS"], <del> [0x0008,0x0070,"Manufacturer","LO"], <del> [0x0008,0x0080,"InstitutionName","LO"], <del> [0x0008,0x0081,"InstitutionAddress","ST"], <del> [0x0008,0x0082,"InstitutionCodeSequence","SQ"], <del> [0x0008,0x0090,"ReferringPhysicianName","PN"], <del> [0x0008,0x0092,"ReferringPhysicianAddress","ST"], <del> [0x0008,0x0094,"ReferringPhysicianTelephoneNumbers","SH"], <del> [0x0008,0x0096,"ReferringPhysicianIdentificationSequence","SQ"], <del> [0x0008,0x0100,"CodeValue","SH"], <del> [0x0008,0x0102,"CodingSchemeDesignator","SH"], <del> [0x0008,0x0103,"CodingSchemeVersion","SH"], <del> [0x0008,0x0104,"CodeMeaning","LO"], <del> [0x0008,0x0105,"MappingResource","CS"], <del> [0x0008,0x0106,"ContextGroupVersion","DT"], <del> [0x0008,0x0107,"ContextGroupLocalVersion","DT"], <del> [0x0008,0x010B,"ContextGroupExtensionFlag","CS"], <del> [0x0008,0x010C,"CodingSchemeUID","UI"], <del> [0x0008,0x010D,"ContextGroupExtensionCreatorUID","UI"], <del> [0x0008,0x010F,"ContextIdentifier","CS"], <del> [0x0008,0x0110,"CodingSchemeIdentificationSequence","SQ"], <del> [0x0008,0x0112,"CodingSchemeRegistry","LO"], <del> [0x0008,0x0114,"CodingSchemeExternalID","ST"], <del> [0x0008,0x0115,"CodingSchemeName","ST"], <del> [0x0008,0x0116,"CodingSchemeResponsibleOrganization","ST"], <del> [0x0008,0x0117,"ContextUID","UI"], <del> [0x0008,0x0201,"TimezoneOffsetFromUTC","SH"], <del> [0x0008,0x1000,"NetworkID","AE"], <del> [0x0008,0x1010,"StationName","SH"], <del> [0x0008,0x1030,"StudyDescription","LO"], <del> [0x0008,0x1032,"ProcedureCodeSequence","SQ"], <del> [0x0008,0x103E,"SeriesDescription","LO"], <del> [0x0008,0x103F,"SeriesDescriptionCodeSequence","SQ"], <del> [0x0008,0x1040,"InstitutionalDepartmentName","LO"], <del> [0x0008,0x1048,"PhysiciansOfRecord","PN"], <del> [0x0008,0x1049,"PhysiciansOfRecordIdentificationSequence","SQ"], <del> [0x0008,0x1050,"PerformingPhysicianName","PN"], <del> [0x0008,0x1052,"PerformingPhysicianIdentificationSequence","SQ"], <del> [0x0008,0x1060,"NameOfPhysiciansReadingStudy","PN"], <del> [0x0008,0x1062,"PhysiciansReadingStudyIdentificationSequence","SQ"], <del> [0x0008,0x1070,"OperatorsName","PN"], <del> [0x0008,0x1072,"OperatorIdentificationSequence","SQ"], <del> [0x0008,0x1080,"AdmittingDiagnosesDescription","LO"], <del> [0x0008,0x1084,"AdmittingDiagnosesCodeSequence","SQ"], <del> [0x0008,0x1090,"ManufacturerModelName","LO"], <del> [0x0008,0x1100,"ReferencedResultsSequence","SQ"], <del> [0x0008,0x1110,"ReferencedStudySequence","SQ"], <del> [0x0008,0x1111,"ReferencedPerformedProcedureStepSequence","SQ"], <del> [0x0008,0x1115,"ReferencedSeriesSequence","SQ"], <del> [0x0008,0x1120,"ReferencedPatientSequence","SQ"], <del> [0x0008,0x1125,"ReferencedVisitSequence","SQ"], <del> [0x0008,0x1130,"ReferencedOverlaySequence","SQ"], <del> [0x0008,0x1134,"ReferencedStereometricInstanceSequence","SQ"], <del> [0x0008,0x113A,"ReferencedWaveformSequence","SQ"], <del> [0x0008,0x1140,"ReferencedImageSequence","SQ"], <del> [0x0008,0x1145,"ReferencedCurveSequence","SQ"], <del> [0x0008,0x114A,"ReferencedInstanceSequence","SQ"], <del> [0x0008,0x114B,"ReferencedRealWorldValueMappingInstanceSequence","SQ"], <del> [0x0008,0x1150,"ReferencedSOPClassUID","UI"], <del> [0x0008,0x1155,"ReferencedSOPInstanceUID","UI"], <del> [0x0008,0x115A,"SOPClassesSupported","UI"], <del> [0x0008,0x1160,"ReferencedFrameNumber","IS"], <del> [0x0008,0x1161,"SimpleFrameList","UL"], <del> [0x0008,0x1162,"CalculatedFrameList","UL"], <del> [0x0008,0x1163,"TimeRange","FD"], <del> [0x0008,0x1164,"FrameExtractionSequence","SQ"], <del> [0x0008,0x1167,"MultiFrameSourceSOPInstanceUID","UI"], <del> [0x0008,0x1195,"TransactionUID","UI"], <del> [0x0008,0x1197,"FailureReason","US"], <del> [0x0008,0x1198,"FailedSOPSequence","SQ"], <del> [0x0008,0x1199,"ReferencedSOPSequence","SQ"], <del> [0x0008,0x1200,"StudiesContainingOtherReferencedInstancesSequence","SQ"], <del> [0x0008,0x1250,"RelatedSeriesSequence","SQ"], <del> [0x0008,0x2110,"LossyImageCompressionRetired","CS"], <del> [0x0008,0x2111,"DerivationDescription","ST"], <del> [0x0008,0x2112,"SourceImageSequence","SQ"], <del> [0x0008,0x2120,"StageName","SH"], <del> [0x0008,0x2122,"StageNumber","IS"], <del> [0x0008,0x2124,"NumberOfStages","IS"], <del> [0x0008,0x2127,"ViewName","SH"], <del> [0x0008,0x2128,"ViewNumber","IS"], <del> [0x0008,0x2129,"NumberOfEventTimers","IS"], <del> [0x0008,0x212A,"NumberOfViewsInStage","IS"], <del> [0x0008,0x2130,"EventElapsedTimes","DS"], <del> [0x0008,0x2132,"EventTimerNames","LO"], <del> [0x0008,0x2133,"EventTimerSequence","SQ"], <del> [0x0008,0x2134,"EventTimeOffset","FD"], <del> [0x0008,0x2135,"EventCodeSequence","SQ"], <del> [0x0008,0x2142,"StartTrim","IS"], <del> [0x0008,0x2143,"StopTrim","IS"], <del> [0x0008,0x2144,"RecommendedDisplayFrameRate","IS"], <del> [0x0008,0x2200,"TransducerPosition","CS"], <del> [0x0008,0x2204,"TransducerOrientation","CS"], <del> [0x0008,0x2208,"AnatomicStructure","CS"], <del> [0x0008,0x2218,"AnatomicRegionSequence","SQ"], <del> [0x0008,0x2220,"AnatomicRegionModifierSequence","SQ"], <del> [0x0008,0x2228,"PrimaryAnatomicStructureSequence","SQ"], <del> [0x0008,0x2229,"AnatomicStructureSpaceOrRegionSequence","SQ"], <del> [0x0008,0x2230,"PrimaryAnatomicStructureModifierSequence","SQ"], <del> [0x0008,0x2240,"TransducerPositionSequence","SQ"], <del> [0x0008,0x2242,"TransducerPositionModifierSequence","SQ"], <del> [0x0008,0x2244,"TransducerOrientationSequence","SQ"], <del> [0x0008,0x2246,"TransducerOrientationModifierSequence","SQ"], <del> [0x0008,0x2251,"AnatomicStructureSpaceOrRegionCodeSequenceTrial","SQ"], <del> [0x0008,0x2253,"AnatomicPortalOfEntranceCodeSequenceTrial","SQ"], <del> [0x0008,0x2255,"AnatomicApproachDirectionCodeSequenceTrial","SQ"], <del> [0x0008,0x2256,"AnatomicPerspectiveDescriptionTrial","ST"], <del> [0x0008,0x2257,"AnatomicPerspectiveCodeSequenceTrial","SQ"], <del> [0x0008,0x2258,"AnatomicLocationOfExaminingInstrumentDescriptionTrial","ST"], <del> [0x0008,0x2259,"AnatomicLocationOfExaminingInstrumentCodeSequenceTrial","SQ"], <del> [0x0008,0x225A,"AnatomicStructureSpaceOrRegionModifierCodeSequenceTrial","SQ"], <del> [0x0008,0x225C,"OnAxisBackgroundAnatomicStructureCodeSequenceTrial","SQ"], <del> [0x0008,0x3001,"AlternateRepresentationSequence","SQ"], <del> [0x0008,0x3010,"IrradiationEventUID","UI"], <del> [0x0008,0x4000,"IdentifyingComments","LT"], <del> [0x0008,0x9007,"FrameType","CS"], <del> [0x0008,0x9092,"ReferencedImageEvidenceSequence","SQ"], <del> [0x0008,0x9121,"ReferencedRawDataSequence","SQ"], <del> [0x0008,0x9123,"CreatorVersionUID","UI"], <del> [0x0008,0x9124,"DerivationImageSequence","SQ"], <del> [0x0008,0x9154,"SourceImageEvidenceSequence","SQ"], <del> [0x0008,0x9205,"PixelPresentation","CS"], <del> [0x0008,0x9206,"VolumetricProperties","CS"], <del> [0x0008,0x9207,"VolumeBasedCalculationTechnique","CS"], <del> [0x0008,0x9208,"ComplexImageComponent","CS"], <del> [0x0008,0x9209,"AcquisitionContrast","CS"], <del> [0x0008,0x9215,"DerivationCodeSequence","SQ"], <del> [0x0008,0x9237,"ReferencedPresentationStateSequence","SQ"], <del> [0x0008,0x9410,"ReferencedOtherPlaneSequence","SQ"], <del> [0x0008,0x9458,"FrameDisplaySequence","SQ"], <del> [0x0008,0x9459,"RecommendedDisplayFrameRateInFloat","FL"], <del> [0x0008,0x9460,"SkipFrameRangeFlag","CS"], <del> [0x0010,0x0010,"PatientName","PN"], <del> [0x0010,0x0020,"PatientID","LO"], <del> [0x0010,0x0021,"IssuerOfPatientID","LO"], <del> [0x0010,0x0022,"TypeOfPatientID","CS"], <del> [0x0010,0x0024,"IssuerOfPatientIDQualifiersSequence","SQ"], <del> [0x0010,0x0030,"PatientBirthDate","DA"], <del> [0x0010,0x0032,"PatientBirthTime","TM"], <del> [0x0010,0x0040,"PatientSex","CS"], <del> [0x0010,0x0050,"PatientInsurancePlanCodeSequence","SQ"], <del> [0x0010,0x0101,"PatientPrimaryLanguageCodeSequence","SQ"], <del> [0x0010,0x0102,"PatientPrimaryLanguageModifierCodeSequence","SQ"], <del> [0x0010,0x1000,"OtherPatientIDs","LO"], <del> [0x0010,0x1001,"OtherPatientNames","PN"], <del> [0x0010,0x1002,"OtherPatientIDsSequence","SQ"], <del> [0x0010,0x1005,"PatientBirthName","PN"], <del> [0x0010,0x1010,"PatientAge","AS"], <del> [0x0010,0x1020,"PatientSize","DS"], <del> [0x0010,0x1021,"PatientSizeCodeSequence","SQ"], <del> [0x0010,0x1030,"PatientWeight","DS"], <del> [0x0010,0x1040,"PatientAddress","LO"], <del> [0x0010,0x1050,"InsurancePlanIdentification","LO"], <del> [0x0010,0x1060,"PatientMotherBirthName","PN"], <del> [0x0010,0x1080,"MilitaryRank","LO"], <del> [0x0010,0x1081,"BranchOfService","LO"], <del> [0x0010,0x1090,"MedicalRecordLocator","LO"], <del> [0x0010,0x2000,"MedicalAlerts","LO"], <del> [0x0010,0x2110,"Allergies","LO"], <del> [0x0010,0x2150,"CountryOfResidence","LO"], <del> [0x0010,0x2152,"RegionOfResidence","LO"], <del> [0x0010,0x2154,"PatientTelephoneNumbers","SH"], <del> [0x0010,0x2160,"EthnicGroup","SH"], <del> [0x0010,0x2180,"Occupation","SH"], <del> [0x0010,0x21A0,"SmokingStatus","CS"], <del> [0x0010,0x21B0,"AdditionalPatientHistory","LT"], <del> [0x0010,0x21C0,"PregnancyStatus","US"], <del> [0x0010,0x21D0,"LastMenstrualDate","DA"], <del> [0x0010,0x21F0,"PatientReligiousPreference","LO"], <del> [0x0010,0x2201,"PatientSpeciesDescription","LO"], <del> [0x0010,0x2202,"PatientSpeciesCodeSequence","SQ"], <del> [0x0010,0x2203,"PatientSexNeutered","CS"], <del> [0x0010,0x2210,"AnatomicalOrientationType","CS"], <del> [0x0010,0x2292,"PatientBreedDescription","LO"], <del> [0x0010,0x2293,"PatientBreedCodeSequence","SQ"], <del> [0x0010,0x2294,"BreedRegistrationSequence","SQ"], <del> [0x0010,0x2295,"BreedRegistrationNumber","LO"], <del> [0x0010,0x2296,"BreedRegistryCodeSequence","SQ"], <del> [0x0010,0x2297,"ResponsiblePerson","PN"], <del> [0x0010,0x2298,"ResponsiblePersonRole","CS"], <del> [0x0010,0x2299,"ResponsibleOrganization","LO"], <del> [0x0010,0x4000,"PatientComments","LT"], <del> [0x0010,0x9431,"ExaminedBodyThickness","FL"], <del> [0x0012,0x0010,"ClinicalTrialSponsorName","LO"], <del> [0x0012,0x0020,"ClinicalTrialProtocolID","LO"], <del> [0x0012,0x0021,"ClinicalTrialProtocolName","LO"], <del> [0x0012,0x0030,"ClinicalTrialSiteID","LO"], <del> [0x0012,0x0031,"ClinicalTrialSiteName","LO"], <del> [0x0012,0x0040,"ClinicalTrialSubjectID","LO"], <del> [0x0012,0x0042,"ClinicalTrialSubjectReadingID","LO"], <del> [0x0012,0x0050,"ClinicalTrialTimePointID","LO"], <del> [0x0012,0x0051,"ClinicalTrialTimePointDescription","ST"], <del> [0x0012,0x0060,"ClinicalTrialCoordinatingCenterName","LO"], <del> [0x0012,0x0062,"PatientIdentityRemoved","CS"], <del> [0x0012,0x0063,"DeidentificationMethod","LO"], <del> [0x0012,0x0064,"DeidentificationMethodCodeSequence","SQ"], <del> [0x0012,0x0071,"ClinicalTrialSeriesID","LO"], <del> [0x0012,0x0072,"ClinicalTrialSeriesDescription","LO"], <del> [0x0012,0x0081,"ClinicalTrialProtocolEthicsCommitteeName","LO"], <del> [0x0012,0x0082,"ClinicalTrialProtocolEthicsCommitteeApprovalNumber","LO"], <del> [0x0012,0x0083,"ConsentForClinicalTrialUseSequence","SQ"], <del> [0x0012,0x0084,"DistributionType","CS"], <del> [0x0012,0x0085,"ConsentForDistributionFlag","CS"], <del> [0x0014,0x0023,"CADFileFormat","ST"], <del> [0x0014,0x0024,"ComponentReferenceSystem","ST"], <del> [0x0014,0x0025,"ComponentManufacturingProcedure","ST"], <del> [0x0014,0x0028,"ComponentManufacturer","ST"], <del> [0x0014,0x0030,"MaterialThickness","DS"], <del> [0x0014,0x0032,"MaterialPipeDiameter","DS"], <del> [0x0014,0x0034,"MaterialIsolationDiameter","DS"], <del> [0x0014,0x0042,"MaterialGrade","ST"], <del> [0x0014,0x0044,"MaterialPropertiesFileID","ST"], <del> [0x0014,0x0045,"MaterialPropertiesFileFormat","ST"], <del> [0x0014,0x0046,"MaterialNotes","LT"], <del> [0x0014,0x0050,"ComponentShape","CS"], <del> [0x0014,0x0052,"CurvatureType","CS"], <del> [0x0014,0x0054,"OuterDiameter","DS"], <del> [0x0014,0x0056,"InnerDiameter","DS"], <del> [0x0014,0x1010,"ActualEnvironmentalConditions","ST"], <del> [0x0014,0x1020,"ExpiryDate","DA"], <del> [0x0014,0x1040,"EnvironmentalConditions","ST"], <del> [0x0014,0x2002,"EvaluatorSequence","SQ"], <del> [0x0014,0x2004,"EvaluatorNumber","IS"], <del> [0x0014,0x2006,"EvaluatorName","PN"], <del> [0x0014,0x2008,"EvaluationAttempt","IS"], <del> [0x0014,0x2012,"IndicationSequence","SQ"], <del> [0x0014,0x2014,"IndicationNumber ","IS"], <del> [0x0014,0x2016,"IndicationLabel","SH"], <del> [0x0014,0x2018,"IndicationDescription","ST"], <del> [0x0014,0x201A,"IndicationType","CS"], <del> [0x0014,0x201C,"IndicationDisposition","CS"], <del> [0x0014,0x201E,"IndicationROISequence","SQ"], <del> [0x0014,0x2030,"IndicationPhysicalPropertySequence","SQ"], <del> [0x0014,0x2032,"PropertyLabel","SH"], <del> [0x0014,0x2202,"CoordinateSystemNumberOfAxes ","IS"], <del> [0x0014,0x2204,"CoordinateSystemAxesSequence","SQ"], <del> [0x0014,0x2206,"CoordinateSystemAxisDescription","ST"], <del> [0x0014,0x2208,"CoordinateSystemDataSetMapping","CS"], <del> [0x0014,0x220A,"CoordinateSystemAxisNumber","IS"], <del> [0x0014,0x220C,"CoordinateSystemAxisType","CS"], <del> [0x0014,0x220E,"CoordinateSystemAxisUnits","CS"], <del> [0x0014,0x2210,"CoordinateSystemAxisValues","OB"], <del> [0x0014,0x2220,"CoordinateSystemTransformSequence","SQ"], <del> [0x0014,0x2222,"TransformDescription","ST"], <del> [0x0014,0x2224,"TransformNumberOfAxes","IS"], <del> [0x0014,0x2226,"TransformOrderOfAxes","IS"], <del> [0x0014,0x2228,"TransformedAxisUnits","CS"], <del> [0x0014,0x222A,"CoordinateSystemTransformRotationAndScaleMatrix","DS"], <del> [0x0014,0x222C,"CoordinateSystemTransformTranslationMatrix","DS"], <del> [0x0014,0x3011,"InternalDetectorFrameTime","DS"], <del> [0x0014,0x3012,"NumberOfFramesIntegrated","DS"], <del> [0x0014,0x3020,"DetectorTemperatureSequence","SQ"], <del> [0x0014,0x3022,"SensorName","DS"], <del> [0x0014,0x3024,"HorizontalOffsetOfSensor","DS"], <del> [0x0014,0x3026,"VerticalOffsetOfSensor","DS"], <del> [0x0014,0x3028,"SensorTemperature","DS"], <del> [0x0014,0x3040,"DarkCurrentSequence","SQ"], <del> [0x0014,0x3050,"DarkCurrentCounts","OB"], <del> [0x0014,0x3060,"GainCorrectionReferenceSequence","SQ"], <del> [0x0014,0x3070,"AirCounts","OB"], <del> [0x0014,0x3071,"KVUsedInGainCalibration","DS"], <del> [0x0014,0x3072,"MAUsedInGainCalibration","DS"], <del> [0x0014,0x3073,"NumberOfFramesUsedForIntegration","DS"], <del> [0x0014,0x3074,"FilterMaterialUsedInGainCalibration","LO"], <del> [0x0014,0x3075,"FilterThicknessUsedInGainCalibration","DS"], <del> [0x0014,0x3076,"DateOfGainCalibration","DA"], <del> [0x0014,0x3077,"TimeOfGainCalibration","TM"], <del> [0x0014,0x3080,"BadPixelImage","OB"], <del> [0x0014,0x3099,"CalibrationNotes","LT"], <del> [0x0014,0x4002,"PulserEquipmentSequence","SQ"], <del> [0x0014,0x4004,"PulserType","CS"], <del> [0x0014,0x4006,"PulserNotes","LT"], <del> [0x0014,0x4008,"ReceiverEquipmentSequence","SQ"], <del> [0x0014,0x400A,"AmplifierType","CS"], <del> [0x0014,0x400C,"ReceiverNotes","LT"], <del> [0x0014,0x400E,"PreAmplifierEquipmentSequence","SQ"], <del> [0x0014,0x400F,"PreAmplifierNotes","LT"], <del> [0x0014,0x4010,"TransmitTransducerSequence","SQ"], <del> [0x0014,0x4011,"ReceiveTransducerSequence","SQ"], <del> [0x0014,0x4012,"NumberOfElements","US"], <del> [0x0014,0x4013,"ElementShape","CS"], <del> [0x0014,0x4014,"ElementDimensionA","DS"], <del> [0x0014,0x4015,"ElementDimensionB","DS"], <del> [0x0014,0x4016,"ElementPitch","DS"], <del> [0x0014,0x4017,"MeasuredBeamDimensionA","DS"], <del> [0x0014,0x4018,"MeasuredBeamDimensionB","DS"], <del> [0x0014,0x4019,"LocationOfMeasuredBeamDiameter","DS"], <del> [0x0014,0x401A,"NominalFrequency","DS"], <del> [0x0014,0x401B,"MeasuredCenterFrequency","DS"], <del> [0x0014,0x401C,"MeasuredBandwidth","DS"], <del> [0x0014,0x4020,"PulserSettingsSequence","SQ"], <del> [0x0014,0x4022,"PulseWidth","DS"], <del> [0x0014,0x4024,"ExcitationFrequency","DS"], <del> [0x0014,0x4026,"ModulationType","CS"], <del> [0x0014,0x4028,"Damping","DS"], <del> [0x0014,0x4030,"ReceiverSettingsSequence","SQ"], <del> [0x0014,0x4031,"AcquiredSoundpathLength","DS"], <del> [0x0014,0x4032,"AcquisitionCompressionType","CS"], <del> [0x0014,0x4033,"AcquisitionSampleSize","IS"], <del> [0x0014,0x4034,"RectifierSmoothing","DS"], <del> [0x0014,0x4035,"DACSequence","SQ"], <del> [0x0014,0x4036,"DACType","CS"], <del> [0x0014,0x4038,"DACGainPoints","DS"], <del> [0x0014,0x403A,"DACTimePoints","DS"], <del> [0x0014,0x403C,"DACAmplitude","DS"], <del> [0x0014,0x4040,"PreAmplifierSettingsSequence","SQ"], <del> [0x0014,0x4050,"TransmitTransducerSettingsSequence","SQ"], <del> [0x0014,0x4051,"ReceiveTransducerSettingsSequence","SQ"], <del> [0x0014,0x4052,"IncidentAngle","DS"], <del> [0x0014,0x4054,"CouplingTechnique","ST"], <del> [0x0014,0x4056,"CouplingMedium","ST"], <del> [0x0014,0x4057,"CouplingVelocity","DS"], <del> [0x0014,0x4058,"CrystalCenterLocationX","DS"], <del> [0x0014,0x4059,"CrystalCenterLocationZ","DS"], <del> [0x0014,0x405A,"SoundPathLength","DS"], <del> [0x0014,0x405C,"DelayLawIdentifier","ST"], <del> [0x0014,0x4060,"GateSettingsSequence","SQ"], <del> [0x0014,0x4062,"GateThreshold","DS"], <del> [0x0014,0x4064,"VelocityOfSound","DS"], <del> [0x0014,0x4070,"CalibrationSettingsSequence","SQ"], <del> [0x0014,0x4072,"CalibrationProcedure","ST"], <del> [0x0014,0x4074,"ProcedureVersion","SH"], <del> [0x0014,0x4076,"ProcedureCreationDate","DA"], <del> [0x0014,0x4078,"ProcedureExpirationDate","DA"], <del> [0x0014,0x407A,"ProcedureLastModifiedDate","DA"], <del> [0x0014,0x407C,"CalibrationTime","TM"], <del> [0x0014,0x407E,"CalibrationDate","DA"], <del> [0x0014,0x5002,"LINACEnergy","IS"], <del> [0x0014,0x5004,"LINACOutput","IS"], <del> [0x0018,0x0010,"ContrastBolusAgent","LO"], <del> [0x0018,0x0012,"ContrastBolusAgentSequence","SQ"], <del> [0x0018,0x0014,"ContrastBolusAdministrationRouteSequence","SQ"], <del> [0x0018,0x0015,"BodyPartExamined","CS"], <del> [0x0018,0x0020,"ScanningSequence","CS"], <del> [0x0018,0x0021,"SequenceVariant","CS"], <del> [0x0018,0x0022,"ScanOptions","CS"], <del> [0x0018,0x0023,"MRAcquisitionType","CS"], <del> [0x0018,0x0024,"SequenceName","SH"], <del> [0x0018,0x0025,"AngioFlag","CS"], <del> [0x0018,0x0026,"InterventionDrugInformationSequence","SQ"], <del> [0x0018,0x0027,"InterventionDrugStopTime","TM"], <del> [0x0018,0x0028,"InterventionDrugDose","DS"], <del> [0x0018,0x0029,"InterventionDrugCodeSequence","SQ"], <del> [0x0018,0x002A,"AdditionalDrugSequence","SQ"], <del> [0x0018,0x0030,"Radionuclide","LO"], <del> [0x0018,0x0031,"Radiopharmaceutical","LO"], <del> [0x0018,0x0032,"EnergyWindowCenterline","DS"], <del> [0x0018,0x0033,"EnergyWindowTotalWidth","DS"], <del> [0x0018,0x0034,"InterventionDrugName","LO"], <del> [0x0018,0x0035,"InterventionDrugStartTime","TM"], <del> [0x0018,0x0036,"InterventionSequence","SQ"], <del> [0x0018,0x0037,"TherapyType","CS"], <del> [0x0018,0x0038,"InterventionStatus","CS"], <del> [0x0018,0x0039,"TherapyDescription","CS"], <del> [0x0018,0x003A,"InterventionDescription","ST"], <del> [0x0018,0x0040,"CineRate","IS"], <del> [0x0018,0x0042,"InitialCineRunState","CS"], <del> [0x0018,0x0050,"SliceThickness","DS"], <del> [0x0018,0x0060,"KVP","DS"], <del> [0x0018,0x0070,"CountsAccumulated","IS"], <del> [0x0018,0x0071,"AcquisitionTerminationCondition","CS"], <del> [0x0018,0x0072,"EffectiveDuration","DS"], <del> [0x0018,0x0073,"AcquisitionStartCondition","CS"], <del> [0x0018,0x0074,"AcquisitionStartConditionData","IS"], <del> [0x0018,0x0075,"AcquisitionTerminationConditionData","IS"], <del> [0x0018,0x0080,"RepetitionTime","DS"], <del> [0x0018,0x0081,"EchoTime","DS"], <del> [0x0018,0x0082,"InversionTime","DS"], <del> [0x0018,0x0083,"NumberOfAverages","DS"], <del> [0x0018,0x0084,"ImagingFrequency","DS"], <del> [0x0018,0x0085,"ImagedNucleus","SH"], <del> [0x0018,0x0086,"EchoNumbers","IS"], <del> [0x0018,0x0087,"MagneticFieldStrength","DS"], <del> [0x0018,0x0088,"SpacingBetweenSlices","DS"], <del> [0x0018,0x0089,"NumberOfPhaseEncodingSteps","IS"], <del> [0x0018,0x0090,"DataCollectionDiameter","DS"], <del> [0x0018,0x0091,"EchoTrainLength","IS"], <del> [0x0018,0x0093,"PercentSampling","DS"], <del> [0x0018,0x0094,"PercentPhaseFieldOfView","DS"], <del> [0x0018,0x0095,"PixelBandwidth","DS"], <del> [0x0018,0x1000,"DeviceSerialNumber","LO"], <del> [0x0018,0x1002,"DeviceUID","UI"], <del> [0x0018,0x1003,"DeviceID","LO"], <del> [0x0018,0x1004,"PlateID","LO"], <del> [0x0018,0x1005,"GeneratorID","LO"], <del> [0x0018,0x1006,"GridID","LO"], <del> [0x0018,0x1007,"CassetteID","LO"], <del> [0x0018,0x1008,"GantryID","LO"], <del> [0x0018,0x1010,"SecondaryCaptureDeviceID","LO"], <del> [0x0018,0x1011,"HardcopyCreationDeviceID","LO"], <del> [0x0018,0x1012,"DateOfSecondaryCapture","DA"], <del> [0x0018,0x1014,"TimeOfSecondaryCapture","TM"], <del> [0x0018,0x1016,"SecondaryCaptureDeviceManufacturer","LO"], <del> [0x0018,0x1017,"HardcopyDeviceManufacturer","LO"], <del> [0x0018,0x1018,"SecondaryCaptureDeviceManufacturerModelName","LO"], <del> [0x0018,0x1019,"SecondaryCaptureDeviceSoftwareVersions","LO"], <del> [0x0018,0x101A,"HardcopyDeviceSoftwareVersion","LO"], <del> [0x0018,0x101B,"HardcopyDeviceManufacturerModelName","LO"], <del> [0x0018,0x1020,"SoftwareVersions","LO"], <del> [0x0018,0x1022,"VideoImageFormatAcquired","SH"], <del> [0x0018,0x1023,"DigitalImageFormatAcquired","LO"], <del> [0x0018,0x1030,"ProtocolName","LO"], <del> [0x0018,0x1040,"ContrastBolusRoute","LO"], <del> [0x0018,0x1041,"ContrastBolusVolume","DS"], <del> [0x0018,0x1042,"ContrastBolusStartTime","TM"], <del> [0x0018,0x1043,"ContrastBolusStopTime","TM"], <del> [0x0018,0x1044,"ContrastBolusTotalDose","DS"], <del> [0x0018,0x1045,"SyringeCounts","IS"], <del> [0x0018,0x1046,"ContrastFlowRate","DS"], <del> [0x0018,0x1047,"ContrastFlowDuration","DS"], <del> [0x0018,0x1048,"ContrastBolusIngredient","CS"], <del> [0x0018,0x1049,"ContrastBolusIngredientConcentration","DS"], <del> [0x0018,0x1050,"SpatialResolution","DS"], <del> [0x0018,0x1060,"TriggerTime","DS"], <del> [0x0018,0x1061,"TriggerSourceOrType","LO"], <del> [0x0018,0x1062,"NominalInterval","IS"], <del> [0x0018,0x1063,"FrameTime","DS"], <del> [0x0018,0x1064,"CardiacFramingType","LO"], <del> [0x0018,0x1065,"FrameTimeVector","DS"], <del> [0x0018,0x1066,"FrameDelay","DS"], <del> [0x0018,0x1067,"ImageTriggerDelay","DS"], <del> [0x0018,0x1068,"MultiplexGroupTimeOffset","DS"], <del> [0x0018,0x1069,"TriggerTimeOffset","DS"], <del> [0x0018,0x106A,"SynchronizationTrigger","CS"], <del> [0x0018,0x106C,"SynchronizationChannel","US"], <del> [0x0018,0x106E,"TriggerSamplePosition","UL"], <del> [0x0018,0x1070,"RadiopharmaceuticalRoute","LO"], <del> [0x0018,0x1071,"RadiopharmaceuticalVolume","DS"], <del> [0x0018,0x1072,"RadiopharmaceuticalStartTime","TM"], <del> [0x0018,0x1073,"RadiopharmaceuticalStopTime","TM"], <del> [0x0018,0x1074,"RadionuclideTotalDose","DS"], <del> [0x0018,0x1075,"RadionuclideHalfLife","DS"], <del> [0x0018,0x1076,"RadionuclidePositronFraction","DS"], <del> [0x0018,0x1077,"RadiopharmaceuticalSpecificActivity","DS"], <del> [0x0018,0x1078,"RadiopharmaceuticalStartDateTime","DT"], <del> [0x0018,0x1079,"RadiopharmaceuticalStopDateTime","DT"], <del> [0x0018,0x1080,"BeatRejectionFlag","CS"], <del> [0x0018,0x1081,"LowRRValue","IS"], <del> [0x0018,0x1082,"HighRRValue","IS"], <del> [0x0018,0x1083,"IntervalsAcquired","IS"], <del> [0x0018,0x1084,"IntervalsRejected","IS"], <del> [0x0018,0x1085,"PVCRejection","LO"], <del> [0x0018,0x1086,"SkipBeats","IS"], <del> [0x0018,0x1088,"HeartRate","IS"], <del> [0x0018,0x1090,"CardiacNumberOfImages","IS"], <del> [0x0018,0x1094,"TriggerWindow","IS"], <del> [0x0018,0x1100,"ReconstructionDiameter","DS"], <del> [0x0018,0x1110,"DistanceSourceToDetector","DS"], <del> [0x0018,0x1111,"DistanceSourceToPatient","DS"], <del> [0x0018,0x1114,"EstimatedRadiographicMagnificationFactor","DS"], <del> [0x0018,0x1120,"GantryDetectorTilt","DS"], <del> [0x0018,0x1121,"GantryDetectorSlew","DS"], <del> [0x0018,0x1130,"TableHeight","DS"], <del> [0x0018,0x1131,"TableTraverse","DS"], <del> [0x0018,0x1134,"TableMotion","CS"], <del> [0x0018,0x1135,"TableVerticalIncrement","DS"], <del> [0x0018,0x1136,"TableLateralIncrement","DS"], <del> [0x0018,0x1137,"TableLongitudinalIncrement","DS"], <del> [0x0018,0x1138,"TableAngle","DS"], <del> [0x0018,0x113A,"TableType","CS"], <del> [0x0018,0x1140,"RotationDirection","CS"], <del> [0x0018,0x1141,"AngularPosition","DS"], <del> [0x0018,0x1142,"RadialPosition","DS"], <del> [0x0018,0x1143,"ScanArc","DS"], <del> [0x0018,0x1144,"AngularStep","DS"], <del> [0x0018,0x1145,"CenterOfRotationOffset","DS"], <del> [0x0018,0x1146,"RotationOffset","DS"], <del> [0x0018,0x1147,"FieldOfViewShape","CS"], <del> [0x0018,0x1149,"FieldOfViewDimensions","IS"], <del> [0x0018,0x1150,"ExposureTime","IS"], <del> [0x0018,0x1151,"XRayTubeCurrent","IS"], <del> [0x0018,0x1152,"Exposure","IS"], <del> [0x0018,0x1153,"ExposureInuAs","IS"], <del> [0x0018,0x1154,"AveragePulseWidth","DS"], <del> [0x0018,0x1155,"RadiationSetting","CS"], <del> [0x0018,0x1156,"RectificationType","CS"], <del> [0x0018,0x115A,"RadiationMode","CS"], <del> [0x0018,0x115E,"ImageAndFluoroscopyAreaDoseProduct","DS"], <del> [0x0018,0x1160,"FilterType","SH"], <del> [0x0018,0x1161,"TypeOfFilters","LO"], <del> [0x0018,0x1162,"IntensifierSize","DS"], <del> [0x0018,0x1164,"ImagerPixelSpacing","DS"], <del> [0x0018,0x1166,"Grid","CS"], <del> [0x0018,0x1170,"GeneratorPower","IS"], <del> [0x0018,0x1180,"CollimatorGridName","SH"], <del> [0x0018,0x1181,"CollimatorType","CS"], <del> [0x0018,0x1182,"FocalDistance","IS"], <del> [0x0018,0x1183,"XFocusCenter","DS"], <del> [0x0018,0x1184,"YFocusCenter","DS"], <del> [0x0018,0x1190,"FocalSpots","DS"], <del> [0x0018,0x1191,"AnodeTargetMaterial","CS"], <del> [0x0018,0x11A0,"BodyPartThickness","DS"], <del> [0x0018,0x11A2,"CompressionForce","DS"], <del> [0x0018,0x1200,"DateOfLastCalibration","DA"], <del> [0x0018,0x1201,"TimeOfLastCalibration","TM"], <del> [0x0018,0x1210,"ConvolutionKernel","SH"], <del> [0x0018,0x1240,"UpperLowerPixelValues","IS"], <del> [0x0018,0x1242,"ActualFrameDuration","IS"], <del> [0x0018,0x1243,"CountRate","IS"], <del> [0x0018,0x1244,"PreferredPlaybackSequencing","US"], <del> [0x0018,0x1250,"ReceiveCoilName","SH"], <del> [0x0018,0x1251,"TransmitCoilName","SH"], <del> [0x0018,0x1260,"PlateType","SH"], <del> [0x0018,0x1261,"PhosphorType","LO"], <del> [0x0018,0x1300,"ScanVelocity","DS"], <del> [0x0018,0x1301,"WholeBodyTechnique","CS"], <del> [0x0018,0x1302,"ScanLength","IS"], <del> [0x0018,0x1310,"AcquisitionMatrix","US"], <del> [0x0018,0x1312,"InPlanePhaseEncodingDirection","CS"], <del> [0x0018,0x1314,"FlipAngle","DS"], <del> [0x0018,0x1315,"VariableFlipAngleFlag","CS"], <del> [0x0018,0x1316,"SAR","DS"], <del> [0x0018,0x1318,"dBdt","DS"], <del> [0x0018,0x1400,"AcquisitionDeviceProcessingDescription","LO"], <del> [0x0018,0x1401,"AcquisitionDeviceProcessingCode","LO"], <del> [0x0018,0x1402,"CassetteOrientation","CS"], <del> [0x0018,0x1403,"CassetteSize","CS"], <del> [0x0018,0x1404,"ExposuresOnPlate","US"], <del> [0x0018,0x1405,"RelativeXRayExposure","IS"], <del> [0x0018,0x1411,"ExposureIndex","DS"], <del> [0x0018,0x1412,"TargetExposureIndex","DS"], <del> [0x0018,0x1413,"DeviationIndex","DS"], <del> [0x0018,0x1450,"ColumnAngulation","DS"], <del> [0x0018,0x1460,"TomoLayerHeight","DS"], <del> [0x0018,0x1470,"TomoAngle","DS"], <del> [0x0018,0x1480,"TomoTime","DS"], <del> [0x0018,0x1490,"TomoType","CS"], <del> [0x0018,0x1491,"TomoClass","CS"], <del> [0x0018,0x1495,"NumberOfTomosynthesisSourceImages","IS"], <del> [0x0018,0x1500,"PositionerMotion","CS"], <del> [0x0018,0x1508,"PositionerType","CS"], <del> [0x0018,0x1510,"PositionerPrimaryAngle","DS"], <del> [0x0018,0x1511,"PositionerSecondaryAngle","DS"], <del> [0x0018,0x1520,"PositionerPrimaryAngleIncrement","DS"], <del> [0x0018,0x1521,"PositionerSecondaryAngleIncrement","DS"], <del> [0x0018,0x1530,"DetectorPrimaryAngle","DS"], <del> [0x0018,0x1531,"DetectorSecondaryAngle","DS"], <del> [0x0018,0x1600,"ShutterShape","CS"], <del> [0x0018,0x1602,"ShutterLeftVerticalEdge","IS"], <del> [0x0018,0x1604,"ShutterRightVerticalEdge","IS"], <del> [0x0018,0x1606,"ShutterUpperHorizontalEdge","IS"], <del> [0x0018,0x1608,"ShutterLowerHorizontalEdge","IS"], <del> [0x0018,0x1610,"CenterOfCircularShutter","IS"], <del> [0x0018,0x1612,"RadiusOfCircularShutter","IS"], <del> [0x0018,0x1620,"VerticesOfThePolygonalShutter","IS"], <del> [0x0018,0x1622,"ShutterPresentationValue","US"], <del> [0x0018,0x1623,"ShutterOverlayGroup","US"], <del> [0x0018,0x1624,"ShutterPresentationColorCIELabValue","US"], <del> [0x0018,0x1700,"CollimatorShape","CS"], <del> [0x0018,0x1702,"CollimatorLeftVerticalEdge","IS"], <del> [0x0018,0x1704,"CollimatorRightVerticalEdge","IS"], <del> [0x0018,0x1706,"CollimatorUpperHorizontalEdge","IS"], <del> [0x0018,0x1708,"CollimatorLowerHorizontalEdge","IS"], <del> [0x0018,0x1710,"CenterOfCircularCollimator","IS"], <del> [0x0018,0x1712,"RadiusOfCircularCollimator","IS"], <del> [0x0018,0x1720,"VerticesOfThePolygonalCollimator","IS"], <del> [0x0018,0x1800,"AcquisitionTimeSynchronized","CS"], <del> [0x0018,0x1801,"TimeSource","SH"], <del> [0x0018,0x1802,"TimeDistributionProtocol","CS"], <del> [0x0018,0x1803,"NTPSourceAddress","LO"], <del> [0x0018,0x2001,"PageNumberVector","IS"], <del> [0x0018,0x2002,"FrameLabelVector","SH"], <del> [0x0018,0x2003,"FramePrimaryAngleVector","DS"], <del> [0x0018,0x2004,"FrameSecondaryAngleVector","DS"], <del> [0x0018,0x2005,"SliceLocationVector","DS"], <del> [0x0018,0x2006,"DisplayWindowLabelVector","SH"], <del> [0x0018,0x2010,"NominalScannedPixelSpacing","DS"], <del> [0x0018,0x2020,"DigitizingDeviceTransportDirection","CS"], <del> [0x0018,0x2030,"RotationOfScannedFilm","DS"], <del> [0x0018,0x3100,"IVUSAcquisition","CS"], <del> [0x0018,0x3101,"IVUSPullbackRate","DS"], <del> [0x0018,0x3102,"IVUSGatedRate","DS"], <del> [0x0018,0x3103,"IVUSPullbackStartFrameNumber","IS"], <del> [0x0018,0x3104,"IVUSPullbackStopFrameNumber","IS"], <del> [0x0018,0x3105,"LesionNumber","IS"], <del> [0x0018,0x4000,"AcquisitionComments","LT"], <del> [0x0018,0x5000,"OutputPower","SH"], <del> [0x0018,0x5010,"TransducerData","LO"], <del> [0x0018,0x5012,"FocusDepth","DS"], <del> [0x0018,0x5020,"ProcessingFunction","LO"], <del> [0x0018,0x5021,"PostprocessingFunction","LO"], <del> [0x0018,0x5022,"MechanicalIndex","DS"], <del> [0x0018,0x5024,"BoneThermalIndex","DS"], <del> [0x0018,0x5026,"CranialThermalIndex","DS"], <del> [0x0018,0x5027,"SoftTissueThermalIndex","DS"], <del> [0x0018,0x5028,"SoftTissueFocusThermalIndex","DS"], <del> [0x0018,0x5029,"SoftTissueSurfaceThermalIndex","DS"], <del> [0x0018,0x5030,"DynamicRange","DS"], <del> [0x0018,0x5040,"TotalGain","DS"], <del> [0x0018,0x5050,"DepthOfScanField","IS"], <del> [0x0018,0x5100,"PatientPosition","CS"], <del> [0x0018,0x5101,"ViewPosition","CS"], <del> [0x0018,0x5104,"ProjectionEponymousNameCodeSequence","SQ"], <del> [0x0018,0x5210,"ImageTransformationMatrix","DS"], <del> [0x0018,0x5212,"ImageTranslationVector","DS"], <del> [0x0018,0x6000,"Sensitivity","DS"], <del> [0x0018,0x6011,"SequenceOfUltrasoundRegions","SQ"], <del> [0x0018,0x6012,"RegionSpatialFormat","US"], <del> [0x0018,0x6014,"RegionDataType","US"], <del> [0x0018,0x6016,"RegionFlags","UL"], <del> [0x0018,0x6018,"RegionLocationMinX0","UL"], <del> [0x0018,0x601A,"RegionLocationMinY0","UL"], <del> [0x0018,0x601C,"RegionLocationMaxX1","UL"], <del> [0x0018,0x601E,"RegionLocationMaxY1","UL"], <del> [0x0018,0x6020,"ReferencePixelX0","SL"], <del> [0x0018,0x6022,"ReferencePixelY0","SL"], <del> [0x0018,0x6024,"PhysicalUnitsXDirection","US"], <del> [0x0018,0x6026,"PhysicalUnitsYDirection","US"], <del> [0x0018,0x6028,"ReferencePixelPhysicalValueX","FD"], <del> [0x0018,0x602A,"ReferencePixelPhysicalValueY","FD"], <del> [0x0018,0x602C,"PhysicalDeltaX","FD"], <del> [0x0018,0x602E,"PhysicalDeltaY","FD"], <del> [0x0018,0x6030,"TransducerFrequency","UL"], <del> [0x0018,0x6031,"TransducerType","CS"], <del> [0x0018,0x6032,"PulseRepetitionFrequency","UL"], <del> [0x0018,0x6034,"DopplerCorrectionAngle","FD"], <del> [0x0018,0x6036,"SteeringAngle","FD"], <del> [0x0018,0x6038,"DopplerSampleVolumeXPositionRetired","UL"], <del> [0x0018,0x6039,"DopplerSampleVolumeXPosition","SL"], <del> [0x0018,0x603A,"DopplerSampleVolumeYPositionRetired","UL"], <del> [0x0018,0x603B,"DopplerSampleVolumeYPosition","SL"], <del> [0x0018,0x603C,"TMLinePositionX0Retired","UL"], <del> [0x0018,0x603D,"TMLinePositionX0","SL"], <del> [0x0018,0x603E,"TMLinePositionY0Retired","UL"], <del> [0x0018,0x603F,"TMLinePositionY0","SL"], <del> [0x0018,0x6040,"TMLinePositionX1Retired","UL"], <del> [0x0018,0x6041,"TMLinePositionX1","SL"], <del> [0x0018,0x6042,"TMLinePositionY1Retired","UL"], <del> [0x0018,0x6043,"TMLinePositionY1","SL"], <del> [0x0018,0x6044,"PixelComponentOrganization","US"], <del> [0x0018,0x6046,"PixelComponentMask","UL"], <del> [0x0018,0x6048,"PixelComponentRangeStart","UL"], <del> [0x0018,0x604A,"PixelComponentRangeStop","UL"], <del> [0x0018,0x604C,"PixelComponentPhysicalUnits","US"], <del> [0x0018,0x604E,"PixelComponentDataType","US"], <del> [0x0018,0x6050,"NumberOfTableBreakPoints","UL"], <del> [0x0018,0x6052,"TableOfXBreakPoints","UL"], <del> [0x0018,0x6054,"TableOfYBreakPoints","FD"], <del> [0x0018,0x6056,"NumberOfTableEntries","UL"], <del> [0x0018,0x6058,"TableOfPixelValues","UL"], <del> [0x0018,0x605A,"TableOfParameterValues","FL"], <del> [0x0018,0x6060,"RWaveTimeVector","FL"], <del> [0x0018,0x7000,"DetectorConditionsNominalFlag","CS"], <del> [0x0018,0x7001,"DetectorTemperature","DS"], <del> [0x0018,0x7004,"DetectorType","CS"], <del> [0x0018,0x7005,"DetectorConfiguration","CS"], <del> [0x0018,0x7006,"DetectorDescription","LT"], <del> [0x0018,0x7008,"DetectorMode","LT"], <del> [0x0018,0x700A,"DetectorID","SH"], <del> [0x0018,0x700C,"DateOfLastDetectorCalibration","DA"], <del> [0x0018,0x700E,"TimeOfLastDetectorCalibration","TM"], <del> [0x0018,0x7010,"ExposuresOnDetectorSinceLastCalibration","IS"], <del> [0x0018,0x7011,"ExposuresOnDetectorSinceManufactured","IS"], <del> [0x0018,0x7012,"DetectorTimeSinceLastExposure","DS"], <del> [0x0018,0x7014,"DetectorActiveTime","DS"], <del> [0x0018,0x7016,"DetectorActivationOffsetFromExposure","DS"], <del> [0x0018,0x701A,"DetectorBinning","DS"], <del> [0x0018,0x7020,"DetectorElementPhysicalSize","DS"], <del> [0x0018,0x7022,"DetectorElementSpacing","DS"], <del> [0x0018,0x7024,"DetectorActiveShape","CS"], <del> [0x0018,0x7026,"DetectorActiveDimensions","DS"], <del> [0x0018,0x7028,"DetectorActiveOrigin","DS"], <del> [0x0018,0x702A,"DetectorManufacturerName","LO"], <del> [0x0018,0x702B,"DetectorManufacturerModelName","LO"], <del> [0x0018,0x7030,"FieldOfViewOrigin","DS"], <del> [0x0018,0x7032,"FieldOfViewRotation","DS"], <del> [0x0018,0x7034,"FieldOfViewHorizontalFlip","CS"], <del> [0x0018,0x7036,"PixelDataAreaOriginRelativeToFOV","FL"], <del> [0x0018,0x7038,"PixelDataAreaRotationAngleRelativeToFOV","FL"], <del> [0x0018,0x7040,"GridAbsorbingMaterial","LT"], <del> [0x0018,0x7041,"GridSpacingMaterial","LT"], <del> [0x0018,0x7042,"GridThickness","DS"], <del> [0x0018,0x7044,"GridPitch","DS"], <del> [0x0018,0x7046,"GridAspectRatio","IS"], <del> [0x0018,0x7048,"GridPeriod","DS"], <del> [0x0018,0x704C,"GridFocalDistance","DS"], <del> [0x0018,0x7050,"FilterMaterial","CS"], <del> [0x0018,0x7052,"FilterThicknessMinimum","DS"], <del> [0x0018,0x7054,"FilterThicknessMaximum","DS"], <del> [0x0018,0x7056,"FilterBeamPathLengthMinimum","FL"], <del> [0x0018,0x7058,"FilterBeamPathLengthMaximum","FL"], <del> [0x0018,0x7060,"ExposureControlMode","CS"], <del> [0x0018,0x7062,"ExposureControlModeDescription","LT"], <del> [0x0018,0x7064,"ExposureStatus","CS"], <del> [0x0018,0x7065,"PhototimerSetting","DS"], <del> [0x0018,0x8150,"ExposureTimeInuS","DS"], <del> [0x0018,0x8151,"XRayTubeCurrentInuA","DS"], <del> [0x0018,0x9004,"ContentQualification","CS"], <del> [0x0018,0x9005,"PulseSequenceName","SH"], <del> [0x0018,0x9006,"MRImagingModifierSequence","SQ"], <del> [0x0018,0x9008,"EchoPulseSequence","CS"], <del> [0x0018,0x9009,"InversionRecovery","CS"], <del> [0x0018,0x9010,"FlowCompensation","CS"], <del> [0x0018,0x9011,"MultipleSpinEcho","CS"], <del> [0x0018,0x9012,"MultiPlanarExcitation","CS"], <del> [0x0018,0x9014,"PhaseContrast","CS"], <del> [0x0018,0x9015,"TimeOfFlightContrast","CS"], <del> [0x0018,0x9016,"Spoiling","CS"], <del> [0x0018,0x9017,"SteadyStatePulseSequence","CS"], <del> [0x0018,0x9018,"EchoPlanarPulseSequence","CS"], <del> [0x0018,0x9019,"TagAngleFirstAxis","FD"], <del> [0x0018,0x9020,"MagnetizationTransfer","CS"], <del> [0x0018,0x9021,"T2Preparation","CS"], <del> [0x0018,0x9022,"BloodSignalNulling","CS"], <del> [0x0018,0x9024,"SaturationRecovery","CS"], <del> [0x0018,0x9025,"SpectrallySelectedSuppression","CS"], <del> [0x0018,0x9026,"SpectrallySelectedExcitation","CS"], <del> [0x0018,0x9027,"SpatialPresaturation","CS"], <del> [0x0018,0x9028,"Tagging","CS"], <del> [0x0018,0x9029,"OversamplingPhase","CS"], <del> [0x0018,0x9030,"TagSpacingFirstDimension","FD"], <del> [0x0018,0x9032,"GeometryOfKSpaceTraversal","CS"], <del> [0x0018,0x9033,"SegmentedKSpaceTraversal","CS"], <del> [0x0018,0x9034,"RectilinearPhaseEncodeReordering","CS"], <del> [0x0018,0x9035,"TagThickness","FD"], <del> [0x0018,0x9036,"PartialFourierDirection","CS"], <del> [0x0018,0x9037,"CardiacSynchronizationTechnique","CS"], <del> [0x0018,0x9041,"ReceiveCoilManufacturerName","LO"], <del> [0x0018,0x9042,"MRReceiveCoilSequence","SQ"], <del> [0x0018,0x9043,"ReceiveCoilType","CS"], <del> [0x0018,0x9044,"QuadratureReceiveCoil","CS"], <del> [0x0018,0x9045,"MultiCoilDefinitionSequence","SQ"], <del> [0x0018,0x9046,"MultiCoilConfiguration","LO"], <del> [0x0018,0x9047,"MultiCoilElementName","SH"], <del> [0x0018,0x9048,"MultiCoilElementUsed","CS"], <del> [0x0018,0x9049,"MRTransmitCoilSequence","SQ"], <del> [0x0018,0x9050,"TransmitCoilManufacturerName","LO"], <del> [0x0018,0x9051,"TransmitCoilType","CS"], <del> [0x0018,0x9052,"SpectralWidth","FD"], <del> [0x0018,0x9053,"ChemicalShiftReference","FD"], <del> [0x0018,0x9054,"VolumeLocalizationTechnique","CS"], <del> [0x0018,0x9058,"MRAcquisitionFrequencyEncodingSteps","US"], <del> [0x0018,0x9059,"Decoupling","CS"], <del> [0x0018,0x9060,"DecoupledNucleus","CS"], <del> [0x0018,0x9061,"DecouplingFrequency","FD"], <del> [0x0018,0x9062,"DecouplingMethod","CS"], <del> [0x0018,0x9063,"DecouplingChemicalShiftReference","FD"], <del> [0x0018,0x9064,"KSpaceFiltering","CS"], <del> [0x0018,0x9065,"TimeDomainFiltering","CS"], <del> [0x0018,0x9066,"NumberOfZeroFills","US"], <del> [0x0018,0x9067,"BaselineCorrection","CS"], <del> [0x0018,0x9069,"ParallelReductionFactorInPlane","FD"], <del> [0x0018,0x9070,"CardiacRRIntervalSpecified","FD"], <del> [0x0018,0x9073,"AcquisitionDuration","FD"], <del> [0x0018,0x9074,"FrameAcquisitionDateTime","DT"], <del> [0x0018,0x9075,"DiffusionDirectionality","CS"], <del> [0x0018,0x9076,"DiffusionGradientDirectionSequence","SQ"], <del> [0x0018,0x9077,"ParallelAcquisition","CS"], <del> [0x0018,0x9078,"ParallelAcquisitionTechnique","CS"], <del> [0x0018,0x9079,"InversionTimes","FD"], <del> [0x0018,0x9080,"MetaboliteMapDescription","ST"], <del> [0x0018,0x9081,"PartialFourier","CS"], <del> [0x0018,0x9082,"EffectiveEchoTime","FD"], <del> [0x0018,0x9083,"MetaboliteMapCodeSequence","SQ"], <del> [0x0018,0x9084,"ChemicalShiftSequence","SQ"], <del> [0x0018,0x9085,"CardiacSignalSource","CS"], <del> [0x0018,0x9087,"DiffusionBValue","FD"], <del> [0x0018,0x9089,"DiffusionGradientOrientation","FD"], <del> [0x0018,0x9090,"VelocityEncodingDirection","FD"], <del> [0x0018,0x9091,"VelocityEncodingMinimumValue","FD"], <del> [0x0018,0x9092,"VelocityEncodingAcquisitionSequence","SQ"], <del> [0x0018,0x9093,"NumberOfKSpaceTrajectories","US"], <del> [0x0018,0x9094,"CoverageOfKSpace","CS"], <del> [0x0018,0x9095,"SpectroscopyAcquisitionPhaseRows","UL"], <del> [0x0018,0x9096,"ParallelReductionFactorInPlaneRetired","FD"], <del> [0x0018,0x9098,"TransmitterFrequency","FD"], <del> [0x0018,0x9100,"ResonantNucleus","CS"], <del> [0x0018,0x9101,"FrequencyCorrection","CS"], <del> [0x0018,0x9103,"MRSpectroscopyFOVGeometrySequence","SQ"], <del> [0x0018,0x9104,"SlabThickness","FD"], <del> [0x0018,0x9105,"SlabOrientation","FD"], <del> [0x0018,0x9106,"MidSlabPosition","FD"], <del> [0x0018,0x9107,"MRSpatialSaturationSequence","SQ"], <del> [0x0018,0x9112,"MRTimingAndRelatedParametersSequence","SQ"], <del> [0x0018,0x9114,"MREchoSequence","SQ"], <del> [0x0018,0x9115,"MRModifierSequence","SQ"], <del> [0x0018,0x9117,"MRDiffusionSequence","SQ"], <del> [0x0018,0x9118,"CardiacSynchronizationSequence","SQ"], <del> [0x0018,0x9119,"MRAveragesSequence","SQ"], <del> [0x0018,0x9125,"MRFOVGeometrySequence","SQ"], <del> [0x0018,0x9126,"VolumeLocalizationSequence","SQ"], <del> [0x0018,0x9127,"SpectroscopyAcquisitionDataColumns","UL"], <del> [0x0018,0x9147,"DiffusionAnisotropyType","CS"], <del> [0x0018,0x9151,"FrameReferenceDateTime","DT"], <del> [0x0018,0x9152,"MRMetaboliteMapSequence","SQ"], <del> [0x0018,0x9155,"ParallelReductionFactorOutOfPlane","FD"], <del> [0x0018,0x9159,"SpectroscopyAcquisitionOutOfPlanePhaseSteps","UL"], <del> [0x0018,0x9166,"BulkMotionStatus","CS"], <del> [0x0018,0x9168,"ParallelReductionFactorSecondInPlane","FD"], <del> [0x0018,0x9169,"CardiacBeatRejectionTechnique","CS"], <del> [0x0018,0x9170,"RespiratoryMotionCompensationTechnique","CS"], <del> [0x0018,0x9171,"RespiratorySignalSource","CS"], <del> [0x0018,0x9172,"BulkMotionCompensationTechnique","CS"], <del> [0x0018,0x9173,"BulkMotionSignalSource","CS"], <del> [0x0018,0x9174,"ApplicableSafetyStandardAgency","CS"], <del> [0x0018,0x9175,"ApplicableSafetyStandardDescription","LO"], <del> [0x0018,0x9176,"OperatingModeSequence","SQ"], <del> [0x0018,0x9177,"OperatingModeType","CS"], <del> [0x0018,0x9178,"OperatingMode","CS"], <del> [0x0018,0x9179,"SpecificAbsorptionRateDefinition","CS"], <del> [0x0018,0x9180,"GradientOutputType","CS"], <del> [0x0018,0x9181,"SpecificAbsorptionRateValue","FD"], <del> [0x0018,0x9182,"GradientOutput","FD"], <del> [0x0018,0x9183,"FlowCompensationDirection","CS"], <del> [0x0018,0x9184,"TaggingDelay","FD"], <del> [0x0018,0x9185,"RespiratoryMotionCompensationTechniqueDescription","ST"], <del> [0x0018,0x9186,"RespiratorySignalSourceID","SH"], <del> [0x0018,0x9195,"ChemicalShiftMinimumIntegrationLimitInHz","FD"], <del> [0x0018,0x9196,"ChemicalShiftMaximumIntegrationLimitInHz","FD"], <del> [0x0018,0x9197,"MRVelocityEncodingSequence","SQ"], <del> [0x0018,0x9198,"FirstOrderPhaseCorrection","CS"], <del> [0x0018,0x9199,"WaterReferencedPhaseCorrection","CS"], <del> [0x0018,0x9200,"MRSpectroscopyAcquisitionType","CS"], <del> [0x0018,0x9214,"RespiratoryCyclePosition","CS"], <del> [0x0018,0x9217,"VelocityEncodingMaximumValue","FD"], <del> [0x0018,0x9218,"TagSpacingSecondDimension","FD"], <del> [0x0018,0x9219,"TagAngleSecondAxis","SS"], <del> [0x0018,0x9220,"FrameAcquisitionDuration","FD"], <del> [0x0018,0x9226,"MRImageFrameTypeSequence","SQ"], <del> [0x0018,0x9227,"MRSpectroscopyFrameTypeSequence","SQ"], <del> [0x0018,0x9231,"MRAcquisitionPhaseEncodingStepsInPlane","US"], <del> [0x0018,0x9232,"MRAcquisitionPhaseEncodingStepsOutOfPlane","US"], <del> [0x0018,0x9234,"SpectroscopyAcquisitionPhaseColumns","UL"], <del> [0x0018,0x9236,"CardiacCyclePosition","CS"], <del> [0x0018,0x9239,"SpecificAbsorptionRateSequence","SQ"], <del> [0x0018,0x9240,"RFEchoTrainLength","US"], <del> [0x0018,0x9241,"GradientEchoTrainLength","US"], <del> [0x0018,0x9250,"ArterialSpinLabelingContrast","CS"], <del> [0x0018,0x9251,"MRArterialSpinLabelingSequence","SQ"], <del> [0x0018,0x9252,"ASLTechniqueDescription","LO"], <del> [0x0018,0x9253,"ASLSlabNumber","US"], <del> [0x0018,0x9254,"ASLSlabThickness","FD "], <del> [0x0018,0x9255,"ASLSlabOrientation","FD "], <del> [0x0018,0x9256,"ASLMidSlabPosition","FD "], <del> [0x0018,0x9257,"ASLContext","CS"], <del> [0x0018,0x9258,"ASLPulseTrainDuration","UL"], <del> [0x0018,0x9259,"ASLCrusherFlag","CS"], <del> [0x0018,0x925A,"ASLCrusherFlow","FD"], <del> [0x0018,0x925B,"ASLCrusherDescription","LO"], <del> [0x0018,0x925C,"ASLBolusCutoffFlag","CS"], <del> [0x0018,0x925D,"ASLBolusCutoffTimingSequence","SQ"], <del> [0x0018,0x925E,"ASLBolusCutoffTechnique","LO"], <del> [0x0018,0x925F,"ASLBolusCutoffDelayTime","UL"], <del> [0x0018,0x9260,"ASLSlabSequence","SQ"], <del> [0x0018,0x9295,"ChemicalShiftMinimumIntegrationLimitInppm","FD"], <del> [0x0018,0x9296,"ChemicalShiftMaximumIntegrationLimitInppm","FD"], <del> [0x0018,0x9301,"CTAcquisitionTypeSequence","SQ"], <del> [0x0018,0x9302,"AcquisitionType","CS"], <del> [0x0018,0x9303,"TubeAngle","FD"], <del> [0x0018,0x9304,"CTAcquisitionDetailsSequence","SQ"], <del> [0x0018,0x9305,"RevolutionTime","FD"], <del> [0x0018,0x9306,"SingleCollimationWidth","FD"], <del> [0x0018,0x9307,"TotalCollimationWidth","FD"], <del> [0x0018,0x9308,"CTTableDynamicsSequence","SQ"], <del> [0x0018,0x9309,"TableSpeed","FD"], <del> [0x0018,0x9310,"TableFeedPerRotation","FD"], <del> [0x0018,0x9311,"SpiralPitchFactor","FD"], <del> [0x0018,0x9312,"CTGeometrySequence","SQ"], <del> [0x0018,0x9313,"DataCollectionCenterPatient","FD"], <del> [0x0018,0x9314,"CTReconstructionSequence","SQ"], <del> [0x0018,0x9315,"ReconstructionAlgorithm","CS"], <del> [0x0018,0x9316,"ConvolutionKernelGroup","CS"], <del> [0x0018,0x9317,"ReconstructionFieldOfView","FD"], <del> [0x0018,0x9318,"ReconstructionTargetCenterPatient","FD"], <del> [0x0018,0x9319,"ReconstructionAngle","FD"], <del> [0x0018,0x9320,"ImageFilter","SH"], <del> [0x0018,0x9321,"CTExposureSequence","SQ"], <del> [0x0018,0x9322,"ReconstructionPixelSpacing","FD"], <del> [0x0018,0x9323,"ExposureModulationType","CS"], <del> [0x0018,0x9324,"EstimatedDoseSaving","FD"], <del> [0x0018,0x9325,"CTXRayDetailsSequence","SQ"], <del> [0x0018,0x9326,"CTPositionSequence","SQ"], <del> [0x0018,0x9327,"TablePosition","FD"], <del> [0x0018,0x9328,"ExposureTimeInms","FD"], <del> [0x0018,0x9329,"CTImageFrameTypeSequence","SQ"], <del> [0x0018,0x9330,"XRayTubeCurrentInmA","FD"], <del> [0x0018,0x9332,"ExposureInmAs","FD"], <del> [0x0018,0x9333,"ConstantVolumeFlag","CS"], <del> [0x0018,0x9334,"FluoroscopyFlag","CS"], <del> [0x0018,0x9335,"DistanceSourceToDataCollectionCenter","FD"], <del> [0x0018,0x9337,"ContrastBolusAgentNumber","US"], <del> [0x0018,0x9338,"ContrastBolusIngredientCodeSequence","SQ"], <del> [0x0018,0x9340,"ContrastAdministrationProfileSequence","SQ"], <del> [0x0018,0x9341,"ContrastBolusUsageSequence","SQ"], <del> [0x0018,0x9342,"ContrastBolusAgentAdministered","CS"], <del> [0x0018,0x9343,"ContrastBolusAgentDetected","CS"], <del> [0x0018,0x9344,"ContrastBolusAgentPhase","CS"], <del> [0x0018,0x9345,"CTDIvol","FD"], <del> [0x0018,0x9346,"CTDIPhantomTypeCodeSequence","SQ"], <del> [0x0018,0x9351,"CalciumScoringMassFactorPatient","FL"], <del> [0x0018,0x9352,"CalciumScoringMassFactorDevice","FL"], <del> [0x0018,0x9353,"EnergyWeightingFactor","FL"], <del> [0x0018,0x9360,"CTAdditionalXRaySourceSequence","SQ"], <del> [0x0018,0x9401,"ProjectionPixelCalibrationSequence","SQ"], <del> [0x0018,0x9402,"DistanceSourceToIsocenter","FL"], <del> [0x0018,0x9403,"DistanceObjectToTableTop","FL"], <del> [0x0018,0x9404,"ObjectPixelSpacingInCenterOfBeam","FL"], <del> [0x0018,0x9405,"PositionerPositionSequence","SQ"], <del> [0x0018,0x9406,"TablePositionSequence","SQ"], <del> [0x0018,0x9407,"CollimatorShapeSequence","SQ"], <del> [0x0018,0x9410,"PlanesInAcquisition","CS"], <del> [0x0018,0x9412,"XAXRFFrameCharacteristicsSequence","SQ"], <del> [0x0018,0x9417,"FrameAcquisitionSequence","SQ"], <del> [0x0018,0x9420,"XRayReceptorType","CS"], <del> [0x0018,0x9423,"AcquisitionProtocolName","LO"], <del> [0x0018,0x9424,"AcquisitionProtocolDescription","LT"], <del> [0x0018,0x9425,"ContrastBolusIngredientOpaque","CS"], <del> [0x0018,0x9426,"DistanceReceptorPlaneToDetectorHousing","FL"], <del> [0x0018,0x9427,"IntensifierActiveShape","CS"], <del> [0x0018,0x9428,"IntensifierActiveDimensions","FL"], <del> [0x0018,0x9429,"PhysicalDetectorSize","FL"], <del> [0x0018,0x9430,"PositionOfIsocenterProjection","FL"], <del> [0x0018,0x9432,"FieldOfViewSequence","SQ"], <del> [0x0018,0x9433,"FieldOfViewDescription","LO"], <del> [0x0018,0x9434,"ExposureControlSensingRegionsSequence","SQ"], <del> [0x0018,0x9435,"ExposureControlSensingRegionShape","CS"], <del> [0x0018,0x9436,"ExposureControlSensingRegionLeftVerticalEdge","SS"], <del> [0x0018,0x9437,"ExposureControlSensingRegionRightVerticalEdge","SS"], <del> [0x0018,0x9438,"ExposureControlSensingRegionUpperHorizontalEdge","SS"], <del> [0x0018,0x9439,"ExposureControlSensingRegionLowerHorizontalEdge","SS"], <del> [0x0018,0x9440,"CenterOfCircularExposureControlSensingRegion","SS"], <del> [0x0018,0x9441,"RadiusOfCircularExposureControlSensingRegion","US"], <del> [0x0018,0x9442,"VerticesOfThePolygonalExposureControlSensingRegion","SS"], <del> [0x0018,0x9447,"ColumnAngulationPatient","FL"], <del> [0x0018,0x9449,"BeamAngle","FL"], <del> [0x0018,0x9451,"FrameDetectorParametersSequence","SQ"], <del> [0x0018,0x9452,"CalculatedAnatomyThickness","FL"], <del> [0x0018,0x9455,"CalibrationSequence","SQ"], <del> [0x0018,0x9456,"ObjectThicknessSequence","SQ"], <del> [0x0018,0x9457,"PlaneIdentification","CS"], <del> [0x0018,0x9461,"FieldOfViewDimensionsInFloat","FL"], <del> [0x0018,0x9462,"IsocenterReferenceSystemSequence","SQ"], <del> [0x0018,0x9463,"PositionerIsocenterPrimaryAngle","FL"], <del> [0x0018,0x9464,"PositionerIsocenterSecondaryAngle","FL"], <del> [0x0018,0x9465,"PositionerIsocenterDetectorRotationAngle","FL"], <del> [0x0018,0x9466,"TableXPositionToIsocenter","FL"], <del> [0x0018,0x9467,"TableYPositionToIsocenter","FL"], <del> [0x0018,0x9468,"TableZPositionToIsocenter","FL"], <del> [0x0018,0x9469,"TableHorizontalRotationAngle","FL"], <del> [0x0018,0x9470,"TableHeadTiltAngle","FL"], <del> [0x0018,0x9471,"TableCradleTiltAngle","FL"], <del> [0x0018,0x9472,"FrameDisplayShutterSequence","SQ"], <del> [0x0018,0x9473,"AcquiredImageAreaDoseProduct","FL"], <del> [0x0018,0x9474,"CArmPositionerTabletopRelationship","CS"], <del> [0x0018,0x9476,"XRayGeometrySequence","SQ"], <del> [0x0018,0x9477,"IrradiationEventIdentificationSequence","SQ"], <del> [0x0018,0x9504,"XRay3DFrameTypeSequence","SQ"], <del> [0x0018,0x9506,"ContributingSourcesSequence","SQ"], <del> [0x0018,0x9507,"XRay3DAcquisitionSequence","SQ"], <del> [0x0018,0x9508,"PrimaryPositionerScanArc","FL"], <del> [0x0018,0x9509,"SecondaryPositionerScanArc","FL"], <del> [0x0018,0x9510,"PrimaryPositionerScanStartAngle","FL "], <del> [0x0018,0x9511,"SecondaryPositionerScanStartAngle","FL"], <del> [0x0018,0x9514,"PrimaryPositionerIncrement","FL"], <del> [0x0018,0x9515,"SecondaryPositionerIncrement","FL"], <del> [0x0018,0x9516,"StartAcquisitionDateTime","DT"], <del> [0x0018,0x9517,"EndAcquisitionDateTime","DT"], <del> [0x0018,0x9524,"ApplicationName","LO"], <del> [0x0018,0x9525,"ApplicationVersion","LO"], <del> [0x0018,0x9526,"ApplicationManufacturer","LO"], <del> [0x0018,0x9527,"AlgorithmType","CS"], <del> [0x0018,0x9528,"AlgorithmDescription","LO"], <del> [0x0018,0x9530,"XRay3DReconstructionSequence","SQ"], <del> [0x0018,0x9531,"ReconstructionDescription","LO"], <del> [0x0018,0x9538,"PerProjectionAcquisitionSequence","SQ"], <del> [0x0018,0x9601,"DiffusionBMatrixSequence","SQ"], <del> [0x0018,0x9602,"DiffusionBValueXX","FD"], <del> [0x0018,0x9603,"DiffusionBValueXY","FD"], <del> [0x0018,0x9604,"DiffusionBValueXZ","FD"], <del> [0x0018,0x9605,"DiffusionBValueYY","FD"], <del> [0x0018,0x9606,"DiffusionBValueYZ","FD"], <del> [0x0018,0x9607,"DiffusionBValueZZ","FD"], <del> [0x0018,0x9701,"DecayCorrectionDateTime","DT"], <del> [0x0018,0x9715,"StartDensityThreshold","FD"], <del> [0x0018,0x9716,"StartRelativeDensityDifferenceThreshold","FD"], <del> [0x0018,0x9717,"StartCardiacTriggerCountThreshold","FD"], <del> [0x0018,0x9718,"StartRespiratoryTriggerCountThreshold","FD"], <del> [0x0018,0x9719,"TerminationCountsThreshold","FD"], <del> [0x0018,0x9720,"TerminationDensityThreshold","FD"], <del> [0x0018,0x9721,"TerminationRelativeDensityThreshold","FD"], <del> [0x0018,0x9722,"TerminationTimeThreshold","FD"], <del> [0x0018,0x9723,"TerminationCardiacTriggerCountThreshold","FD"], <del> [0x0018,0x9724,"TerminationRespiratoryTriggerCountThreshold","FD"], <del> [0x0018,0x9725,"DetectorGeometry","CS"], <del> [0x0018,0x9726,"TransverseDetectorSeparation","FD"], <del> [0x0018,0x9727,"AxialDetectorDimension","FD"], <del> [0x0018,0x9729,"RadiopharmaceuticalAgentNumber","US"], <del> [0x0018,0x9732,"PETFrameAcquisitionSequence","SQ"], <del> [0x0018,0x9733,"PETDetectorMotionDetailsSequence","SQ"], <del> [0x0018,0x9734,"PETTableDynamicsSequence","SQ"], <del> [0x0018,0x9735,"PETPositionSequence","SQ"], <del> [0x0018,0x9736,"PETFrameCorrectionFactorsSequence","SQ"], <del> [0x0018,0x9737,"RadiopharmaceuticalUsageSequence","SQ"], <del> [0x0018,0x9738,"AttenuationCorrectionSource","CS"], <del> [0x0018,0x9739,"NumberOfIterations","US"], <del> [0x0018,0x9740,"NumberOfSubsets","US"], <del> [0x0018,0x9749,"PETReconstructionSequence","SQ"], <del> [0x0018,0x9751,"PETFrameTypeSequence","SQ"], <del> [0x0018,0x9755,"TimeOfFlightInformationUsed","CS"], <del> [0x0018,0x9756,"ReconstructionType","CS"], <del> [0x0018,0x9758,"DecayCorrected","CS"], <del> [0x0018,0x9759,"AttenuationCorrected","CS"], <del> [0x0018,0x9760,"ScatterCorrected","CS"], <del> [0x0018,0x9761,"DeadTimeCorrected","CS"], <del> [0x0018,0x9762,"GantryMotionCorrected","CS"], <del> [0x0018,0x9763,"PatientMotionCorrected","CS"], <del> [0x0018,0x9764,"CountLossNormalizationCorrected","CS"], <del> [0x0018,0x9765,"RandomsCorrected","CS"], <del> [0x0018,0x9766,"NonUniformRadialSamplingCorrected","CS"], <del> [0x0018,0x9767,"SensitivityCalibrated","CS"], <del> [0x0018,0x9768,"DetectorNormalizationCorrection","CS"], <del> [0x0018,0x9769,"IterativeReconstructionMethod","CS"], <del> [0x0018,0x9770,"AttenuationCorrectionTemporalRelationship","CS"], <del> [0x0018,0x9771,"PatientPhysiologicalStateSequence","SQ"], <del> [0x0018,0x9772,"PatientPhysiologicalStateCodeSequence","SQ"], <del> [0x0018,0x9801,"DepthsOfFocus","FD"], <del> [0x0018,0x9803,"ExcludedIntervalsSequence","SQ"], <del> [0x0018,0x9804,"ExclusionStartDatetime","DT"], <del> [0x0018,0x9805,"ExclusionDuration","FD"], <del> [0x0018,0x9806,"USImageDescriptionSequence","SQ"], <del> [0x0018,0x9807,"ImageDataTypeSequence","SQ"], <del> [0x0018,0x9808,"DataType","CS"], <del> [0x0018,0x9809,"TransducerScanPatternCodeSequence","SQ"], <del> [0x0018,0x980B,"AliasedDataType","CS"], <del> [0x0018,0x980C,"PositionMeasuringDeviceUsed","CS"], <del> [0x0018,0x980D,"TransducerGeometryCodeSequence","SQ"], <del> [0x0018,0x980E,"TransducerBeamSteeringCodeSequence","SQ"], <del> [0x0018,0x980F,"TransducerApplicationCodeSequence","SQ"], <del> [0x0018,0xA001,"ContributingEquipmentSequence","SQ"], <del> [0x0018,0xA002,"ContributionDateTime","DT"], <del> [0x0018,0xA003,"ContributionDescription","ST"], <del> [0x0020,0x000D,"StudyInstanceUID","UI"], <del> [0x0020,0x000E,"SeriesInstanceUID","UI"], <del> [0x0020,0x0010,"StudyID","SH"], <del> [0x0020,0x0011,"SeriesNumber","IS"], <del> [0x0020,0x0012,"AcquisitionNumber","IS"], <del> [0x0020,0x0013,"InstanceNumber","IS"], <del> [0x0020,0x0014,"IsotopeNumber","IS"], <del> [0x0020,0x0015,"PhaseNumber","IS"], <del> [0x0020,0x0016,"IntervalNumber","IS"], <del> [0x0020,0x0017,"TimeSlotNumber","IS"], <del> [0x0020,0x0018,"AngleNumber","IS"], <del> [0x0020,0x0019,"ItemNumber","IS"], <del> [0x0020,0x0020,"PatientOrientation","CS"], <del> [0x0020,0x0022,"OverlayNumber","IS"], <del> [0x0020,0x0024,"CurveNumber","IS"], <del> [0x0020,0x0026,"LUTNumber","IS"], <del> [0x0020,0x0030,"ImagePosition","DS"], <del> [0x0020,0x0032,"ImagePositionPatient","DS"], <del> [0x0020,0x0035,"ImageOrientation","DS"], <del> [0x0020,0x0037,"ImageOrientationPatient","DS"], <del> [0x0020,0x0050,"Location","DS"], <del> [0x0020,0x0052,"FrameOfReferenceUID","UI"], <del> [0x0020,0x0060,"Laterality","CS"], <del> [0x0020,0x0062,"ImageLaterality","CS"], <del> [0x0020,0x0070,"ImageGeometryType","LO"], <del> [0x0020,0x0080,"MaskingImage","CS"], <del> [0x0020,0x00AA,"ReportNumber","IS"], <del> [0x0020,0x0100,"TemporalPositionIdentifier","IS"], <del> [0x0020,0x0105,"NumberOfTemporalPositions","IS"], <del> [0x0020,0x0110,"TemporalResolution","DS"], <del> [0x0020,0x0200,"SynchronizationFrameOfReferenceUID","UI"], <del> [0x0020,0x0242,"SOPInstanceUIDOfConcatenationSource","UI"], <del> [0x0020,0x1000,"SeriesInStudy","IS"], <del> [0x0020,0x1001,"AcquisitionsInSeries","IS"], <del> [0x0020,0x1002,"ImagesInAcquisition","IS"], <del> [0x0020,0x1003,"ImagesInSeries","IS"], <del> [0x0020,0x1004,"AcquisitionsInStudy","IS"], <del> [0x0020,0x1005,"ImagesInStudy","IS"], <del> [0x0020,0x1020,"Reference","LO"], <del> [0x0020,0x1040,"PositionReferenceIndicator","LO"], <del> [0x0020,0x1041,"SliceLocation","DS"], <del> [0x0020,0x1070,"OtherStudyNumbers","IS"], <del> [0x0020,0x1200,"NumberOfPatientRelatedStudies","IS"], <del> [0x0020,0x1202,"NumberOfPatientRelatedSeries","IS"], <del> [0x0020,0x1204,"NumberOfPatientRelatedInstances","IS"], <del> [0x0020,0x1206,"NumberOfStudyRelatedSeries","IS"], <del> [0x0020,0x1208,"NumberOfStudyRelatedInstances","IS"], <del> [0x0020,0x1209,"NumberOfSeriesRelatedInstances","IS"], <del> [0x0020,0x3401,"ModifyingDeviceID","CS"], <del> [0x0020,0x3402,"ModifiedImageID","CS"], <del> [0x0020,0x3403,"ModifiedImageDate","DA"], <del> [0x0020,0x3404,"ModifyingDeviceManufacturer","LO"], <del> [0x0020,0x3405,"ModifiedImageTime","TM"], <del> [0x0020,0x3406,"ModifiedImageDescription","LO"], <del> [0x0020,0x4000,"ImageComments","LT"], <del> [0x0020,0x5000,"OriginalImageIdentification","AT"], <del> [0x0020,0x5002,"OriginalImageIdentificationNomenclature","LO"], <del> [0x0020,0x9056,"StackID","SH"], <del> [0x0020,0x9057,"InStackPositionNumber","UL"], <del> [0x0020,0x9071,"FrameAnatomySequence","SQ"], <del> [0x0020,0x9072,"FrameLaterality","CS"], <del> [0x0020,0x9111,"FrameContentSequence","SQ"], <del> [0x0020,0x9113,"PlanePositionSequence","SQ"], <del> [0x0020,0x9116,"PlaneOrientationSequence","SQ"], <del> [0x0020,0x9128,"TemporalPositionIndex","UL"], <del> [0x0020,0x9153,"NominalCardiacTriggerDelayTime","FD"], <del> [0x0020,0x9154,"NominalCardiacTriggerTimePriorToRPeak","FL"], <del> [0x0020,0x9155,"ActualCardiacTriggerTimePriorToRPeak","FL"], <del> [0x0020,0x9156,"FrameAcquisitionNumber","US"], <del> [0x0020,0x9157,"DimensionIndexValues","UL"], <del> [0x0020,0x9158,"FrameComments","LT"], <del> [0x0020,0x9161,"ConcatenationUID","UI"], <del> [0x0020,0x9162,"InConcatenationNumber","US"], <del> [0x0020,0x9163,"InConcatenationTotalNumber","US"], <del> [0x0020,0x9164,"DimensionOrganizationUID","UI"], <del> [0x0020,0x9165,"DimensionIndexPointer","AT"], <del> [0x0020,0x9167,"FunctionalGroupPointer","AT"], <del> [0x0020,0x9213,"DimensionIndexPrivateCreator","LO"], <del> [0x0020,0x9221,"DimensionOrganizationSequence","SQ"], <del> [0x0020,0x9222,"DimensionIndexSequence","SQ"], <del> [0x0020,0x9228,"ConcatenationFrameOffsetNumber","UL"], <del> [0x0020,0x9238,"FunctionalGroupPrivateCreator","LO"], <del> [0x0020,0x9241,"NominalPercentageOfCardiacPhase","FL"], <del> [0x0020,0x9245,"NominalPercentageOfRespiratoryPhase","FL"], <del> [0x0020,0x9246,"StartingRespiratoryAmplitude","FL"], <del> [0x0020,0x9247,"StartingRespiratoryPhase","CS"], <del> [0x0020,0x9248,"EndingRespiratoryAmplitude","FL"], <del> [0x0020,0x9249,"EndingRespiratoryPhase","CS"], <del> [0x0020,0x9250,"RespiratoryTriggerType","CS"], <del> [0x0020,0x9251,"RRIntervalTimeNominal","FD"], <del> [0x0020,0x9252,"ActualCardiacTriggerDelayTime","FD"], <del> [0x0020,0x9253,"RespiratorySynchronizationSequence","SQ"], <del> [0x0020,0x9254,"RespiratoryIntervalTime","FD"], <del> [0x0020,0x9255,"NominalRespiratoryTriggerDelayTime","FD"], <del> [0x0020,0x9256,"RespiratoryTriggerDelayThreshold","FD"], <del> [0x0020,0x9257,"ActualRespiratoryTriggerDelayTime","FD"], <del> [0x0020,0x9301,"ImagePositionVolume","FD"], <del> [0x0020,0x9302,"ImageOrientationVolume","FD"], <del> [0x0020,0x9307,"UltrasoundAcquisitionGeometry","CS"], <del> [0x0020,0x9308,"ApexPosition","FD"], <del> [0x0020,0x9309,"VolumeToTransducerMappingMatrix","FD"], <del> [0x0020,0x930A,"VolumeToTableMappingMatrix","FD"], <del> [0x0020,0x930C,"PatientFrameOfReferenceSource","CS"], <del> [0x0020,0x930D,"TemporalPositionTimeOffset","FD"], <del> [0x0020,0x930E,"PlanePositionVolumeSequence","SQ"], <del> [0x0020,0x930F,"PlaneOrientationVolumeSequence","SQ"], <del> [0x0020,0x9310,"TemporalPositionSequence","SQ"], <del> [0x0020,0x9311,"DimensionOrganizationType","CS"], <del> [0x0020,0x9312,"VolumeFrameOfReferenceUID","UI"], <del> [0x0020,0x9313,"TableFrameOfReferenceUID","UI"], <del> [0x0020,0x9421,"DimensionDescriptionLabel","LO"], <del> [0x0020,0x9450,"PatientOrientationInFrameSequence","SQ"], <del> [0x0020,0x9453,"FrameLabel","LO"], <del> [0x0020,0x9518,"AcquisitionIndex","US"], <del> [0x0020,0x9529,"ContributingSOPInstancesReferenceSequence","SQ"], <del> [0x0020,0x9536,"ReconstructionIndex","US"], <del> [0x0022,0x0001,"LightPathFilterPassThroughWavelength","US"], <del> [0x0022,0x0002,"LightPathFilterPassBand","US"], <del> [0x0022,0x0003,"ImagePathFilterPassThroughWavelength","US"], <del> [0x0022,0x0004,"ImagePathFilterPassBand","US"], <del> [0x0022,0x0005,"PatientEyeMovementCommanded","CS"], <del> [0x0022,0x0006,"PatientEyeMovementCommandCodeSequence","SQ"], <del> [0x0022,0x0007,"SphericalLensPower","FL"], <del> [0x0022,0x0008,"CylinderLensPower","FL"], <del> [0x0022,0x0009,"CylinderAxis","FL"], <del> [0x0022,0x000A,"EmmetropicMagnification","FL"], <del> [0x0022,0x000B,"IntraOcularPressure","FL"], <del> [0x0022,0x000C,"HorizontalFieldOfView","FL"], <del> [0x0022,0x000D,"PupilDilated","CS"], <del> [0x0022,0x000E,"DegreeOfDilation","FL"], <del> [0x0022,0x0010,"StereoBaselineAngle","FL"], <del> [0x0022,0x0011,"StereoBaselineDisplacement","FL"], <del> [0x0022,0x0012,"StereoHorizontalPixelOffset","FL"], <del> [0x0022,0x0013,"StereoVerticalPixelOffset","FL"], <del> [0x0022,0x0014,"StereoRotation","FL"], <del> [0x0022,0x0015,"AcquisitionDeviceTypeCodeSequence","SQ"], <del> [0x0022,0x0016,"IlluminationTypeCodeSequence","SQ"], <del> [0x0022,0x0017,"LightPathFilterTypeStackCodeSequence","SQ"], <del> [0x0022,0x0018,"ImagePathFilterTypeStackCodeSequence","SQ"], <del> [0x0022,0x0019,"LensesCodeSequence","SQ"], <del> [0x0022,0x001A,"ChannelDescriptionCodeSequence","SQ"], <del> [0x0022,0x001B,"RefractiveStateSequence","SQ"], <del> [0x0022,0x001C,"MydriaticAgentCodeSequence","SQ"], <del> [0x0022,0x001D,"RelativeImagePositionCodeSequence","SQ"], <del> [0x0022,0x001E,"CameraAngleOfView","FL"], <del> [0x0022,0x0020,"StereoPairsSequence","SQ"], <del> [0x0022,0x0021,"LeftImageSequence","SQ"], <del> [0x0022,0x0022,"RightImageSequence","SQ"], <del> [0x0022,0x0030,"AxialLengthOfTheEye","FL"], <del> [0x0022,0x0031,"OphthalmicFrameLocationSequence","SQ"], <del> [0x0022,0x0032,"ReferenceCoordinates","FL"], <del> [0x0022,0x0035,"DepthSpatialResolution","FL"], <del> [0x0022,0x0036,"MaximumDepthDistortion","FL"], <del> [0x0022,0x0037,"AlongScanSpatialResolution","FL"], <del> [0x0022,0x0038,"MaximumAlongScanDistortion","FL"], <del> [0x0022,0x0039,"OphthalmicImageOrientation","CS"], <del> [0x0022,0x0041,"DepthOfTransverseImage","FL"], <del> [0x0022,0x0042,"MydriaticAgentConcentrationUnitsSequence","SQ"], <del> [0x0022,0x0048,"AcrossScanSpatialResolution","FL"], <del> [0x0022,0x0049,"MaximumAcrossScanDistortion","FL"], <del> [0x0022,0x004E,"MydriaticAgentConcentration","DS"], <del> [0x0022,0x0055,"IlluminationWaveLength","FL"], <del> [0x0022,0x0056,"IlluminationPower","FL"], <del> [0x0022,0x0057,"IlluminationBandwidth","FL"], <del> [0x0022,0x0058,"MydriaticAgentSequence","SQ"], <del> [0x0022,0x1007,"OphthalmicAxialMeasurementsRightEyeSequence","SQ"], <del> [0x0022,0x1008,"OphthalmicAxialMeasurementsLeftEyeSequence","SQ"], <del> [0x0022,0x1010,"OphthalmicAxialLengthMeasurementsType","CS"], <del> [0x0022,0x1019,"OphthalmicAxialLength","FL"], <del> [0x0022,0x1024,"LensStatusCodeSequence","SQ"], <del> [0x0022,0x1025,"VitreousStatusCodeSequence","SQ"], <del> [0x0022,0x1028,"IOLFormulaCodeSequence","SQ"], <del> [0x0022,0x1029,"IOLFormulaDetail","LO"], <del> [0x0022,0x1033,"KeratometerIndex","FL"], <del> [0x0022,0x1035,"SourceOfOphthalmicAxialLengthCodeSequence","SQ"], <del> [0x0022,0x1037,"TargetRefraction","FL"], <del> [0x0022,0x1039,"RefractiveProcedureOccurred","CS"], <del> [0x0022,0x1040,"RefractiveSurgeryTypeCodeSequence","SQ"], <del> [0x0022,0x1044,"OphthalmicUltrasoundAxialMeasurementsTypeCodeSequence","SQ"], <del> [0x0022,0x1050,"OphthalmicAxialLengthMeasurementsSequence","SQ"], <del> [0x0022,0x1053,"IOLPower","FL"], <del> [0x0022,0x1054,"PredictedRefractiveError","FL"], <del> [0x0022,0x1059,"OphthalmicAxialLengthVelocity","FL"], <del> [0x0022,0x1065,"LensStatusDescription","LO"], <del> [0x0022,0x1066,"VitreousStatusDescription","LO"], <del> [0x0022,0x1090,"IOLPowerSequence","SQ"], <del> [0x0022,0x1092,"LensConstantSequence","SQ"], <del> [0x0022,0x1093,"IOLManufacturer","LO"], <del> [0x0022,0x1094,"LensConstantDescription","LO"], <del> [0x0022,0x1096,"KeratometryMeasurementTypeCodeSequence","SQ"], <del> [0x0022,0x1100,"ReferencedOphthalmicAxialMeasurementsSequence","SQ"], <del> [0x0022,0x1101,"OphthalmicAxialLengthMeasurementsSegmentNameCodeSequence","SQ"], <del> [0x0022,0x1103,"RefractiveErrorBeforeRefractiveSurgeryCodeSequence","SQ"], <del> [0x0022,0x1121,"IOLPowerForExactEmmetropia","FL"], <del> [0x0022,0x1122,"IOLPowerForExactTargetRefraction","FL"], <del> [0x0022,0x1125,"AnteriorChamberDepthDefinitionCodeSequence","SQ"], <del> [0x0022,0x1130,"LensThickness","FL"], <del> [0x0022,0x1131,"AnteriorChamberDepth","FL"], <del> [0x0022,0x1132,"SourceOfLensThicknessDataCodeSequence","SQ"], <del> [0x0022,0x1133,"SourceOfAnteriorChamberDepthDataCodeSequence","SQ"], <del> [0x0022,0x1135,"SourceOfRefractiveErrorDataCodeSequence","SQ"], <del> [0x0022,0x1140,"OphthalmicAxialLengthMeasurementModified","CS"], <del> [0x0022,0x1150,"OphthalmicAxialLengthDataSourceCodeSequence","SQ"], <del> [0x0022,0x1153,"OphthalmicAxialLengthAcquisitionMethodCodeSequence","SQ"], <del> [0x0022,0x1155,"SignalToNoiseRatio","FL"], <del> [0x0022,0x1159,"OphthalmicAxialLengthDataSourceDescription","LO"], <del> [0x0022,0x1210,"OphthalmicAxialLengthMeasurementsTotalLengthSequence","SQ"], <del> [0x0022,0x1211,"OphthalmicAxialLengthMeasurementsSegmentalLengthSequence","SQ"], <del> [0x0022,0x1212,"OphthalmicAxialLengthMeasurementsLengthSummationSequence","SQ"], <del> [0x0022,0x1220,"UltrasoundOphthalmicAxialLengthMeasurementsSequence","SQ"], <del> [0x0022,0x1225,"OpticalOphthalmicAxialLengthMeasurementsSequence","SQ"], <del> [0x0022,0x1230,"UltrasoundSelectedOphthalmicAxialLengthSequence","SQ"], <del> [0x0022,0x1250,"OphthalmicAxialLengthSelectionMethodCodeSequence","SQ"], <del> [0x0022,0x1255,"OpticalSelectedOphthalmicAxialLengthSequence","SQ"], <del> [0x0022,0x1257,"SelectedSegmentalOphthalmicAxialLengthSequence","SQ"], <del> [0x0022,0x1260,"SelectedTotalOphthalmicAxialLengthSequence","SQ"], <del> [0x0022,0x1262,"OphthalmicAxialLengthQualityMetricSequence","SQ"], <del> [0x0022,0x1273,"OphthalmicAxialLengthQualityMetricTypeDescription","LO"], <del> [0x0022,0x1300,"IntraocularLensCalculationsRightEyeSequence","SQ"], <del> [0x0022,0x1310,"IntraocularLensCalculationsLeftEyeSequence","SQ"], <del> [0x0022,0x1330,"ReferencedOphthalmicAxialLengthMeasurementQCImageSequence","SQ"], <del> [0x0024,0x0010,"VisualFieldHorizontalExtent","FL"], <del> [0x0024,0x0011,"VisualFieldVerticalExtent","FL"], <del> [0x0024,0x0012,"VisualFieldShape","CS"], <del> [0x0024,0x0016,"ScreeningTestModeCodeSequence","SQ"], <del> [0x0024,0x0018,"MaximumStimulusLuminance","FL"], <del> [0x0024,0x0020,"BackgroundLuminance","FL"], <del> [0x0024,0x0021,"StimulusColorCodeSequence","SQ"], <del> [0x0024,0x0024,"BackgroundIlluminationColorCodeSequence","SQ"], <del> [0x0024,0x0025,"StimulusArea","FL"], <del> [0x0024,0x0028,"StimulusPresentationTime","FL"], <del> [0x0024,0x0032,"FixationSequence","SQ"], <del> [0x0024,0x0033,"FixationMonitoringCodeSequence","SQ"], <del> [0x0024,0x0034,"VisualFieldCatchTrialSequence","SQ"], <del> [0x0024,0x0035,"FixationCheckedQuantity","US"], <del> [0x0024,0x0036,"PatientNotProperlyFixatedQuantity","US"], <del> [0x0024,0x0037,"PresentedVisualStimuliDataFlag","CS"], <del> [0x0024,0x0038,"NumberOfVisualStimuli","US"], <del> [0x0024,0x0039,"ExcessiveFixationLossesDataFlag","CS"], <del> [0x0024,0x0040,"ExcessiveFixationLosses","CS"], <del> [0x0024,0x0042,"StimuliRetestingQuantity","US"], <del> [0x0024,0x0044,"CommentsOnPatientPerformanceOfVisualField","LT"], <del> [0x0024,0x0045,"FalseNegativesEstimateFlag","CS"], <del> [0x0024,0x0046,"FalseNegativesEstimate","FL"], <del> [0x0024,0x0048,"NegativeCatchTrialsQuantity","US"], <del> [0x0024,0x0050,"FalseNegativesQuantity","US"], <del> [0x0024,0x0051,"ExcessiveFalseNegativesDataFlag","CS"], <del> [0x0024,0x0052,"ExcessiveFalseNegatives","CS"], <del> [0x0024,0x0053,"FalsePositivesEstimateFlag","CS"], <del> [0x0024,0x0054,"FalsePositivesEstimate","FL"], <del> [0x0024,0x0055,"CatchTrialsDataFlag","CS"], <del> [0x0024,0x0056,"PositiveCatchTrialsQuantity","US"], <del> [0x0024,0x0057,"TestPointNormalsDataFlag","CS"], <del> [0x0024,0x0058,"TestPointNormalsSequence","SQ"], <del> [0x0024,0x0059,"GlobalDeviationProbabilityNormalsFlag","CS"], <del> [0x0024,0x0060,"FalsePositivesQuantity","US"], <del> [0x0024,0x0061,"ExcessiveFalsePositivesDataFlag","CS"], <del> [0x0024,0x0062,"ExcessiveFalsePositives","CS"], <del> [0x0024,0x0063,"VisualFieldTestNormalsFlag","CS"], <del> [0x0024,0x0064,"ResultsNormalsSequence","SQ"], <del> [0x0024,0x0065,"AgeCorrectedSensitivityDeviationAlgorithmSequence","SQ"], <del> [0x0024,0x0066,"GlobalDeviationFromNormal","FL"], <del> [0x0024,0x0067,"GeneralizedDefectSensitivityDeviationAlgorithmSequence","SQ"], <del> [0x0024,0x0068,"LocalizedDeviationfromNormal","FL"], <del> [0x0024,0x0069,"PatientReliabilityIndicator","LO"], <del> [0x0024,0x0070,"VisualFieldMeanSensitivity","FL"], <del> [0x0024,0x0071,"GlobalDeviationProbability","FL"], <del> [0x0024,0x0072,"LocalDeviationProbabilityNormalsFlag","CS"], <del> [0x0024,0x0073,"LocalizedDeviationProbability","FL"], <del> [0x0024,0x0074,"ShortTermFluctuationCalculated","CS"], <del> [0x0024,0x0075,"ShortTermFluctuation","FL"], <del> [0x0024,0x0076,"ShortTermFluctuationProbabilityCalculated","CS"], <del> [0x0024,0x0077,"ShortTermFluctuationProbability","FL"], <del> [0x0024,0x0078,"CorrectedLocalizedDeviationFromNormalCalculated","CS"], <del> [0x0024,0x0079,"CorrectedLocalizedDeviationFromNormal","FL"], <del> [0x0024,0x0080,"CorrectedLocalizedDeviationFromNormalProbabilityCalculated","CS"], <del> [0x0024,0x0081,"CorrectedLocalizedDeviationFromNormalProbability","FL"], <del> [0x0024,0x0083,"GlobalDeviationProbabilitySequence","SQ"], <del> [0x0024,0x0085,"LocalizedDeviationProbabilitySequence","SQ"], <del> [0x0024,0x0086,"FovealSensitivityMeasured","CS"], <del> [0x0024,0x0087,"FovealSensitivity","FL"], <del> [0x0024,0x0088,"VisualFieldTestDuration","FL"], <del> [0x0024,0x0089,"VisualFieldTestPointSequence","SQ"], <del> [0x0024,0x0090,"VisualFieldTestPointXCoordinate","FL"], <del> [0x0024,0x0091,"VisualFieldTestPointYCoordinate","FL"], <del> [0x0024,0x0092,"AgeCorrectedSensitivityDeviationValue","FL"], <del> [0x0024,0x0093,"StimulusResults","CS"], <del> [0x0024,0x0094,"SensitivityValue","FL"], <del> [0x0024,0x0095,"RetestStimulusSeen","CS"], <del> [0x0024,0x0096,"RetestSensitivityValue","FL"], <del> [0x0024,0x0097,"VisualFieldTestPointNormalsSequence","SQ"], <del> [0x0024,0x0098,"QuantifiedDefect","FL"], <del> [0x0024,0x0100,"AgeCorrectedSensitivityDeviationProbabilityValue","FL"], <del> [0x0024,0x0102,"GeneralizedDefectCorrectedSensitivityDeviationFlag ","CS"], <del> [0x0024,0x0103,"GeneralizedDefectCorrectedSensitivityDeviationValue ","FL"], <del> [0x0024,0x0104,"GeneralizedDefectCorrectedSensitivityDeviationProbabilityValue","FL"], <del> [0x0024,0x0105,"MinimumSensitivityValue","FL "], <del> [0x0024,0x0106,"BlindSpotLocalized","CS"], <del> [0x0024,0x0107,"BlindSpotXCoordinate","FL"], <del> [0x0024,0x0108,"BlindSpotYCoordinate ","FL"], <del> [0x0024,0x0110,"VisualAcuityMeasurementSequence","SQ"], <del> [0x0024,0x0112,"RefractiveParametersUsedOnPatientSequence","SQ"], <del> [0x0024,0x0113,"MeasurementLaterality","CS"], <del> [0x0024,0x0114,"OphthalmicPatientClinicalInformationLeftEyeSequence","SQ"], <del> [0x0024,0x0115,"OphthalmicPatientClinicalInformationRightEyeSequence","SQ"], <del> [0x0024,0x0117,"FovealPointNormativeDataFlag","CS"], <del> [0x0024,0x0118,"FovealPointProbabilityValue","FL"], <del> [0x0024,0x0120,"ScreeningBaselineMeasured","CS"], <del> [0x0024,0x0122,"ScreeningBaselineMeasuredSequence","SQ"], <del> [0x0024,0x0124,"ScreeningBaselineType","CS"], <del> [0x0024,0x0126,"ScreeningBaselineValue","FL"], <del> [0x0024,0x0202,"AlgorithmSource","LO"], <del> [0x0024,0x0306,"DataSetName","LO"], <del> [0x0024,0x0307,"DataSetVersion","LO"], <del> [0x0024,0x0308,"DataSetSource","LO"], <del> [0x0024,0x0309,"DataSetDescription","LO"], <del> [0x0024,0x0317,"VisualFieldTestReliabilityGlobalIndexSequence","SQ"], <del> [0x0024,0x0320,"VisualFieldGlobalResultsIndexSequence","SQ"], <del> [0x0024,0x0325,"DataObservationSequence","SQ"], <del> [0x0024,0x0338,"IndexNormalsFlag","CS"], <del> [0x0024,0x0341,"IndexProbability","FL"], <del> [0x0024,0x0344,"IndexProbabilitySequence","SQ"], <del> [0x0028,0x0002,"SamplesPerPixel","US"], <del> [0x0028,0x0003,"SamplesPerPixelUsed","US"], <del> [0x0028,0x0004,"PhotometricInterpretation","CS"], <del> [0x0028,0x0005,"ImageDimensions","US"], <del> [0x0028,0x0006,"PlanarConfiguration","US"], <del> [0x0028,0x0008,"NumberOfFrames","IS"], <del> [0x0028,0x0009,"FrameIncrementPointer","AT"], <del> [0x0028,0x000A,"FrameDimensionPointer","AT"], <del> [0x0028,0x0010,"Rows","US"], <del> [0x0028,0x0011,"Columns","US"], <del> [0x0028,0x0012,"Planes","US"], <del> [0x0028,0x0014,"UltrasoundColorDataPresent","US"], <del> [0x0028,0x0030,"PixelSpacing","DS"], <del> [0x0028,0x0031,"ZoomFactor","DS"], <del> [0x0028,0x0032,"ZoomCenter","DS"], <del> [0x0028,0x0034,"PixelAspectRatio","IS"], <del> [0x0028,0x0040,"ImageFormat","CS"], <del> [0x0028,0x0050,"ManipulatedImage","LO"], <del> [0x0028,0x0051,"CorrectedImage","CS"], <del> [0x0028,0x005F,"CompressionRecognitionCode","LO"], <del> [0x0028,0x0060,"CompressionCode","CS"], <del> [0x0028,0x0061,"CompressionOriginator","SH"], <del> [0x0028,0x0062,"CompressionLabel","LO"], <del> [0x0028,0x0063,"CompressionDescription","SH"], <del> [0x0028,0x0065,"CompressionSequence","CS"], <del> [0x0028,0x0066,"CompressionStepPointers","AT"], <del> [0x0028,0x0068,"RepeatInterval","US"], <del> [0x0028,0x0069,"BitsGrouped","US"], <del> [0x0028,0x0070,"PerimeterTable","US"], <del> [0x0028,0x0071,"PerimeterValue","SS"], <del> [0x0028,0x0080,"PredictorRows","US"], <del> [0x0028,0x0081,"PredictorColumns","US"], <del> [0x0028,0x0082,"PredictorConstants","US"], <del> [0x0028,0x0090,"BlockedPixels","CS"], <del> [0x0028,0x0091,"BlockRows","US"], <del> [0x0028,0x0092,"BlockColumns","US"], <del> [0x0028,0x0093,"RowOverlap","US"], <del> [0x0028,0x0094,"ColumnOverlap","US"], <del> [0x0028,0x0100,"BitsAllocated","US"], <del> [0x0028,0x0101,"BitsStored","US"], <del> [0x0028,0x0102,"HighBit","US"], <del> [0x0028,0x0103,"PixelRepresentation","US"], <del> [0x0028,0x0104,"SmallestValidPixelValue","SS"], <del> [0x0028,0x0105,"LargestValidPixelValue","SS"], <del> [0x0028,0x0106,"SmallestImagePixelValue","SS"], <del> [0x0028,0x0107,"LargestImagePixelValue","SS"], <del> [0x0028,0x0108,"SmallestPixelValueInSeries","SS"], <del> [0x0028,0x0109,"LargestPixelValueInSeries","SS"], <del> [0x0028,0x0110,"SmallestImagePixelValueInPlane","SS"], <del> [0x0028,0x0111,"LargestImagePixelValueInPlane","SS"], <del> [0x0028,0x0120,"PixelPaddingValue","SS"], <del> [0x0028,0x0121,"PixelPaddingRangeLimit","SS"], <del> [0x0028,0x0200,"ImageLocation","US"], <del> [0x0028,0x0300,"QualityControlImage","CS"], <del> [0x0028,0x0301,"BurnedInAnnotation","CS"], <del> [0x0028,0x0302,"RecognizableVisualFeatures","CS"], <del> [0x0028,0x0303,"LongitudinalTemporalInformationModified","CS"], <del> [0x0028,0x0400,"TransformLabel","LO"], <del> [0x0028,0x0401,"TransformVersionNumber","LO"], <del> [0x0028,0x0402,"NumberOfTransformSteps","US"], <del> [0x0028,0x0403,"SequenceOfCompressedData","LO"], <del> [0x0028,0x0404,"DetailsOfCoefficients","AT"], <del> [0x0028,0x0700,"DCTLabel","LO"], <del> [0x0028,0x0701,"DataBlockDescription","CS"], <del> [0x0028,0x0702,"DataBlock","AT"], <del> [0x0028,0x0710,"NormalizationFactorFormat","US"], <del> [0x0028,0x0720,"ZonalMapNumberFormat","US"], <del> [0x0028,0x0721,"ZonalMapLocation","AT"], <del> [0x0028,0x0722,"ZonalMapFormat","US"], <del> [0x0028,0x0730,"AdaptiveMapFormat","US"], <del> [0x0028,0x0740,"CodeNumberFormat","US"], <del> [0x0028,0x0A02,"PixelSpacingCalibrationType","CS"], <del> [0x0028,0x0A04,"PixelSpacingCalibrationDescription","LO"], <del> [0x0028,0x1040,"PixelIntensityRelationship","CS"], <del> [0x0028,0x1041,"PixelIntensityRelationshipSign","SS"], <del> [0x0028,0x1050,"WindowCenter","DS"], <del> [0x0028,0x1051,"WindowWidth","DS"], <del> [0x0028,0x1052,"RescaleIntercept","DS"], <del> [0x0028,0x1053,"RescaleSlope","DS"], <del> [0x0028,0x1054,"RescaleType","LO"], <del> [0x0028,0x1055,"WindowCenterWidthExplanation","LO"], <del> [0x0028,0x1056,"VOILUTFunction","CS"], <del> [0x0028,0x1080,"GrayScale","CS"], <del> [0x0028,0x1090,"RecommendedViewingMode","CS"], <del> [0x0028,0x1100,"GrayLookupTableDescriptor","SS"], <del> [0x0028,0x1101,"RedPaletteColorLookupTableDescriptor","SS"], <del> [0x0028,0x1102,"GreenPaletteColorLookupTableDescriptor","SS"], <del> [0x0028,0x1103,"BluePaletteColorLookupTableDescriptor","SS"], <del> [0x0028,0x1104,"AlphaPaletteColorLookupTableDescriptor","US"], <del> [0x0028,0x1111,"LargeRedPaletteColorLookupTableDescriptor","SS"], <del> [0x0028,0x1112,"LargeGreenPaletteColorLookupTableDescriptor","SS"], <del> [0x0028,0x1113,"LargeBluePaletteColorLookupTableDescriptor","SS"], <del> [0x0028,0x1199,"PaletteColorLookupTableUID","UI"], <del> [0x0028,0x1200,"GrayLookupTableData","OW"], <del> [0x0028,0x1201,"RedPaletteColorLookupTableData","OW"], <del> [0x0028,0x1202,"GreenPaletteColorLookupTableData","OW"], <del> [0x0028,0x1203,"BluePaletteColorLookupTableData","OW"], <del> [0x0028,0x1204,"AlphaPaletteColorLookupTableData","OW"], <del> [0x0028,0x1211,"LargeRedPaletteColorLookupTableData","OW"], <del> [0x0028,0x1212,"LargeGreenPaletteColorLookupTableData","OW"], <del> [0x0028,0x1213,"LargeBluePaletteColorLookupTableData","OW"], <del> [0x0028,0x1214,"LargePaletteColorLookupTableUID","UI"], <del> [0x0028,0x1221,"SegmentedRedPaletteColorLookupTableData","OW"], <del> [0x0028,0x1222,"SegmentedGreenPaletteColorLookupTableData","OW"], <del> [0x0028,0x1223,"SegmentedBluePaletteColorLookupTableData","OW"], <del> [0x0028,0x1300,"BreastImplantPresent","CS"], <del> [0x0028,0x1350,"PartialView","CS"], <del> [0x0028,0x1351,"PartialViewDescription","ST"], <del> [0x0028,0x1352,"PartialViewCodeSequence","SQ"], <del> [0x0028,0x135A,"SpatialLocationsPreserved","CS"], <del> [0x0028,0x1401,"DataFrameAssignmentSequence","SQ"], <del> [0x0028,0x1402,"DataPathAssignment","CS"], <del> [0x0028,0x1403,"BitsMappedToColorLookupTable","US"], <del> [0x0028,0x1404,"BlendingLUT1Sequence","SQ"], <del> [0x0028,0x1405,"BlendingLUT1TransferFunction","CS"], <del> [0x0028,0x1406,"BlendingWeightConstant","FD"], <del> [0x0028,0x1407,"BlendingLookupTableDescriptor","US"], <del> [0x0028,0x1408,"BlendingLookupTableData","OW"], <del> [0x0028,0x140B,"EnhancedPaletteColorLookupTableSequence","SQ"], <del> [0x0028,0x140C,"BlendingLUT2Sequence","SQ"], <del> [0x0028,0x140D,"BlendingLUT2TransferFunction","CS"], <del> [0x0028,0x140E,"DataPathID","CS"], <del> [0x0028,0x140F,"RGBLUTTransferFunction","CS"], <del> [0x0028,0x1410,"AlphaLUTTransferFunction","CS"], <del> [0x0028,0x2000,"ICCProfile","OB"], <del> [0x0028,0x2110,"LossyImageCompression","CS"], <del> [0x0028,0x2112,"LossyImageCompressionRatio","DS"], <del> [0x0028,0x2114,"LossyImageCompressionMethod","CS"], <del> [0x0028,0x3000,"ModalityLUTSequence","SQ"], <del> [0x0028,0x3002,"LUTDescriptor","SS"], <del> [0x0028,0x3003,"LUTExplanation","LO"], <del> [0x0028,0x3004,"ModalityLUTType","LO"], <del> [0x0028,0x3006,"LUTData","OW"], <del> [0x0028,0x3010,"VOILUTSequence","SQ"], <del> [0x0028,0x3110,"SoftcopyVOILUTSequence","SQ"], <del> [0x0028,0x4000,"ImagePresentationComments","LT"], <del> [0x0028,0x5000,"BiPlaneAcquisitionSequence","SQ"], <del> [0x0028,0x6010,"RepresentativeFrameNumber","US"], <del> [0x0028,0x6020,"FrameNumbersOfInterest","US"], <del> [0x0028,0x6022,"FrameOfInterestDescription","LO"], <del> [0x0028,0x6023,"FrameOfInterestType","CS"], <del> [0x0028,0x6030,"MaskPointers","US"], <del> [0x0028,0x6040,"RWavePointer","US"], <del> [0x0028,0x6100,"MaskSubtractionSequence","SQ"], <del> [0x0028,0x6101,"MaskOperation","CS"], <del> [0x0028,0x6102,"ApplicableFrameRange","US"], <del> [0x0028,0x6110,"MaskFrameNumbers","US"], <del> [0x0028,0x6112,"ContrastFrameAveraging","US"], <del> [0x0028,0x6114,"MaskSubPixelShift","FL"], <del> [0x0028,0x6120,"TIDOffset","SS"], <del> [0x0028,0x6190,"MaskOperationExplanation","ST"], <del> [0x0028,0x7FE0,"PixelDataProviderURL","UT"], <del> [0x0028,0x9001,"DataPointRows","UL"], <del> [0x0028,0x9002,"DataPointColumns","UL"], <del> [0x0028,0x9003,"SignalDomainColumns","CS"], <del> [0x0028,0x9099,"LargestMonochromePixelValue","US"], <del> [0x0028,0x9108,"DataRepresentation","CS"], <del> [0x0028,0x9110,"PixelMeasuresSequence","SQ"], <del> [0x0028,0x9132,"FrameVOILUTSequence","SQ"], <del> [0x0028,0x9145,"PixelValueTransformationSequence","SQ"], <del> [0x0028,0x9235,"SignalDomainRows","CS"], <del> [0x0028,0x9411,"DisplayFilterPercentage","FL"], <del> [0x0028,0x9415,"FramePixelShiftSequence","SQ"], <del> [0x0028,0x9416,"SubtractionItemID","US"], <del> [0x0028,0x9422,"PixelIntensityRelationshipLUTSequence","SQ"], <del> [0x0028,0x9443,"FramePixelDataPropertiesSequence","SQ"], <del> [0x0028,0x9444,"GeometricalProperties","CS"], <del> [0x0028,0x9445,"GeometricMaximumDistortion","FL"], <del> [0x0028,0x9446,"ImageProcessingApplied","CS"], <del> [0x0028,0x9454,"MaskSelectionMode","CS"], <del> [0x0028,0x9474,"LUTFunction","CS"], <del> [0x0028,0x9478,"MaskVisibilityPercentage","FL"], <del> [0x0028,0x9501,"PixelShiftSequence","SQ"], <del> [0x0028,0x9502,"RegionPixelShiftSequence","SQ"], <del> [0x0028,0x9503,"VerticesOfTheRegion","SS"], <del> [0x0028,0x9505,"MultiFramePresentationSequence","SQ"], <del> [0x0028,0x9506,"PixelShiftFrameRange","US"], <del> [0x0028,0x9507,"LUTFrameRange","US"], <del> [0x0028,0x9520,"ImageToEquipmentMappingMatrix","DS"], <del> [0x0028,0x9537,"EquipmentCoordinateSystemIdentification","CS"], <del> [0x0032,0x000A,"StudyStatusID","CS"], <del> [0x0032,0x000C,"StudyPriorityID","CS"], <del> [0x0032,0x0012,"StudyIDIssuer","LO"], <del> [0x0032,0x0032,"StudyVerifiedDate","DA"], <del> [0x0032,0x0033,"StudyVerifiedTime","TM"], <del> [0x0032,0x0034,"StudyReadDate","DA"], <del> [0x0032,0x0035,"StudyReadTime","TM"], <del> [0x0032,0x1000,"ScheduledStudyStartDate","DA"], <del> [0x0032,0x1001,"ScheduledStudyStartTime","TM"], <del> [0x0032,0x1010,"ScheduledStudyStopDate","DA"], <del> [0x0032,0x1011,"ScheduledStudyStopTime","TM"], <del> [0x0032,0x1020,"ScheduledStudyLocation","LO"], <del> [0x0032,0x1021,"ScheduledStudyLocationAETitle","AE"], <del> [0x0032,0x1030,"ReasonForStudy","LO"], <del> [0x0032,0x1031,"RequestingPhysicianIdentificationSequence","SQ"], <del> [0x0032,0x1032,"RequestingPhysician","PN"], <del> [0x0032,0x1033,"RequestingService","LO"], <del> [0x0032,0x1034,"RequestingServiceCodeSequence","SQ"], <del> [0x0032,0x1040,"StudyArrivalDate","DA"], <del> [0x0032,0x1041,"StudyArrivalTime","TM"], <del> [0x0032,0x1050,"StudyCompletionDate","DA"], <del> [0x0032,0x1051,"StudyCompletionTime","TM"], <del> [0x0032,0x1055,"StudyComponentStatusID","CS"], <del> [0x0032,0x1060,"RequestedProcedureDescription","LO"], <del> [0x0032,0x1064,"RequestedProcedureCodeSequence","SQ"], <del> [0x0032,0x1070,"RequestedContrastAgent","LO"], <del> [0x0032,0x4000,"StudyComments","LT"], <del> [0x0038,0x0004,"ReferencedPatientAliasSequence","SQ"], <del> [0x0038,0x0008,"VisitStatusID","CS"], <del> [0x0038,0x0010,"AdmissionID","LO"], <del> [0x0038,0x0011,"IssuerOfAdmissionID","LO"], <del> [0x0038,0x0014,"IssuerOfAdmissionIDSequence","SQ"], <del> [0x0038,0x0016,"RouteOfAdmissions","LO"], <del> [0x0038,0x001A,"ScheduledAdmissionDate","DA"], <del> [0x0038,0x001B,"ScheduledAdmissionTime","TM"], <del> [0x0038,0x001C,"ScheduledDischargeDate","DA"], <del> [0x0038,0x001D,"ScheduledDischargeTime","TM"], <del> [0x0038,0x001E,"ScheduledPatientInstitutionResidence","LO"], <del> [0x0038,0x0020,"AdmittingDate","DA"], <del> [0x0038,0x0021,"AdmittingTime","TM"], <del> [0x0038,0x0030,"DischargeDate","DA"], <del> [0x0038,0x0032,"DischargeTime","TM"], <del> [0x0038,0x0040,"DischargeDiagnosisDescription","LO"], <del> [0x0038,0x0044,"DischargeDiagnosisCodeSequence","SQ"], <del> [0x0038,0x0050,"SpecialNeeds","LO"], <del> [0x0038,0x0060,"ServiceEpisodeID","LO"], <del> [0x0038,0x0061,"IssuerOfServiceEpisodeID","LO"], <del> [0x0038,0x0062,"ServiceEpisodeDescription","LO"], <del> [0x0038,0x0064,"IssuerOfServiceEpisodeIDSequence","SQ"], <del> [0x0038,0x0100,"PertinentDocumentsSequence","SQ"], <del> [0x0038,0x0300,"CurrentPatientLocation","LO"], <del> [0x0038,0x0400,"PatientInstitutionResidence","LO"], <del> [0x0038,0x0500,"PatientState","LO"], <del> [0x0038,0x0502,"PatientClinicalTrialParticipationSequence","SQ"], <del> [0x0038,0x4000,"VisitComments","LT"], <del> [0x003A,0x0004,"WaveformOriginality","CS"], <del> [0x003A,0x0005,"NumberOfWaveformChannels","US"], <del> [0x003A,0x0010,"NumberOfWaveformSamples","UL"], <del> [0x003A,0x001A,"SamplingFrequency","DS"], <del> [0x003A,0x0020,"MultiplexGroupLabel","SH"], <del> [0x003A,0x0200,"ChannelDefinitionSequence","SQ"], <del> [0x003A,0x0202,"WaveformChannelNumber","IS"], <del> [0x003A,0x0203,"ChannelLabel","SH"], <del> [0x003A,0x0205,"ChannelStatus","CS"], <del> [0x003A,0x0208,"ChannelSourceSequence","SQ"], <del> [0x003A,0x0209,"ChannelSourceModifiersSequence","SQ"], <del> [0x003A,0x020A,"SourceWaveformSequence","SQ"], <del> [0x003A,0x020C,"ChannelDerivationDescription","LO"], <del> [0x003A,0x0210,"ChannelSensitivity","DS"], <del> [0x003A,0x0211,"ChannelSensitivityUnitsSequence","SQ"], <del> [0x003A,0x0212,"ChannelSensitivityCorrectionFactor","DS"], <del> [0x003A,0x0213,"ChannelBaseline","DS"], <del> [0x003A,0x0214,"ChannelTimeSkew","DS"], <del> [0x003A,0x0215,"ChannelSampleSkew","DS"], <del> [0x003A,0x0218,"ChannelOffset","DS"], <del> [0x003A,0x021A,"WaveformBitsStored","US"], <del> [0x003A,0x0220,"FilterLowFrequency","DS"], <del> [0x003A,0x0221,"FilterHighFrequency","DS"], <del> [0x003A,0x0222,"NotchFilterFrequency","DS"], <del> [0x003A,0x0223,"NotchFilterBandwidth","DS"], <del> [0x003A,0x0230,"WaveformDataDisplayScale","FL"], <del> [0x003A,0x0231,"WaveformDisplayBackgroundCIELabValue","US"], <del> [0x003A,0x0240,"WaveformPresentationGroupSequence","SQ"], <del> [0x003A,0x0241,"PresentationGroupNumber","US"], <del> [0x003A,0x0242,"ChannelDisplaySequence","SQ"], <del> [0x003A,0x0244,"ChannelRecommendedDisplayCIELabValue","US"], <del> [0x003A,0x0245,"ChannelPosition","FL"], <del> [0x003A,0x0246,"DisplayShadingFlag","CS"], <del> [0x003A,0x0247,"FractionalChannelDisplayScale","FL"], <del> [0x003A,0x0248,"AbsoluteChannelDisplayScale","FL"], <del> [0x003A,0x0300,"MultiplexedAudioChannelsDescriptionCodeSequence","SQ"], <del> [0x003A,0x0301,"ChannelIdentificationCode","IS"], <del> [0x003A,0x0302,"ChannelMode","CS"], <del> [0x0040,0x0001,"ScheduledStationAETitle","AE"], <del> [0x0040,0x0002,"ScheduledProcedureStepStartDate","DA"], <del> [0x0040,0x0003,"ScheduledProcedureStepStartTime","TM"], <del> [0x0040,0x0004,"ScheduledProcedureStepEndDate","DA"], <del> [0x0040,0x0005,"ScheduledProcedureStepEndTime","TM"], <del> [0x0040,0x0006,"ScheduledPerformingPhysicianName","PN"], <del> [0x0040,0x0007,"ScheduledProcedureStepDescription","LO"], <del> [0x0040,0x0008,"ScheduledProtocolCodeSequence","SQ"], <del> [0x0040,0x0009,"ScheduledProcedureStepID","SH"], <del> [0x0040,0x000A,"StageCodeSequence","SQ"], <del> [0x0040,0x000B,"ScheduledPerformingPhysicianIdentificationSequence","SQ"], <del> [0x0040,0x0010,"ScheduledStationName","SH"], <del> [0x0040,0x0011,"ScheduledProcedureStepLocation","SH"], <del> [0x0040,0x0012,"PreMedication","LO"], <del> [0x0040,0x0020,"ScheduledProcedureStepStatus","CS"], <del> [0x0040,0x0026,"OrderPlacerIdentifierSequence","SQ"], <del> [0x0040,0x0027,"OrderFillerIdentifierSequence","SQ"], <del> [0x0040,0x0031,"LocalNamespaceEntityID","UT"], <del> [0x0040,0x0032,"UniversalEntityID","UT"], <del> [0x0040,0x0033,"UniversalEntityIDType","CS"], <del> [0x0040,0x0035,"IdentifierTypeCode","CS"], <del> [0x0040,0x0036,"AssigningFacilitySequence","SQ"], <del> [0x0040,0x0039,"AssigningJurisdictionCodeSequence","SQ"], <del> [0x0040,0x003A,"AssigningAgencyOrDepartmentCodeSequence","SQ"], <del> [0x0040,0x0100,"ScheduledProcedureStepSequence","SQ"], <del> [0x0040,0x0220,"ReferencedNonImageCompositeSOPInstanceSequence","SQ"], <del> [0x0040,0x0241,"PerformedStationAETitle","AE"], <del> [0x0040,0x0242,"PerformedStationName","SH"], <del> [0x0040,0x0243,"PerformedLocation","SH"], <del> [0x0040,0x0244,"PerformedProcedureStepStartDate","DA"], <del> [0x0040,0x0245,"PerformedProcedureStepStartTime","TM"], <del> [0x0040,0x0250,"PerformedProcedureStepEndDate","DA"], <del> [0x0040,0x0251,"PerformedProcedureStepEndTime","TM"], <del> [0x0040,0x0252,"PerformedProcedureStepStatus","CS"], <del> [0x0040,0x0253,"PerformedProcedureStepID","SH"], <del> [0x0040,0x0254,"PerformedProcedureStepDescription","LO"], <del> [0x0040,0x0255,"PerformedProcedureTypeDescription","LO"], <del> [0x0040,0x0260,"PerformedProtocolCodeSequence","SQ"], <del> [0x0040,0x0261,"PerformedProtocolType","CS"], <del> [0x0040,0x0270,"ScheduledStepAttributesSequence","SQ"], <del> [0x0040,0x0275,"RequestAttributesSequence","SQ"], <del> [0x0040,0x0280,"CommentsOnThePerformedProcedureStep","ST"], <del> [0x0040,0x0281,"PerformedProcedureStepDiscontinuationReasonCodeSequence","SQ"], <del> [0x0040,0x0293,"QuantitySequence","SQ"], <del> [0x0040,0x0294,"Quantity","DS"], <del> [0x0040,0x0295,"MeasuringUnitsSequence","SQ"], <del> [0x0040,0x0296,"BillingItemSequence","SQ"], <del> [0x0040,0x0300,"TotalTimeOfFluoroscopy","US"], <del> [0x0040,0x0301,"TotalNumberOfExposures","US"], <del> [0x0040,0x0302,"EntranceDose","US"], <del> [0x0040,0x0303,"ExposedArea","US"], <del> [0x0040,0x0306,"DistanceSourceToEntrance","DS"], <del> [0x0040,0x0307,"DistanceSourceToSupport","DS"], <del> [0x0040,0x030E,"ExposureDoseSequence","SQ"], <del> [0x0040,0x0310,"CommentsOnRadiationDose","ST"], <del> [0x0040,0x0312,"XRayOutput","DS"], <del> [0x0040,0x0314,"HalfValueLayer","DS"], <del> [0x0040,0x0316,"OrganDose","DS"], <del> [0x0040,0x0318,"OrganExposed","CS"], <del> [0x0040,0x0320,"BillingProcedureStepSequence","SQ"], <del> [0x0040,0x0321,"FilmConsumptionSequence","SQ"], <del> [0x0040,0x0324,"BillingSuppliesAndDevicesSequence","SQ"], <del> [0x0040,0x0330,"ReferencedProcedureStepSequence","SQ"], <del> [0x0040,0x0340,"PerformedSeriesSequence","SQ"], <del> [0x0040,0x0400,"CommentsOnTheScheduledProcedureStep","LT"], <del> [0x0040,0x0440,"ProtocolContextSequence","SQ"], <del> [0x0040,0x0441,"ContentItemModifierSequence","SQ"], <del> [0x0040,0x0500,"ScheduledSpecimenSequence","SQ"], <del> [0x0040,0x050A,"SpecimenAccessionNumber","LO"], <del> [0x0040,0x0512,"ContainerIdentifier","LO"], <del> [0x0040,0x0513,"IssuerOfTheContainerIdentifierSequence","SQ"], <del> [0x0040,0x0515,"AlternateContainerIdentifierSequence","SQ"], <del> [0x0040,0x0518,"ContainerTypeCodeSequence","SQ"], <del> [0x0040,0x051A,"ContainerDescription","LO"], <del> [0x0040,0x0520,"ContainerComponentSequence","SQ"], <del> [0x0040,0x0550,"SpecimenSequence","SQ"], <del> [0x0040,0x0551,"SpecimenIdentifier","LO"], <del> [0x0040,0x0552,"SpecimenDescriptionSequenceTrial","SQ"], <del> [0x0040,0x0553,"SpecimenDescriptionTrial","ST"], <del> [0x0040,0x0554,"SpecimenUID","UI"], <del> [0x0040,0x0555,"AcquisitionContextSequence","SQ"], <del> [0x0040,0x0556,"AcquisitionContextDescription","ST"], <del> [0x0040,0x059A,"SpecimenTypeCodeSequence","SQ"], <del> [0x0040,0x0560,"SpecimenDescriptionSequence","SQ"], <del> [0x0040,0x0562,"IssuerOfTheSpecimenIdentifierSequence","SQ"], <del> [0x0040,0x0600,"SpecimenShortDescription","LO"], <del> [0x0040,0x0602,"SpecimenDetailedDescription","UT"], <del> [0x0040,0x0610,"SpecimenPreparationSequence","SQ"], <del> [0x0040,0x0612,"SpecimenPreparationStepContentItemSequence","SQ"], <del> [0x0040,0x0620,"SpecimenLocalizationContentItemSequence","SQ"], <del> [0x0040,0x06FA,"SlideIdentifier","LO"], <del> [0x0040,0x071A,"ImageCenterPointCoordinatesSequence","SQ"], <del> [0x0040,0x072A,"XOffsetInSlideCoordinateSystem","DS"], <del> [0x0040,0x073A,"YOffsetInSlideCoordinateSystem","DS"], <del> [0x0040,0x074A,"ZOffsetInSlideCoordinateSystem","DS"], <del> [0x0040,0x08D8,"PixelSpacingSequence","SQ"], <del> [0x0040,0x08DA,"CoordinateSystemAxisCodeSequence","SQ"], <del> [0x0040,0x08EA,"MeasurementUnitsCodeSequence","SQ"], <del> [0x0040,0x09F8,"VitalStainCodeSequenceTrial","SQ"], <del> [0x0040,0x1001,"RequestedProcedureID","SH"], <del> [0x0040,0x1002,"ReasonForTheRequestedProcedure","LO"], <del> [0x0040,0x1003,"RequestedProcedurePriority","SH"], <del> [0x0040,0x1004,"PatientTransportArrangements","LO"], <del> [0x0040,0x1005,"RequestedProcedureLocation","LO"], <del> [0x0040,0x1006,"PlacerOrderNumberProcedure","SH"], <del> [0x0040,0x1007,"FillerOrderNumberProcedure","SH"], <del> [0x0040,0x1008,"ConfidentialityCode","LO"], <del> [0x0040,0x1009,"ReportingPriority","SH"], <del> [0x0040,0x100A,"ReasonForRequestedProcedureCodeSequence","SQ"], <del> [0x0040,0x1010,"NamesOfIntendedRecipientsOfResults","PN"], <del> [0x0040,0x1011,"IntendedRecipientsOfResultsIdentificationSequence","SQ"], <del> [0x0040,0x1012,"ReasonForPerformedProcedureCodeSequence","SQ"], <del> [0x0040,0x1060,"RequestedProcedureDescriptionTrial","LO"], <del> [0x0040,0x1101,"PersonIdentificationCodeSequence","SQ"], <del> [0x0040,0x1102,"PersonAddress","ST"], <del> [0x0040,0x1103,"PersonTelephoneNumbers","LO"], <del> [0x0040,0x1400,"RequestedProcedureComments","LT"], <del> [0x0040,0x2001,"ReasonForTheImagingServiceRequest","LO"], <del> [0x0040,0x2004,"IssueDateOfImagingServiceRequest","DA"], <del> [0x0040,0x2005,"IssueTimeOfImagingServiceRequest","TM"], <del> [0x0040,0x2006,"PlacerOrderNumberImagingServiceRequestRetired","SH"], <del> [0x0040,0x2007,"FillerOrderNumberImagingServiceRequestRetired","SH"], <del> [0x0040,0x2008,"OrderEnteredBy","PN"], <del> [0x0040,0x2009,"OrderEntererLocation","SH"], <del> [0x0040,0x2010,"OrderCallbackPhoneNumber","SH"], <del> [0x0040,0x2016,"PlacerOrderNumberImagingServiceRequest","LO"], <del> [0x0040,0x2017,"FillerOrderNumberImagingServiceRequest","LO"], <del> [0x0040,0x2400,"ImagingServiceRequestComments","LT"], <del> [0x0040,0x3001,"ConfidentialityConstraintOnPatientDataDescription","LO"], <del> [0x0040,0x4001,"GeneralPurposeScheduledProcedureStepStatus","CS"], <del> [0x0040,0x4002,"GeneralPurposePerformedProcedureStepStatus","CS"], <del> [0x0040,0x4003,"GeneralPurposeScheduledProcedureStepPriority","CS"], <del> [0x0040,0x4004,"ScheduledProcessingApplicationsCodeSequence","SQ"], <del> [0x0040,0x4005,"ScheduledProcedureStepStartDateTime","DT"], <del> [0x0040,0x4006,"MultipleCopiesFlag","CS"], <del> [0x0040,0x4007,"PerformedProcessingApplicationsCodeSequence","SQ"], <del> [0x0040,0x4009,"HumanPerformerCodeSequence","SQ"], <del> [0x0040,0x4010,"ScheduledProcedureStepModificationDateTime","DT"], <del> [0x0040,0x4011,"ExpectedCompletionDateTime","DT"], <del> [0x0040,0x4015,"ResultingGeneralPurposePerformedProcedureStepsSequence","SQ"], <del> [0x0040,0x4016,"ReferencedGeneralPurposeScheduledProcedureStepSequence","SQ"], <del> [0x0040,0x4018,"ScheduledWorkitemCodeSequence","SQ"], <del> [0x0040,0x4019,"PerformedWorkitemCodeSequence","SQ"], <del> [0x0040,0x4020,"InputAvailabilityFlag","CS"], <del> [0x0040,0x4021,"InputInformationSequence","SQ"], <del> [0x0040,0x4022,"RelevantInformationSequence","SQ"], <del> [0x0040,0x4023,"ReferencedGeneralPurposeScheduledProcedureStepTransactionUID","UI"], <del> [0x0040,0x4025,"ScheduledStationNameCodeSequence","SQ"], <del> [0x0040,0x4026,"ScheduledStationClassCodeSequence","SQ"], <del> [0x0040,0x4027,"ScheduledStationGeographicLocationCodeSequence","SQ"], <del> [0x0040,0x4028,"PerformedStationNameCodeSequence","SQ"], <del> [0x0040,0x4029,"PerformedStationClassCodeSequence","SQ"], <del> [0x0040,0x4030,"PerformedStationGeographicLocationCodeSequence","SQ"], <del> [0x0040,0x4031,"RequestedSubsequentWorkitemCodeSequence","SQ"], <del> [0x0040,0x4032,"NonDICOMOutputCodeSequence","SQ"], <del> [0x0040,0x4033,"OutputInformationSequence","SQ"], <del> [0x0040,0x4034,"ScheduledHumanPerformersSequence","SQ"], <del> [0x0040,0x4035,"ActualHumanPerformersSequence","SQ"], <del> [0x0040,0x4036,"HumanPerformerOrganization","LO"], <del> [0x0040,0x4037,"HumanPerformerName","PN"], <del> [0x0040,0x4040,"RawDataHandling","CS"], <del> [0x0040,0x4041,"InputReadinessState","CS"], <del> [0x0040,0x4050,"PerformedProcedureStepStartDateTime","DT"], <del> [0x0040,0x4051,"PerformedProcedureStepEndDateTime","DT"], <del> [0x0040,0x4052,"ProcedureStepCancellationDateTime","DT"], <del> [0x0040,0x8302,"EntranceDoseInmGy","DS"], <del> [0x0040,0x9094,"ReferencedImageRealWorldValueMappingSequence","SQ"], <del> [0x0040,0x9096,"RealWorldValueMappingSequence","SQ"], <del> [0x0040,0x9098,"PixelValueMappingCodeSequence","SQ"], <del> [0x0040,0x9210,"LUTLabel","SH"], <del> [0x0040,0x9211,"RealWorldValueLastValueMapped","SS"], <del> [0x0040,0x9212,"RealWorldValueLUTData","FD"], <del> [0x0040,0x9216,"RealWorldValueFirstValueMapped","SS"], <del> [0x0040,0x9224,"RealWorldValueIntercept","FD"], <del> [0x0040,0x9225,"RealWorldValueSlope","FD"], <del> [0x0040,0xA007,"FindingsFlagTrial","CS"], <del> [0x0040,0xA010,"RelationshipType","CS"], <del> [0x0040,0xA020,"FindingsSequenceTrial","SQ"], <del> [0x0040,0xA021,"FindingsGroupUIDTrial","UI"], <del> [0x0040,0xA022,"ReferencedFindingsGroupUIDTrial","UI"], <del> [0x0040,0xA023,"FindingsGroupRecordingDateTrial","DA"], <del> [0x0040,0xA024,"FindingsGroupRecordingTimeTrial","TM"], <del> [0x0040,0xA026,"FindingsSourceCategoryCodeSequenceTrial","SQ"], <del> [0x0040,0xA027,"VerifyingOrganization","LO"], <del> [0x0040,0xA028,"DocumentingOrganizationIdentifierCodeSequenceTrial","SQ"], <del> [0x0040,0xA030,"VerificationDateTime","DT"], <del> [0x0040,0xA032,"ObservationDateTime","DT"], <del> [0x0040,0xA040,"ValueType","CS"], <del> [0x0040,0xA043,"ConceptNameCodeSequence","SQ"], <del> [0x0040,0xA047,"MeasurementPrecisionDescriptionTrial","LO"], <del> [0x0040,0xA050,"ContinuityOfContent","CS"], <del> [0x0040,0xA057,"UrgencyOrPriorityAlertsTrial","CS"], <del> [0x0040,0xA060,"SequencingIndicatorTrial","LO"], <del> [0x0040,0xA066,"DocumentIdentifierCodeSequenceTrial","SQ"], <del> [0x0040,0xA067,"DocumentAuthorTrial","PN"], <del> [0x0040,0xA068,"DocumentAuthorIdentifierCodeSequenceTrial","SQ"], <del> [0x0040,0xA070,"IdentifierCodeSequenceTrial","SQ"], <del> [0x0040,0xA073,"VerifyingObserverSequence","SQ"], <del> [0x0040,0xA074,"ObjectBinaryIdentifierTrial","OB"], <del> [0x0040,0xA075,"VerifyingObserverName","PN"], <del> [0x0040,0xA076,"DocumentingObserverIdentifierCodeSequenceTrial","SQ"], <del> [0x0040,0xA078,"AuthorObserverSequence","SQ"], <del> [0x0040,0xA07A,"ParticipantSequence","SQ"], <del> [0x0040,0xA07C,"CustodialOrganizationSequence","SQ"], <del> [0x0040,0xA080,"ParticipationType","CS"], <del> [0x0040,0xA082,"ParticipationDateTime","DT"], <del> [0x0040,0xA084,"ObserverType","CS"], <del> [0x0040,0xA085,"ProcedureIdentifierCodeSequenceTrial","SQ"], <del> [0x0040,0xA088,"VerifyingObserverIdentificationCodeSequence","SQ"], <del> [0x0040,0xA089,"ObjectDirectoryBinaryIdentifierTrial","OB"], <del> [0x0040,0xA090,"EquivalentCDADocumentSequence","SQ"], <del> [0x0040,0xA0B0,"ReferencedWaveformChannels","US"], <del> [0x0040,0xA110,"DateOfDocumentOrVerbalTransactionTrial","DA"], <del> [0x0040,0xA112,"TimeOfDocumentCreationOrVerbalTransactionTrial","TM"], <del> [0x0040,0xA120,"DateTime","DT"], <del> [0x0040,0xA121,"Date","DA"], <del> [0x0040,0xA122,"Time","TM"], <del> [0x0040,0xA123,"PersonName","PN"], <del> [0x0040,0xA124,"UID","UI"], <del> [0x0040,0xA125,"ReportStatusIDTrial","CS"], <del> [0x0040,0xA130,"TemporalRangeType","CS"], <del> [0x0040,0xA132,"ReferencedSamplePositions","UL"], <del> [0x0040,0xA136,"ReferencedFrameNumbers","US"], <del> [0x0040,0xA138,"ReferencedTimeOffsets","DS"], <del> [0x0040,0xA13A,"ReferencedDateTime","DT"], <del> [0x0040,0xA160,"TextValue","UT"], <del> [0x0040,0xA167,"ObservationCategoryCodeSequenceTrial","SQ"], <del> [0x0040,0xA168,"ConceptCodeSequence","SQ"], <del> [0x0040,0xA16A,"BibliographicCitationTrial","ST"], <del> [0x0040,0xA170,"PurposeOfReferenceCodeSequence","SQ"], <del> [0x0040,0xA171,"ObservationUIDTrial","UI"], <del> [0x0040,0xA172,"ReferencedObservationUIDTrial","UI"], <del> [0x0040,0xA173,"ReferencedObservationClassTrial","CS"], <del> [0x0040,0xA174,"ReferencedObjectObservationClassTrial","CS"], <del> [0x0040,0xA180,"AnnotationGroupNumber","US"], <del> [0x0040,0xA192,"ObservationDateTrial","DA"], <del> [0x0040,0xA193,"ObservationTimeTrial","TM"], <del> [0x0040,0xA194,"MeasurementAutomationTrial","CS"], <del> [0x0040,0xA195,"ModifierCodeSequence","SQ"], <del> [0x0040,0xA224,"IdentificationDescriptionTrial","ST"], <del> [0x0040,0xA290,"CoordinatesSetGeometricTypeTrial","CS"], <del> [0x0040,0xA296,"AlgorithmCodeSequenceTrial","SQ"], <del> [0x0040,0xA297,"AlgorithmDescriptionTrial","ST"], <del> [0x0040,0xA29A,"PixelCoordinatesSetTrial","SL"], <del> [0x0040,0xA300,"MeasuredValueSequence","SQ"], <del> [0x0040,0xA301,"NumericValueQualifierCodeSequence","SQ"], <del> [0x0040,0xA307,"CurrentObserverTrial","PN"], <del> [0x0040,0xA30A,"NumericValue","DS"], <del> [0x0040,0xA313,"ReferencedAccessionSequenceTrial","SQ"], <del> [0x0040,0xA33A,"ReportStatusCommentTrial","ST"], <del> [0x0040,0xA340,"ProcedureContextSequenceTrial","SQ"], <del> [0x0040,0xA352,"VerbalSourceTrial","PN"], <del> [0x0040,0xA353,"AddressTrial","ST"], <del> [0x0040,0xA354,"TelephoneNumberTrial","LO"], <del> [0x0040,0xA358,"VerbalSourceIdentifierCodeSequenceTrial","SQ"], <del> [0x0040,0xA360,"PredecessorDocumentsSequence","SQ"], <del> [0x0040,0xA370,"ReferencedRequestSequence","SQ"], <del> [0x0040,0xA372,"PerformedProcedureCodeSequence","SQ"], <del> [0x0040,0xA375,"CurrentRequestedProcedureEvidenceSequence","SQ"], <del> [0x0040,0xA380,"ReportDetailSequenceTrial","SQ"], <del> [0x0040,0xA385,"PertinentOtherEvidenceSequence","SQ"], <del> [0x0040,0xA390,"HL7StructuredDocumentReferenceSequence","SQ"], <del> [0x0040,0xA402,"ObservationSubjectUIDTrial","UI"], <del> [0x0040,0xA403,"ObservationSubjectClassTrial","CS"], <del> [0x0040,0xA404,"ObservationSubjectTypeCodeSequenceTrial","SQ"], <del> [0x0040,0xA491,"CompletionFlag","CS"], <del> [0x0040,0xA492,"CompletionFlagDescription","LO"], <del> [0x0040,0xA493,"VerificationFlag","CS"], <del> [0x0040,0xA494,"ArchiveRequested","CS"], <del> [0x0040,0xA496,"PreliminaryFlag","CS"], <del> [0x0040,0xA504,"ContentTemplateSequence","SQ"], <del> [0x0040,0xA525,"IdenticalDocumentsSequence","SQ"], <del> [0x0040,0xA600,"ObservationSubjectContextFlagTrial","CS"], <del> [0x0040,0xA601,"ObserverContextFlagTrial","CS"], <del> [0x0040,0xA603,"ProcedureContextFlagTrial","CS"], <del> [0x0040,0xA730,"ContentSequence","SQ"], <del> [0x0040,0xA731,"RelationshipSequenceTrial","SQ"], <del> [0x0040,0xA732,"RelationshipTypeCodeSequenceTrial","SQ"], <del> [0x0040,0xA744,"LanguageCodeSequenceTrial","SQ"], <del> [0x0040,0xA992,"UniformResourceLocatorTrial","ST"], <del> [0x0040,0xB020,"WaveformAnnotationSequence","SQ"], <del> [0x0040,0xDB00,"TemplateIdentifier","CS"], <del> [0x0040,0xDB06,"TemplateVersion","DT"], <del> [0x0040,0xDB07,"TemplateLocalVersion","DT"], <del> [0x0040,0xDB0B,"TemplateExtensionFlag","CS"], <del> [0x0040,0xDB0C,"TemplateExtensionOrganizationUID","UI"], <del> [0x0040,0xDB0D,"TemplateExtensionCreatorUID","UI"], <del> [0x0040,0xDB73,"ReferencedContentItemIdentifier","UL"], <del> [0x0040,0xE001,"HL7InstanceIdentifier","ST"], <del> [0x0040,0xE004,"HL7DocumentEffectiveTime","DT"], <del> [0x0040,0xE006,"HL7DocumentTypeCodeSequence","SQ"], <del> [0x0040,0xE008,"DocumentClassCodeSequence","SQ"], <del> [0x0040,0xE010,"RetrieveURI","UT"], <del> [0x0040,0xE011,"RetrieveLocationUID","UI"], <del> [0x0040,0xE020,"TypeOfInstances","CS"], <del> [0x0040,0xE021,"DICOMRetrievalSequence","SQ"], <del> [0x0040,0xE022,"DICOMMediaRetrievalSequence","SQ"], <del> [0x0040,0xE023,"WADORetrievalSequence","SQ"], <del> [0x0040,0xE024,"XDSRetrievalSequence","SQ"], <del> [0x0040,0xE030,"RepositoryUniqueID","UI"], <del> [0x0040,0xE031,"HomeCommunityID","UI"], <del> [0x0042,0x0010,"DocumentTitle","ST"], <del> [0x0042,0x0011,"EncapsulatedDocument","OB"], <del> [0x0042,0x0012,"MIMETypeOfEncapsulatedDocument","LO"], <del> [0x0042,0x0013,"SourceInstanceSequence","SQ"], <del> [0x0042,0x0014,"ListOfMIMETypes","LO"], <del> [0x0044,0x0001,"ProductPackageIdentifier","ST"], <del> [0x0044,0x0002,"SubstanceAdministrationApproval","CS"], <del> [0x0044,0x0003,"ApprovalStatusFurtherDescription","LT"], <del> [0x0044,0x0004,"ApprovalStatusDateTime","DT"], <del> [0x0044,0x0007,"ProductTypeCodeSequence","SQ"], <del> [0x0044,0x0008,"ProductName","LO"], <del> [0x0044,0x0009,"ProductDescription","LT"], <del> [0x0044,0x000A,"ProductLotIdentifier","LO"], <del> [0x0044,0x000B,"ProductExpirationDateTime","DT"], <del> [0x0044,0x0010,"SubstanceAdministrationDateTime","DT"], <del> [0x0044,0x0011,"SubstanceAdministrationNotes","LO"], <del> [0x0044,0x0012,"SubstanceAdministrationDeviceID","LO"], <del> [0x0044,0x0013,"ProductParameterSequence","SQ"], <del> [0x0044,0x0019,"SubstanceAdministrationParameterSequence","SQ"], <del> [0x0046,0x0012,"LensDescription","LO"], <del> [0x0046,0x0014,"RightLensSequence","SQ"], <del> [0x0046,0x0015,"LeftLensSequence","SQ"], <del> [0x0046,0x0016,"UnspecifiedLateralityLensSequence","SQ"], <del> [0x0046,0x0018,"CylinderSequence","SQ"], <del> [0x0046,0x0028,"PrismSequence","SQ"], <del> [0x0046,0x0030,"HorizontalPrismPower","FD"], <del> [0x0046,0x0032,"HorizontalPrismBase","CS"], <del> [0x0046,0x0034,"VerticalPrismPower","FD"], <del> [0x0046,0x0036,"VerticalPrismBase","CS"], <del> [0x0046,0x0038,"LensSegmentType","CS"], <del> [0x0046,0x0040,"OpticalTransmittance","FD"], <del> [0x0046,0x0042,"ChannelWidth","FD"], <del> [0x0046,0x0044,"PupilSize","FD"], <del> [0x0046,0x0046,"CornealSize","FD"], <del> [0x0046,0x0050,"AutorefractionRightEyeSequence","SQ"], <del> [0x0046,0x0052,"AutorefractionLeftEyeSequence","SQ"], <del> [0x0046,0x0060,"DistancePupillaryDistance","FD"], <del> [0x0046,0x0062,"NearPupillaryDistance","FD"], <del> [0x0046,0x0063,"IntermediatePupillaryDistance","FD"], <del> [0x0046,0x0064,"OtherPupillaryDistance","FD"], <del> [0x0046,0x0070,"KeratometryRightEyeSequence","SQ"], <del> [0x0046,0x0071,"KeratometryLeftEyeSequence","SQ"], <del> [0x0046,0x0074,"SteepKeratometricAxisSequence","SQ"], <del> [0x0046,0x0075,"RadiusOfCurvature","FD"], <del> [0x0046,0x0076,"KeratometricPower","FD"], <del> [0x0046,0x0077,"KeratometricAxis","FD"], <del> [0x0046,0x0080,"FlatKeratometricAxisSequence","SQ"], <del> [0x0046,0x0092,"BackgroundColor","CS"], <del> [0x0046,0x0094,"Optotype","CS"], <del> [0x0046,0x0095,"OptotypePresentation","CS"], <del> [0x0046,0x0097,"SubjectiveRefractionRightEyeSequence","SQ"], <del> [0x0046,0x0098,"SubjectiveRefractionLeftEyeSequence","SQ"], <del> [0x0046,0x0100,"AddNearSequence","SQ"], <del> [0x0046,0x0101,"AddIntermediateSequence","SQ"], <del> [0x0046,0x0102,"AddOtherSequence","SQ"], <del> [0x0046,0x0104,"AddPower","FD"], <del> [0x0046,0x0106,"ViewingDistance","FD"], <del> [0x0046,0x0121,"VisualAcuityTypeCodeSequence","SQ"], <del> [0x0046,0x0122,"VisualAcuityRightEyeSequence","SQ"], <del> [0x0046,0x0123,"VisualAcuityLeftEyeSequence","SQ"], <del> [0x0046,0x0124,"VisualAcuityBothEyesOpenSequence","SQ"], <del> [0x0046,0x0125,"ViewingDistanceType","CS"], <del> [0x0046,0x0135,"VisualAcuityModifiers","SS"], <del> [0x0046,0x0137,"DecimalVisualAcuity","FD"], <del> [0x0046,0x0139,"OptotypeDetailedDefinition","LO"], <del> [0x0046,0x0145,"ReferencedRefractiveMeasurementsSequence","SQ"], <del> [0x0046,0x0146,"SpherePower","FD"], <del> [0x0046,0x0147,"CylinderPower","FD"], <del> [0x0048,0x0001,"ImagedVolumeWidth","FL"], <del> [0x0048,0x0002,"ImagedVolumeHeight","FL"], <del> [0x0048,0x0003,"ImagedVolumeDepth","FL"], <del> [0x0048,0x0006,"TotalPixelMatrixColumns","UL"], <del> [0x0048,0x0007,"TotalPixelMatrixRows","UL"], <del> [0x0048,0x0008,"TotalPixelMatrixOriginSequence","SQ"], <del> [0x0048,0x0010,"SpecimenLabelInImage","CS"], <del> [0x0048,0x0011,"FocusMethod","CS"], <del> [0x0048,0x0012,"ExtendedDepthOfField","CS"], <del> [0x0048,0x0013,"NumberOfFocalPlanes","US"], <del> [0x0048,0x0014,"DistanceBetweenFocalPlanes","FL"], <del> [0x0048,0x0015,"RecommendedAbsentPixelCIELabValue","US"], <del> [0x0048,0x0100,"IlluminatorTypeCodeSequence","SQ"], <del> [0x0048,0x0102,"ImageOrientationSlide","DS"], <del> [0x0048,0x0105,"OpticalPathSequence","SQ"], <del> [0x0048,0x0106,"OpticalPathIdentifier","SH"], <del> [0x0048,0x0107,"OpticalPathDescription","ST"], <del> [0x0048,0x0108,"IlluminationColorCodeSequence","SQ"], <del> [0x0048,0x0110,"SpecimenReferenceSequence","SQ"], <del> [0x0048,0x0111,"CondenserLensPower","DS"], <del> [0x0048,0x0112,"ObjectiveLensPower","DS"], <del> [0x0048,0x0113,"ObjectiveLensNumericalAperture","DS"], <del> [0x0048,0x0120,"PaletteColorLookupTableSequence","SQ"], <del> [0x0048,0x0200,"ReferencedImageNavigationSequence","SQ"], <del> [0x0048,0x0201,"TopLeftHandCornerOfLocalizerArea","US"], <del> [0x0048,0x0202,"BottomRightHandCornerOfLocalizerArea","US"], <del> [0x0048,0x0207,"OpticalPathIdentificationSequence","SQ"], <del> [0x0048,0x021A,"PlanePositionSlideSequence","SQ"], <del> [0x0048,0x021E,"RowPositionInTotalImagePixelMatrix","SL"], <del> [0x0048,0x021F,"ColumnPositionInTotalImagePixelMatrix","SL"], <del> [0x0048,0x0301,"PixelOriginInterpretation","CS"], <del> [0x0050,0x0004,"CalibrationImage","CS"], <del> [0x0050,0x0010,"DeviceSequence","SQ"], <del> [0x0050,0x0012,"ContainerComponentTypeCodeSequence","SQ"], <del> [0x0050,0x0013,"ContainerComponentThickness","FD"], <del> [0x0050,0x0014,"DeviceLength","DS"], <del> [0x0050,0x0015,"ContainerComponentWidth","FD"], <del> [0x0050,0x0016,"DeviceDiameter","DS"], <del> [0x0050,0x0017,"DeviceDiameterUnits","CS"], <del> [0x0050,0x0018,"DeviceVolume","DS"], <del> [0x0050,0x0019,"InterMarkerDistance","DS"], <del> [0x0050,0x001A,"ContainerComponentMaterial","CS"], <del> [0x0050,0x001B,"ContainerComponentID","LO"], <del> [0x0050,0x001C,"ContainerComponentLength","FD"], <del> [0x0050,0x001D,"ContainerComponentDiameter","FD"], <del> [0x0050,0x001E,"ContainerComponentDescription","LO"], <del> [0x0050,0x0020,"DeviceDescription","LO"], <del> [0x0052,0x0001,"ContrastBolusIngredientPercentByVolume","FL"], <del> [0x0052,0x0002,"OCTFocalDistance","FD"], <del> [0x0052,0x0003,"BeamSpotSize","FD"], <del> [0x0052,0x0004,"EffectiveRefractiveIndex","FD"], <del> [0x0052,0x0006,"OCTAcquisitionDomain","CS"], <del> [0x0052,0x0007,"OCTOpticalCenterWavelength","FD"], <del> [0x0052,0x0008,"AxialResolution","FD"], <del> [0x0052,0x0009,"RangingDepth","FD"], <del> [0x0052,0x0011,"ALineRate","FD"], <del> [0x0052,0x0012,"ALinesPerFrame","US"], <del> [0x0052,0x0013,"CatheterRotationalRate","FD"], <del> [0x0052,0x0014,"ALinePixelSpacing","FD"], <del> [0x0052,0x0016,"ModeOfPercutaneousAccessSequence","SQ"], <del> [0x0052,0x0025,"IntravascularOCTFrameTypeSequence","SQ"], <del> [0x0052,0x0026,"OCTZOffsetApplied","CS"], <del> [0x0052,0x0027,"IntravascularFrameContentSequence","SQ"], <del> [0x0052,0x0028,"IntravascularLongitudinalDistance","FD"], <del> [0x0052,0x0029,"IntravascularOCTFrameContentSequence","SQ"], <del> [0x0052,0x0030,"OCTZOffsetCorrection","SS"], <del> [0x0052,0x0031,"CatheterDirectionOfRotation","CS"], <del> [0x0052,0x0033,"SeamLineLocation","FD"], <del> [0x0052,0x0034,"FirstALineLocation","FD"], <del> [0x0052,0x0036,"SeamLineIndex","US"], <del> [0x0052,0x0038,"NumberOfPaddedAlines","US"], <del> [0x0052,0x0039,"InterpolationType","CS"], <del> [0x0052,0x003A,"RefractiveIndexApplied","CS"], <del> [0x0054,0x0010,"EnergyWindowVector","US"], <del> [0x0054,0x0011,"NumberOfEnergyWindows","US"], <del> [0x0054,0x0012,"EnergyWindowInformationSequence","SQ"], <del> [0x0054,0x0013,"EnergyWindowRangeSequence","SQ"], <del> [0x0054,0x0014,"EnergyWindowLowerLimit","DS"], <del> [0x0054,0x0015,"EnergyWindowUpperLimit","DS"], <del> [0x0054,0x0016,"RadiopharmaceuticalInformationSequence","SQ"], <del> [0x0054,0x0017,"ResidualSyringeCounts","IS"], <del> [0x0054,0x0018,"EnergyWindowName","SH"], <del> [0x0054,0x0020,"DetectorVector","US"], <del> [0x0054,0x0021,"NumberOfDetectors","US"], <del> [0x0054,0x0022,"DetectorInformationSequence","SQ"], <del> [0x0054,0x0030,"PhaseVector","US"], <del> [0x0054,0x0031,"NumberOfPhases","US"], <del> [0x0054,0x0032,"PhaseInformationSequence","SQ"], <del> [0x0054,0x0033,"NumberOfFramesInPhase","US"], <del> [0x0054,0x0036,"PhaseDelay","IS"], <del> [0x0054,0x0038,"PauseBetweenFrames","IS"], <del> [0x0054,0x0039,"PhaseDescription","CS"], <del> [0x0054,0x0050,"RotationVector","US"], <del> [0x0054,0x0051,"NumberOfRotations","US"], <del> [0x0054,0x0052,"RotationInformationSequence","SQ"], <del> [0x0054,0x0053,"NumberOfFramesInRotation","US"], <del> [0x0054,0x0060,"RRIntervalVector","US"], <del> [0x0054,0x0061,"NumberOfRRIntervals","US"], <del> [0x0054,0x0062,"GatedInformationSequence","SQ"], <del> [0x0054,0x0063,"DataInformationSequence","SQ"], <del> [0x0054,0x0070,"TimeSlotVector","US"], <del> [0x0054,0x0071,"NumberOfTimeSlots","US"], <del> [0x0054,0x0072,"TimeSlotInformationSequence","SQ"], <del> [0x0054,0x0073,"TimeSlotTime","DS"], <del> [0x0054,0x0080,"SliceVector","US"], <del> [0x0054,0x0081,"NumberOfSlices","US"], <del> [0x0054,0x0090,"AngularViewVector","US"], <del> [0x0054,0x0100,"TimeSliceVector","US"], <del> [0x0054,0x0101,"NumberOfTimeSlices","US"], <del> [0x0054,0x0200,"StartAngle","DS"], <del> [0x0054,0x0202,"TypeOfDetectorMotion","CS"], <del> [0x0054,0x0210,"TriggerVector","IS"], <del> [0x0054,0x0211,"NumberOfTriggersInPhase","US"], <del> [0x0054,0x0220,"ViewCodeSequence","SQ"], <del> [0x0054,0x0222,"ViewModifierCodeSequence","SQ"], <del> [0x0054,0x0300,"RadionuclideCodeSequence","SQ"], <del> [0x0054,0x0302,"AdministrationRouteCodeSequence","SQ"], <del> [0x0054,0x0304,"RadiopharmaceuticalCodeSequence","SQ"], <del> [0x0054,0x0306,"CalibrationDataSequence","SQ"], <del> [0x0054,0x0308,"EnergyWindowNumber","US"], <del> [0x0054,0x0400,"ImageID","SH"], <del> [0x0054,0x0410,"PatientOrientationCodeSequence","SQ"], <del> [0x0054,0x0412,"PatientOrientationModifierCodeSequence","SQ"], <del> [0x0054,0x0414,"PatientGantryRelationshipCodeSequence","SQ"], <del> [0x0054,0x0500,"SliceProgressionDirection","CS"], <del> [0x0054,0x1000,"SeriesType","CS"], <del> [0x0054,0x1001,"Units","CS"], <del> [0x0054,0x1002,"CountsSource","CS"], <del> [0x0054,0x1004,"ReprojectionMethod","CS"], <del> [0x0054,0x1006,"SUVType","CS"], <del> [0x0054,0x1100,"RandomsCorrectionMethod","CS"], <del> [0x0054,0x1101,"AttenuationCorrectionMethod","LO"], <del> [0x0054,0x1102,"DecayCorrection","CS"], <del> [0x0054,0x1103,"ReconstructionMethod","LO"], <del> [0x0054,0x1104,"DetectorLinesOfResponseUsed","LO"], <del> [0x0054,0x1105,"ScatterCorrectionMethod","LO"], <del> [0x0054,0x1200,"AxialAcceptance","DS"], <del> [0x0054,0x1201,"AxialMash","IS"], <del> [0x0054,0x1202,"TransverseMash","IS"], <del> [0x0054,0x1203,"DetectorElementSize","DS"], <del> [0x0054,0x1210,"CoincidenceWindowWidth","DS"], <del> [0x0054,0x1220,"SecondaryCountsType","CS"], <del> [0x0054,0x1300,"FrameReferenceTime","DS"], <del> [0x0054,0x1310,"PrimaryPromptsCountsAccumulated","IS"], <del> [0x0054,0x1311,"SecondaryCountsAccumulated","IS"], <del> [0x0054,0x1320,"SliceSensitivityFactor","DS"], <del> [0x0054,0x1321,"DecayFactor","DS"], <del> [0x0054,0x1322,"DoseCalibrationFactor","DS"], <del> [0x0054,0x1323,"ScatterFractionFactor","DS"], <del> [0x0054,0x1324,"DeadTimeFactor","DS"], <del> [0x0054,0x1330,"ImageIndex","US"], <del> [0x0054,0x1400,"CountsIncluded","CS"], <del> [0x0054,0x1401,"DeadTimeCorrectionFlag","CS"], <del> [0x0060,0x3000,"HistogramSequence","SQ"], <del> [0x0060,0x3002,"HistogramNumberOfBins","US"], <del> [0x0060,0x3004,"HistogramFirstBinValue","SS"], <del> [0x0060,0x3006,"HistogramLastBinValue","SS"], <del> [0x0060,0x3008,"HistogramBinWidth","US"], <del> [0x0060,0x3010,"HistogramExplanation","LO"], <del> [0x0060,0x3020,"HistogramData","UL"], <del> [0x0062,0x0001,"SegmentationType","CS"], <del> [0x0062,0x0002,"SegmentSequence","SQ"], <del> [0x0062,0x0003,"SegmentedPropertyCategoryCodeSequence","SQ"], <del> [0x0062,0x0004,"SegmentNumber","US"], <del> [0x0062,0x0005,"SegmentLabel","LO"], <del> [0x0062,0x0006,"SegmentDescription","ST"], <del> [0x0062,0x0008,"SegmentAlgorithmType","CS"], <del> [0x0062,0x0009,"SegmentAlgorithmName","LO"], <del> [0x0062,0x000A,"SegmentIdentificationSequence","SQ"], <del> [0x0062,0x000B,"ReferencedSegmentNumber","US"], <del> [0x0062,0x000C,"RecommendedDisplayGrayscaleValue","US"], <del> [0x0062,0x000D,"RecommendedDisplayCIELabValue","US"], <del> [0x0062,0x000E,"MaximumFractionalValue","US"], <del> [0x0062,0x000F,"SegmentedPropertyTypeCodeSequence","SQ"], <del> [0x0062,0x0010,"SegmentationFractionalType","CS"], <del> [0x0064,0x0002,"DeformableRegistrationSequence","SQ"], <del> [0x0064,0x0003,"SourceFrameOfReferenceUID","UI"], <del> [0x0064,0x0005,"DeformableRegistrationGridSequence","SQ"], <del> [0x0064,0x0007,"GridDimensions","UL"], <del> [0x0064,0x0008,"GridResolution","FD"], <del> [0x0064,0x0009,"VectorGridData","OF"], <del> [0x0064,0x000F,"PreDeformationMatrixRegistrationSequence","SQ"], <del> [0x0064,0x0010,"PostDeformationMatrixRegistrationSequence","SQ"], <del> [0x0066,0x0001,"NumberOfSurfaces","UL"], <del> [0x0066,0x0002,"SurfaceSequence","SQ"], <del> [0x0066,0x0003,"SurfaceNumber","UL"], <del> [0x0066,0x0004,"SurfaceComments","LT"], <del> [0x0066,0x0009,"SurfaceProcessing","CS"], <del> [0x0066,0x000A,"SurfaceProcessingRatio","FL"], <del> [0x0066,0x000B,"SurfaceProcessingDescription","LO"], <del> [0x0066,0x000C,"RecommendedPresentationOpacity","FL"], <del> [0x0066,0x000D,"RecommendedPresentationType","CS"], <del> [0x0066,0x000E,"FiniteVolume","CS"], <del> [0x0066,0x0010,"Manifold","CS"], <del> [0x0066,0x0011,"SurfacePointsSequence","SQ"], <del> [0x0066,0x0012,"SurfacePointsNormalsSequence","SQ"], <del> [0x0066,0x0013,"SurfaceMeshPrimitivesSequence","SQ"], <del> [0x0066,0x0015,"NumberOfSurfacePoints","UL"], <del> [0x0066,0x0016,"PointCoordinatesData","OF"], <del> [0x0066,0x0017,"PointPositionAccuracy","FL"], <del> [0x0066,0x0018,"MeanPointDistance","FL"], <del> [0x0066,0x0019,"MaximumPointDistance","FL"], <del> [0x0066,0x001A,"PointsBoundingBoxCoordinates","FL"], <del> [0x0066,0x001B,"AxisOfRotation","FL"], <del> [0x0066,0x001C,"CenterOfRotation","FL"], <del> [0x0066,0x001E,"NumberOfVectors","UL"], <del> [0x0066,0x001F,"VectorDimensionality","US"], <del> [0x0066,0x0020,"VectorAccuracy","FL"], <del> [0x0066,0x0021,"VectorCoordinateData","OF"], <del> [0x0066,0x0023,"TrianglePointIndexList","OW"], <del> [0x0066,0x0024,"EdgePointIndexList","OW"], <del> [0x0066,0x0025,"VertexPointIndexList","OW"], <del> [0x0066,0x0026,"TriangleStripSequence","SQ"], <del> [0x0066,0x0027,"TriangleFanSequence","SQ"], <del> [0x0066,0x0028,"LineSequence","SQ"], <del> [0x0066,0x0029,"PrimitivePointIndexList","OW"], <del> [0x0066,0x002A,"SurfaceCount","UL"], <del> [0x0066,0x002B,"ReferencedSurfaceSequence","SQ"], <del> [0x0066,0x002C,"ReferencedSurfaceNumber","UL"], <del> [0x0066,0x002D,"SegmentSurfaceGenerationAlgorithmIdentificationSequence","SQ"], <del> [0x0066,0x002E,"SegmentSurfaceSourceInstanceSequence","SQ"], <del> [0x0066,0x002F,"AlgorithmFamilyCodeSequence","SQ"], <del> [0x0066,0x0030,"AlgorithmNameCodeSequence","SQ"], <del> [0x0066,0x0031,"AlgorithmVersion","LO"], <del> [0x0066,0x0032,"AlgorithmParameters","LT"], <del> [0x0066,0x0034,"FacetSequence","SQ"], <del> [0x0066,0x0035,"SurfaceProcessingAlgorithmIdentificationSequence","SQ"], <del> [0x0066,0x0036,"AlgorithmName","LO"], <del> [0x0068,0x6210,"ImplantSize","LO"], <del> [0x0068,0x6221,"ImplantTemplateVersion","LO"], <del> [0x0068,0x6222,"ReplacedImplantTemplateSequence","SQ"], <del> [0x0068,0x6223,"ImplantType","CS"], <del> [0x0068,0x6224,"DerivationImplantTemplateSequence","SQ"], <del> [0x0068,0x6225,"OriginalImplantTemplateSequence","SQ"], <del> [0x0068,0x6226,"EffectiveDateTime","DT"], <del> [0x0068,0x6230,"ImplantTargetAnatomySequence","SQ"], <del> [0x0068,0x6260,"InformationFromManufacturerSequence","SQ"], <del> [0x0068,0x6265,"NotificationFromManufacturerSequence","SQ"], <del> [0x0068,0x6270,"InformationIssueDateTime","DT"], <del> [0x0068,0x6280,"InformationSummary","ST"], <del> [0x0068,0x62A0,"ImplantRegulatoryDisapprovalCodeSequence","SQ"], <del> [0x0068,0x62A5,"OverallTemplateSpatialTolerance","FD"], <del> [0x0068,0x62C0,"HPGLDocumentSequence","SQ"], <del> [0x0068,0x62D0,"HPGLDocumentID","US"], <del> [0x0068,0x62D5,"HPGLDocumentLabel","LO"], <del> [0x0068,0x62E0,"ViewOrientationCodeSequence","SQ"], <del> [0x0068,0x62F0,"ViewOrientationModifier","FD"], <del> [0x0068,0x62F2,"HPGLDocumentScaling","FD"], <del> [0x0068,0x6300,"HPGLDocument","OB"], <del> [0x0068,0x6310,"HPGLContourPenNumber","US"], <del> [0x0068,0x6320,"HPGLPenSequence","SQ"], <del> [0x0068,0x6330,"HPGLPenNumber","US"], <del> [0x0068,0x6340,"HPGLPenLabel","LO"], <del> [0x0068,0x6345,"HPGLPenDescription","ST"], <del> [0x0068,0x6346,"RecommendedRotationPoint","FD"], <del> [0x0068,0x6347,"BoundingRectangle","FD"], <del> [0x0068,0x6350,"ImplantTemplate3DModelSurfaceNumber","US"], <del> [0x0068,0x6360,"SurfaceModelDescriptionSequence","SQ"], <del> [0x0068,0x6380,"SurfaceModelLabel","LO"], <del> [0x0068,0x6390,"SurfaceModelScalingFactor","FD"], <del> [0x0068,0x63A0,"MaterialsCodeSequence","SQ"], <del> [0x0068,0x63A4,"CoatingMaterialsCodeSequence","SQ"], <del> [0x0068,0x63A8,"ImplantTypeCodeSequence","SQ"], <del> [0x0068,0x63AC,"FixationMethodCodeSequence","SQ"], <del> [0x0068,0x63B0,"MatingFeatureSetsSequence","SQ"], <del> [0x0068,0x63C0,"MatingFeatureSetID","US"], <del> [0x0068,0x63D0,"MatingFeatureSetLabel","LO"], <del> [0x0068,0x63E0,"MatingFeatureSequence","SQ"], <del> [0x0068,0x63F0,"MatingFeatureID","US"], <del> [0x0068,0x6400,"MatingFeatureDegreeOfFreedomSequence","SQ"], <del> [0x0068,0x6410,"DegreeOfFreedomID","US"], <del> [0x0068,0x6420,"DegreeOfFreedomType","CS"], <del> [0x0068,0x6430,"TwoDMatingFeatureCoordinatesSequence","SQ"], <del> [0x0068,0x6440,"ReferencedHPGLDocumentID","US"], <del> [0x0068,0x6450,"TwoDMatingPoint","FD"], <del> [0x0068,0x6460,"TwoDMatingAxes","FD"], <del> [0x0068,0x6470,"TwoDDegreeOfFreedomSequence","SQ"], <del> [0x0068,0x6490,"ThreeDDegreeOfFreedomAxis","FD"], <del> [0x0068,0x64A0,"RangeOfFreedom","FD"], <del> [0x0068,0x64C0,"ThreeDMatingPoint","FD"], <del> [0x0068,0x64D0,"ThreeDMatingAxes","FD"], <del> [0x0068,0x64F0,"TwoDDegreeOfFreedomAxis","FD"], <del> [0x0068,0x6500,"PlanningLandmarkPointSequence","SQ"], <del> [0x0068,0x6510,"PlanningLandmarkLineSequence","SQ"], <del> [0x0068,0x6520,"PlanningLandmarkPlaneSequence","SQ"], <del> [0x0068,0x6530,"PlanningLandmarkID","US"], <del> [0x0068,0x6540,"PlanningLandmarkDescription","LO"], <del> [0x0068,0x6545,"PlanningLandmarkIdentificationCodeSequence","SQ"], <del> [0x0068,0x6550,"TwoDPointCoordinatesSequence","SQ"], <del> [0x0068,0x6560,"TwoDPointCoordinates","FD"], <del> [0x0068,0x6590,"ThreeDPointCoordinates","FD"], <del> [0x0068,0x65A0,"TwoDLineCoordinatesSequence","SQ"], <del> [0x0068,0x65B0,"TwoDLineCoordinates","FD"], <del> [0x0068,0x65D0,"ThreeDLineCoordinates","FD"], <del> [0x0068,0x65E0,"TwoDPlaneCoordinatesSequence","SQ"], <del> [0x0068,0x65F0,"TwoDPlaneIntersection","FD"], <del> [0x0068,0x6610,"ThreeDPlaneOrigin","FD"], <del> [0x0068,0x6620,"ThreeDPlaneNormal","FD"], <del> [0x0070,0x0001,"GraphicAnnotationSequence","SQ"], <del> [0x0070,0x0002,"GraphicLayer","CS"], <del> [0x0070,0x0003,"BoundingBoxAnnotationUnits","CS"], <del> [0x0070,0x0004,"AnchorPointAnnotationUnits","CS"], <del> [0x0070,0x0005,"GraphicAnnotationUnits","CS"], <del> [0x0070,0x0006,"UnformattedTextValue","ST"], <del> [0x0070,0x0008,"TextObjectSequence","SQ"], <del> [0x0070,0x0009,"GraphicObjectSequence","SQ"], <del> [0x0070,0x0010,"BoundingBoxTopLeftHandCorner","FL"], <del> [0x0070,0x0011,"BoundingBoxBottomRightHandCorner","FL"], <del> [0x0070,0x0012,"BoundingBoxTextHorizontalJustification","CS"], <del> [0x0070,0x0014,"AnchorPoint","FL"], <del> [0x0070,0x0015,"AnchorPointVisibility","CS"], <del> [0x0070,0x0020,"GraphicDimensions","US"], <del> [0x0070,0x0021,"NumberOfGraphicPoints","US"], <del> [0x0070,0x0022,"GraphicData","FL"], <del> [0x0070,0x0023,"GraphicType","CS"], <del> [0x0070,0x0024,"GraphicFilled","CS"], <del> [0x0070,0x0040,"ImageRotationRetired","IS"], <del> [0x0070,0x0041,"ImageHorizontalFlip","CS"], <del> [0x0070,0x0042,"ImageRotation","US"], <del> [0x0070,0x0050,"DisplayedAreaTopLeftHandCornerTrial","US"], <del> [0x0070,0x0051,"DisplayedAreaBottomRightHandCornerTrial","US"], <del> [0x0070,0x0052,"DisplayedAreaTopLeftHandCorner","SL"], <del> [0x0070,0x0053,"DisplayedAreaBottomRightHandCorner","SL"], <del> [0x0070,0x005A,"DisplayedAreaSelectionSequence","SQ"], <del> [0x0070,0x0060,"GraphicLayerSequence","SQ"], <del> [0x0070,0x0062,"GraphicLayerOrder","IS"], <del> [0x0070,0x0066,"GraphicLayerRecommendedDisplayGrayscaleValue","US"], <del> [0x0070,0x0067,"GraphicLayerRecommendedDisplayRGBValue","US"], <del> [0x0070,0x0068,"GraphicLayerDescription","LO"], <del> [0x0070,0x0080,"ContentLabel","CS"], <del> [0x0070,0x0081,"ContentDescription","LO"], <del> [0x0070,0x0082,"PresentationCreationDate","DA"], <del> [0x0070,0x0083,"PresentationCreationTime","TM"], <del> [0x0070,0x0084,"ContentCreatorName","PN"], <del> [0x0070,0x0086,"ContentCreatorIdentificationCodeSequence","SQ"], <del> [0x0070,0x0087,"AlternateContentDescriptionSequence","SQ"], <del> [0x0070,0x0100,"PresentationSizeMode","CS"], <del> [0x0070,0x0101,"PresentationPixelSpacing","DS"], <del> [0x0070,0x0102,"PresentationPixelAspectRatio","IS"], <del> [0x0070,0x0103,"PresentationPixelMagnificationRatio","FL"], <del> [0x0070,0x0207,"GraphicGroupLabel","LO"], <del> [0x0070,0x0208,"GraphicGroupDescription","ST"], <del> [0x0070,0x0209,"CompoundGraphicSequence","SQ"], <del> [0x0070,0x0226,"CompoundGraphicInstanceID","UL"], <del> [0x0070,0x0227,"FontName","LO"], <del> [0x0070,0x0228,"FontNameType","CS"], <del> [0x0070,0x0229,"CSSFontName","LO"], <del> [0x0070,0x0230,"RotationAngle","FD"], <del> [0x0070,0x0231,"TextStyleSequence","SQ"], <del> [0x0070,0x0232,"LineStyleSequence","SQ"], <del> [0x0070,0x0233,"FillStyleSequence","SQ"], <del> [0x0070,0x0234,"GraphicGroupSequence","SQ"], <del> [0x0070,0x0241,"TextColorCIELabValue","US"], <del> [0x0070,0x0242,"HorizontalAlignment","CS"], <del> [0x0070,0x0243,"VerticalAlignment","CS"], <del> [0x0070,0x0244,"ShadowStyle","CS"], <del> [0x0070,0x0245,"ShadowOffsetX","FL"], <del> [0x0070,0x0246,"ShadowOffsetY","FL"], <del> [0x0070,0x0247,"ShadowColorCIELabValue","US"], <del> [0x0070,0x0248,"Underlined","CS"], <del> [0x0070,0x0249,"Bold","CS"], <del> [0x0070,0x0250,"Italic","CS"], <del> [0x0070,0x0251,"PatternOnColorCIELabValue","US"], <del> [0x0070,0x0252,"PatternOffColorCIELabValue","US"], <del> [0x0070,0x0253,"LineThickness","FL"], <del> [0x0070,0x0254,"LineDashingStyle","CS"], <del> [0x0070,0x0255,"LinePattern","UL"], <del> [0x0070,0x0256,"FillPattern","OB"], <del> [0x0070,0x0257,"FillMode","CS"], <del> [0x0070,0x0258,"ShadowOpacity","FL"], <del> [0x0070,0x0261,"GapLength","FL"], <del> [0x0070,0x0262,"DiameterOfVisibility","FL"], <del> [0x0070,0x0273,"RotationPoint","FL"], <del> [0x0070,0x0274,"TickAlignment","CS"], <del> [0x0070,0x0278,"ShowTickLabel","CS"], <del> [0x0070,0x0279,"TickLabelAlignment","CS"], <del> [0x0070,0x0282,"CompoundGraphicUnits","CS"], <del> [0x0070,0x0284,"PatternOnOpacity","FL"], <del> [0x0070,0x0285,"PatternOffOpacity","FL"], <del> [0x0070,0x0287,"MajorTicksSequence","SQ"], <del> [0x0070,0x0288,"TickPosition","FL"], <del> [0x0070,0x0289,"TickLabel","SH"], <del> [0x0070,0x0294,"CompoundGraphicType","CS"], <del> [0x0070,0x0295,"GraphicGroupID","UL"], <del> [0x0070,0x0306,"ShapeType","CS"], <del> [0x0070,0x0308,"RegistrationSequence","SQ"], <del> [0x0070,0x0309,"MatrixRegistrationSequence","SQ"], <del> [0x0070,0x030A,"MatrixSequence","SQ"], <del> [0x0070,0x030C,"FrameOfReferenceTransformationMatrixType","CS"], <del> [0x0070,0x030D,"RegistrationTypeCodeSequence","SQ"], <del> [0x0070,0x030F,"FiducialDescription","ST"], <del> [0x0070,0x0310,"FiducialIdentifier","SH"], <del> [0x0070,0x0311,"FiducialIdentifierCodeSequence","SQ"], <del> [0x0070,0x0312,"ContourUncertaintyRadius","FD"], <del> [0x0070,0x0314,"UsedFiducialsSequence","SQ"], <del> [0x0070,0x0318,"GraphicCoordinatesDataSequence","SQ"], <del> [0x0070,0x031A,"FiducialUID","UI"], <del> [0x0070,0x031C,"FiducialSetSequence","SQ"], <del> [0x0070,0x031E,"FiducialSequence","SQ"], <del> [0x0070,0x0401,"GraphicLayerRecommendedDisplayCIELabValue","US"], <del> [0x0070,0x0402,"BlendingSequence","SQ"], <del> [0x0070,0x0403,"RelativeOpacity","FL"], <del> [0x0070,0x0404,"ReferencedSpatialRegistrationSequence","SQ"], <del> [0x0070,0x0405,"BlendingPosition","CS"], <del> [0x0072,0x0002,"HangingProtocolName","SH"], <del> [0x0072,0x0004,"HangingProtocolDescription","LO"], <del> [0x0072,0x0006,"HangingProtocolLevel","CS"], <del> [0x0072,0x0008,"HangingProtocolCreator","LO"], <del> [0x0072,0x000A,"HangingProtocolCreationDateTime","DT"], <del> [0x0072,0x000C,"HangingProtocolDefinitionSequence","SQ"], <del> [0x0072,0x000E,"HangingProtocolUserIdentificationCodeSequence","SQ"], <del> [0x0072,0x0010,"HangingProtocolUserGroupName","LO"], <del> [0x0072,0x0012,"SourceHangingProtocolSequence","SQ"], <del> [0x0072,0x0014,"NumberOfPriorsReferenced","US"], <del> [0x0072,0x0020,"ImageSetsSequence","SQ"], <del> [0x0072,0x0022,"ImageSetSelectorSequence","SQ"], <del> [0x0072,0x0024,"ImageSetSelectorUsageFlag","CS"], <del> [0x0072,0x0026,"SelectorAttribute","AT"], <del> [0x0072,0x0028,"SelectorValueNumber","US"], <del> [0x0072,0x0030,"TimeBasedImageSetsSequence","SQ"], <del> [0x0072,0x0032,"ImageSetNumber","US"], <del> [0x0072,0x0034,"ImageSetSelectorCategory","CS"], <del> [0x0072,0x0038,"RelativeTime","US"], <del> [0x0072,0x003A,"RelativeTimeUnits","CS"], <del> [0x0072,0x003C,"AbstractPriorValue","SS"], <del> [0x0072,0x003E,"AbstractPriorCodeSequence","SQ"], <del> [0x0072,0x0040,"ImageSetLabel","LO"], <del> [0x0072,0x0050,"SelectorAttributeVR","CS"], <del> [0x0072,0x0052,"SelectorSequencePointer","AT"], <del> [0x0072,0x0054,"SelectorSequencePointerPrivateCreator","LO"], <del> [0x0072,0x0056,"SelectorAttributePrivateCreator","LO"], <del> [0x0072,0x0060,"SelectorATValue","AT"], <del> [0x0072,0x0062,"SelectorCSValue","CS"], <del> [0x0072,0x0064,"SelectorISValue","IS"], <del> [0x0072,0x0066,"SelectorLOValue","LO"], <del> [0x0072,0x0068,"SelectorLTValue","LT"], <del> [0x0072,0x006A,"SelectorPNValue","PN"], <del> [0x0072,0x006C,"SelectorSHValue","SH"], <del> [0x0072,0x006E,"SelectorSTValue","ST"], <del> [0x0072,0x0070,"SelectorUTValue","UT"], <del> [0x0072,0x0072,"SelectorDSValue","DS"], <del> [0x0072,0x0074,"SelectorFDValue","FD"], <del> [0x0072,0x0076,"SelectorFLValue","FL"], <del> [0x0072,0x0078,"SelectorULValue","UL"], <del> [0x0072,0x007A,"SelectorUSValue","US"], <del> [0x0072,0x007C,"SelectorSLValue","SL"], <del> [0x0072,0x007E,"SelectorSSValue","SS"], <del> [0x0072,0x0080,"SelectorCodeSequenceValue","SQ"], <del> [0x0072,0x0100,"NumberOfScreens","US"], <del> [0x0072,0x0102,"NominalScreenDefinitionSequence","SQ"], <del> [0x0072,0x0104,"NumberOfVerticalPixels","US"], <del> [0x0072,0x0106,"NumberOfHorizontalPixels","US"], <del> [0x0072,0x0108,"DisplayEnvironmentSpatialPosition","FD"], <del> [0x0072,0x010A,"ScreenMinimumGrayscaleBitDepth","US"], <del> [0x0072,0x010C,"ScreenMinimumColorBitDepth","US"], <del> [0x0072,0x010E,"ApplicationMaximumRepaintTime","US"], <del> [0x0072,0x0200,"DisplaySetsSequence","SQ"], <del> [0x0072,0x0202,"DisplaySetNumber","US"], <del> [0x0072,0x0203,"DisplaySetLabel","LO"], <del> [0x0072,0x0204,"DisplaySetPresentationGroup","US"], <del> [0x0072,0x0206,"DisplaySetPresentationGroupDescription","LO"], <del> [0x0072,0x0208,"PartialDataDisplayHandling","CS"], <del> [0x0072,0x0210,"SynchronizedScrollingSequence","SQ"], <del> [0x0072,0x0212,"DisplaySetScrollingGroup","US"], <del> [0x0072,0x0214,"NavigationIndicatorSequence","SQ"], <del> [0x0072,0x0216,"NavigationDisplaySet","US"], <del> [0x0072,0x0218,"ReferenceDisplaySets","US"], <del> [0x0072,0x0300,"ImageBoxesSequence","SQ"], <del> [0x0072,0x0302,"ImageBoxNumber","US"], <del> [0x0072,0x0304,"ImageBoxLayoutType","CS"], <del> [0x0072,0x0306,"ImageBoxTileHorizontalDimension","US"], <del> [0x0072,0x0308,"ImageBoxTileVerticalDimension","US"], <del> [0x0072,0x0310,"ImageBoxScrollDirection","CS"], <del> [0x0072,0x0312,"ImageBoxSmallScrollType","CS"], <del> [0x0072,0x0314,"ImageBoxSmallScrollAmount","US"], <del> [0x0072,0x0316,"ImageBoxLargeScrollType","CS"], <del> [0x0072,0x0318,"ImageBoxLargeScrollAmount","US"], <del> [0x0072,0x0320,"ImageBoxOverlapPriority","US"], <del> [0x0072,0x0330,"CineRelativeToRealTime","FD"], <del> [0x0072,0x0400,"FilterOperationsSequence","SQ"], <del> [0x0072,0x0402,"FilterByCategory","CS"], <del> [0x0072,0x0404,"FilterByAttributePresence","CS"], <del> [0x0072,0x0406,"FilterByOperator","CS"], <del> [0x0072,0x0420,"StructuredDisplayBackgroundCIELabValue","US"], <del> [0x0072,0x0421,"EmptyImageBoxCIELabValue","US"], <del> [0x0072,0x0422,"StructuredDisplayImageBoxSequence","SQ"], <del> [0x0072,0x0424,"StructuredDisplayTextBoxSequence","SQ"], <del> [0x0072,0x0427,"ReferencedFirstFrameSequence","SQ"], <del> [0x0072,0x0430,"ImageBoxSynchronizationSequence","SQ"], <del> [0x0072,0x0432,"SynchronizedImageBoxList","US"], <del> [0x0072,0x0434,"TypeOfSynchronization","CS"], <del> [0x0072,0x0500,"BlendingOperationType","CS"], <del> [0x0072,0x0510,"ReformattingOperationType","CS"], <del> [0x0072,0x0512,"ReformattingThickness","FD"], <del> [0x0072,0x0514,"ReformattingInterval","FD"], <del> [0x0072,0x0516,"ReformattingOperationInitialViewDirection","CS"], <del> [0x0072,0x0520,"ThreeDRenderingType","CS"], <del> [0x0072,0x0600,"SortingOperationsSequence","SQ"], <del> [0x0072,0x0602,"SortByCategory","CS"], <del> [0x0072,0x0604,"SortingDirection","CS"], <del> [0x0072,0x0700,"DisplaySetPatientOrientation","CS"], <del> [0x0072,0x0702,"VOIType","CS"], <del> [0x0072,0x0704,"PseudoColorType","CS"], <del> [0x0072,0x0705,"PseudoColorPaletteInstanceReferenceSequence","SQ"], <del> [0x0072,0x0706,"ShowGrayscaleInverted","CS"], <del> [0x0072,0x0710,"ShowImageTrueSizeFlag","CS"], <del> [0x0072,0x0712,"ShowGraphicAnnotationFlag","CS"], <del> [0x0072,0x0714,"ShowPatientDemographicsFlag","CS"], <del> [0x0072,0x0716,"ShowAcquisitionTechniquesFlag","CS"], <del> [0x0072,0x0717,"DisplaySetHorizontalJustification","CS"], <del> [0x0072,0x0718,"DisplaySetVerticalJustification","CS"], <del> [0x0074,0x0120,"ContinuationStartMeterset","FD"], <del> [0x0074,0x0121,"ContinuationEndMeterset","FD"], <del> [0x0074,0x1000,"ProcedureStepState","CS"], <del> [0x0074,0x1002,"ProcedureStepProgressInformationSequence","SQ"], <del> [0x0074,0x1004,"ProcedureStepProgress","DS"], <del> [0x0074,0x1006,"ProcedureStepProgressDescription","ST"], <del> [0x0074,0x1008,"ProcedureStepCommunicationsURISequence","SQ"], <del> [0x0074,0x100a,"ContactURI","ST"], <del> [0x0074,0x100c,"ContactDisplayName","LO"], <del> [0x0074,0x100e,"ProcedureStepDiscontinuationReasonCodeSequence","SQ"], <del> [0x0074,0x1020,"BeamTaskSequence","SQ"], <del> [0x0074,0x1022,"BeamTaskType","CS"], <del> [0x0074,0x1024,"BeamOrderIndexTrial","IS"], <del> [0x0074,0x1026,"TableTopVerticalAdjustedPosition","FD"], <del> [0x0074,0x1027,"TableTopLongitudinalAdjustedPosition","FD"], <del> [0x0074,0x1028,"TableTopLateralAdjustedPosition","FD"], <del> [0x0074,0x102A,"PatientSupportAdjustedAngle","FD"], <del> [0x0074,0x102B,"TableTopEccentricAdjustedAngle","FD"], <del> [0x0074,0x102C,"TableTopPitchAdjustedAngle","FD"], <del> [0x0074,0x102D,"TableTopRollAdjustedAngle","FD"], <del> [0x0074,0x1030,"DeliveryVerificationImageSequence","SQ"], <del> [0x0074,0x1032,"VerificationImageTiming","CS"], <del> [0x0074,0x1034,"DoubleExposureFlag","CS"], <del> [0x0074,0x1036,"DoubleExposureOrdering","CS"], <del> [0x0074,0x1038,"DoubleExposureMetersetTrial","DS"], <del> [0x0074,0x103A,"DoubleExposureFieldDeltaTrial","DS"], <del> [0x0074,0x1040,"RelatedReferenceRTImageSequence","SQ"], <del> [0x0074,0x1042,"GeneralMachineVerificationSequence","SQ"], <del> [0x0074,0x1044,"ConventionalMachineVerificationSequence","SQ"], <del> [0x0074,0x1046,"IonMachineVerificationSequence","SQ"], <del> [0x0074,0x1048,"FailedAttributesSequence","SQ"], <del> [0x0074,0x104A,"OverriddenAttributesSequence","SQ"], <del> [0x0074,0x104C,"ConventionalControlPointVerificationSequence","SQ"], <del> [0x0074,0x104E,"IonControlPointVerificationSequence","SQ"], <del> [0x0074,0x1050,"AttributeOccurrenceSequence","SQ"], <del> [0x0074,0x1052,"AttributeOccurrencePointer","AT"], <del> [0x0074,0x1054,"AttributeItemSelector","UL"], <del> [0x0074,0x1056,"AttributeOccurrencePrivateCreator","LO"], <del> [0x0074,0x1057,"SelectorSequencePointerItems","IS"], <del> [0x0074,0x1200,"ScheduledProcedureStepPriority","CS"], <del> [0x0074,0x1202,"WorklistLabel","LO"], <del> [0x0074,0x1204,"ProcedureStepLabel","LO"], <del> [0x0074,0x1210,"ScheduledProcessingParametersSequence","SQ"], <del> [0x0074,0x1212,"PerformedProcessingParametersSequence","SQ"], <del> [0x0074,0x1216,"UnifiedProcedureStepPerformedProcedureSequence","SQ"], <del> [0x0074,0x1220,"RelatedProcedureStepSequence","SQ"], <del> [0x0074,0x1222,"ProcedureStepRelationshipType","LO"], <del> [0x0074,0x1224,"ReplacedProcedureStepSequence","SQ"], <del> [0x0074,0x1230,"DeletionLock","LO"], <del> [0x0074,0x1234,"ReceivingAE","AE"], <del> [0x0074,0x1236,"RequestingAE","AE"], <del> [0x0074,0x1238,"ReasonForCancellation","LT"], <del> [0x0074,0x1242,"SCPStatus","CS"], <del> [0x0074,0x1244,"SubscriptionListStatus","CS"], <del> [0x0074,0x1246,"UnifiedProcedureStepListStatus","CS"], <del> [0x0074,0x1324,"BeamOrderIndex","UL"], <del> [0x0074,0x1338,"DoubleExposureMeterset","FD"], <del> [0x0074,0x133A,"DoubleExposureFieldDelta","FD"], <del> [0x0076,0x0001,"ImplantAssemblyTemplateName","LO"], <del> [0x0076,0x0003,"ImplantAssemblyTemplateIssuer","LO"], <del> [0x0076,0x0006,"ImplantAssemblyTemplateVersion","LO"], <del> [0x0076,0x0008,"ReplacedImplantAssemblyTemplateSequence","SQ"], <del> [0x0076,0x000A,"ImplantAssemblyTemplateType","CS"], <del> [0x0076,0x000C,"OriginalImplantAssemblyTemplateSequence","SQ"], <del> [0x0076,0x000E,"DerivationImplantAssemblyTemplateSequence","SQ"], <del> [0x0076,0x0010,"ImplantAssemblyTemplateTargetAnatomySequence","SQ"], <del> [0x0076,0x0020,"ProcedureTypeCodeSequence","SQ"], <del> [0x0076,0x0030,"SurgicalTechnique","LO"], <del> [0x0076,0x0032,"ComponentTypesSequence","SQ"], <del> [0x0076,0x0034,"ComponentTypeCodeSequence","CS"], <del> [0x0076,0x0036,"ExclusiveComponentType","CS"], <del> [0x0076,0x0038,"MandatoryComponentType","CS"], <del> [0x0076,0x0040,"ComponentSequence","SQ"], <del> [0x0076,0x0055,"ComponentID","US"], <del> [0x0076,0x0060,"ComponentAssemblySequence","SQ"], <del> [0x0076,0x0070,"Component1ReferencedID","US"], <del> [0x0076,0x0080,"Component1ReferencedMatingFeatureSetID","US"], <del> [0x0076,0x0090,"Component1ReferencedMatingFeatureID","US"], <del> [0x0076,0x00A0,"Component2ReferencedID","US"], <del> [0x0076,0x00B0,"Component2ReferencedMatingFeatureSetID","US"], <del> [0x0076,0x00C0,"Component2ReferencedMatingFeatureID","US"], <del> [0x0078,0x0001,"ImplantTemplateGroupName","LO"], <del> [0x0078,0x0010,"ImplantTemplateGroupDescription","ST"], <del> [0x0078,0x0020,"ImplantTemplateGroupIssuer","LO"], <del> [0x0078,0x0024,"ImplantTemplateGroupVersion","LO"], <del> [0x0078,0x0026,"ReplacedImplantTemplateGroupSequence","SQ"], <del> [0x0078,0x0028,"ImplantTemplateGroupTargetAnatomySequence","SQ"], <del> [0x0078,0x002A,"ImplantTemplateGroupMembersSequence","SQ"], <del> [0x0078,0x002E,"ImplantTemplateGroupMemberID","US"], <del> [0x0078,0x0050,"ThreeDImplantTemplateGroupMemberMatchingPoint","FD"], <del> [0x0078,0x0060,"ThreeDImplantTemplateGroupMemberMatchingAxes","FD"], <del> [0x0078,0x0070,"ImplantTemplateGroupMemberMatching2DCoordinatesSequence","SQ"], <del> [0x0078,0x0090,"TwoDImplantTemplateGroupMemberMatchingPoint","FD"], <del> [0x0078,0x00A0,"TwoDImplantTemplateGroupMemberMatchingAxes","FD"], <del> [0x0078,0x00B0,"ImplantTemplateGroupVariationDimensionSequence","SQ"], <del> [0x0078,0x00B2,"ImplantTemplateGroupVariationDimensionName","LO"], <del> [0x0078,0x00B4,"ImplantTemplateGroupVariationDimensionRankSequence","SQ"], <del> [0x0078,0x00B6,"ReferencedImplantTemplateGroupMemberID","US"], <del> [0x0078,0x00B8,"ImplantTemplateGroupVariationDimensionRank","US"], <del> [0x0088,0x0130,"StorageMediaFileSetID","SH"], <del> [0x0088,0x0140,"StorageMediaFileSetUID","UI"], <del> [0x0088,0x0200,"IconImageSequence","SQ"], <del> [0x0088,0x0904,"TopicTitle","LO"], <del> [0x0088,0x0906,"TopicSubject","ST"], <del> [0x0088,0x0910,"TopicAuthor","LO"], <del> [0x0088,0x0912,"TopicKeywords","LO"], <del> [0x0100,0x0410,"SOPInstanceStatus","CS"], <del> [0x0100,0x0420,"SOPAuthorizationDateTime","DT"], <del> [0x0100,0x0424,"SOPAuthorizationComment","LT"], <del> [0x0100,0x0426,"AuthorizationEquipmentCertificationNumber","LO"], <del> [0x0400,0x0005,"MACIDNumber","US"], <del> [0x0400,0x0010,"MACCalculationTransferSyntaxUID","UI"], <del> [0x0400,0x0015,"MACAlgorithm","CS"], <del> [0x0400,0x0020,"DataElementsSigned","AT"], <del> [0x0400,0x0100,"DigitalSignatureUID","UI"], <del> [0x0400,0x0105,"DigitalSignatureDateTime","DT"], <del> [0x0400,0x0110,"CertificateType","CS"], <del> [0x0400,0x0115,"CertificateOfSigner","OB"], <del> [0x0400,0x0120,"Signature","OB"], <del> [0x0400,0x0305,"CertifiedTimestampType","CS"], <del> [0x0400,0x0310,"CertifiedTimestamp","OB"], <del> [0x0400,0x0401,"DigitalSignaturePurposeCodeSequence","SQ"], <del> [0x0400,0x0402,"ReferencedDigitalSignatureSequence","SQ"], <del> [0x0400,0x0403,"ReferencedSOPInstanceMACSequence","SQ"], <del> [0x0400,0x0404,"MAC","OB"], <del> [0x0400,0x0500,"EncryptedAttributesSequence","SQ"], <del> [0x0400,0x0510,"EncryptedContentTransferSyntaxUID","UI"], <del> [0x0400,0x0520,"EncryptedContent","OB"], <del> [0x0400,0x0550,"ModifiedAttributesSequence","SQ"], <del> [0x0400,0x0561,"OriginalAttributesSequence","SQ"], <del> [0x0400,0x0562,"AttributeModificationDateTime","DT"], <del> [0x0400,0x0563,"ModifyingSystem","LO"], <del> [0x0400,0x0564,"SourceOfPreviousValues","LO"], <del> [0x0400,0x0565,"ReasonForTheAttributeModification","CS"], <del> [0x2000,0x0010,"NumberOfCopies","IS"], <del> [0x2000,0x001E,"PrinterConfigurationSequence","SQ"], <del> [0x2000,0x0020,"PrintPriority","CS"], <del> [0x2000,0x0030,"MediumType","CS"], <del> [0x2000,0x0040,"FilmDestination","CS"], <del> [0x2000,0x0050,"FilmSessionLabel","LO"], <del> [0x2000,0x0060,"MemoryAllocation","IS"], <del> [0x2000,0x0061,"MaximumMemoryAllocation","IS"], <del> [0x2000,0x0062,"ColorImagePrintingFlag","CS"], <del> [0x2000,0x0063,"CollationFlag","CS"], <del> [0x2000,0x0065,"AnnotationFlag","CS"], <del> [0x2000,0x0067,"ImageOverlayFlag","CS"], <del> [0x2000,0x0069,"PresentationLUTFlag","CS"], <del> [0x2000,0x006A,"ImageBoxPresentationLUTFlag","CS"], <del> [0x2000,0x00A0,"MemoryBitDepth","US"], <del> [0x2000,0x00A1,"PrintingBitDepth","US"], <del> [0x2000,0x00A2,"MediaInstalledSequence","SQ"], <del> [0x2000,0x00A4,"OtherMediaAvailableSequence","SQ"], <del> [0x2000,0x00A8,"SupportedImageDisplayFormatsSequence","SQ"], <del> [0x2000,0x0500,"ReferencedFilmBoxSequence","SQ"], <del> [0x2000,0x0510,"ReferencedStoredPrintSequence","SQ"], <del> [0x2010,0x0010,"ImageDisplayFormat","ST"], <del> [0x2010,0x0030,"AnnotationDisplayFormatID","CS"], <del> [0x2010,0x0040,"FilmOrientation","CS"], <del> [0x2010,0x0050,"FilmSizeID","CS"], <del> [0x2010,0x0052,"PrinterResolutionID","CS"], <del> [0x2010,0x0054,"DefaultPrinterResolutionID","CS"], <del> [0x2010,0x0060,"MagnificationType","CS"], <del> [0x2010,0x0080,"SmoothingType","CS"], <del> [0x2010,0x00A6,"DefaultMagnificationType","CS"], <del> [0x2010,0x00A7,"OtherMagnificationTypesAvailable","CS"], <del> [0x2010,0x00A8,"DefaultSmoothingType","CS"], <del> [0x2010,0x00A9,"OtherSmoothingTypesAvailable","CS"], <del> [0x2010,0x0100,"BorderDensity","CS"], <del> [0x2010,0x0110,"EmptyImageDensity","CS"], <del> [0x2010,0x0120,"MinDensity","US"], <del> [0x2010,0x0130,"MaxDensity","US"], <del> [0x2010,0x0140,"Trim","CS"], <del> [0x2010,0x0150,"ConfigurationInformation","ST"], <del> [0x2010,0x0152,"ConfigurationInformationDescription","LT"], <del> [0x2010,0x0154,"MaximumCollatedFilms","IS"], <del> [0x2010,0x015E,"Illumination","US"], <del> [0x2010,0x0160,"ReflectedAmbientLight","US"], <del> [0x2010,0x0376,"PrinterPixelSpacing","DS"], <del> [0x2010,0x0500,"ReferencedFilmSessionSequence","SQ"], <del> [0x2010,0x0510,"ReferencedImageBoxSequence","SQ"], <del> [0x2010,0x0520,"ReferencedBasicAnnotationBoxSequence","SQ"], <del> [0x2020,0x0010,"ImageBoxPosition","US"], <del> [0x2020,0x0020,"Polarity","CS"], <del> [0x2020,0x0030,"RequestedImageSize","DS"], <del> [0x2020,0x0040,"RequestedDecimateCropBehavior","CS"], <del> [0x2020,0x0050,"RequestedResolutionID","CS"], <del> [0x2020,0x00A0,"RequestedImageSizeFlag","CS"], <del> [0x2020,0x00A2,"DecimateCropResult","CS"], <del> [0x2020,0x0110,"BasicGrayscaleImageSequence","SQ"], <del> [0x2020,0x0111,"BasicColorImageSequence","SQ"], <del> [0x2020,0x0130,"ReferencedImageOverlayBoxSequence","SQ"], <del> [0x2020,0x0140,"ReferencedVOILUTBoxSequence","SQ"], <del> [0x2030,0x0010,"AnnotationPosition","US"], <del> [0x2030,0x0020,"TextString","LO"], <del> [0x2040,0x0010,"ReferencedOverlayPlaneSequence","SQ"], <del> [0x2040,0x0011,"ReferencedOverlayPlaneGroups","US"], <del> [0x2040,0x0020,"OverlayPixelDataSequence","SQ"], <del> [0x2040,0x0060,"OverlayMagnificationType","CS"], <del> [0x2040,0x0070,"OverlaySmoothingType","CS"], <del> [0x2040,0x0072,"OverlayOrImageMagnification","CS"], <del> [0x2040,0x0074,"MagnifyToNumberOfColumns","US"], <del> [0x2040,0x0080,"OverlayForegroundDensity","CS"], <del> [0x2040,0x0082,"OverlayBackgroundDensity","CS"], <del> [0x2040,0x0090,"OverlayMode","CS"], <del> [0x2040,0x0100,"ThresholdDensity","CS"], <del> [0x2040,0x0500,"ReferencedImageBoxSequenceRetired","SQ"], <del> [0x2050,0x0010,"PresentationLUTSequence","SQ"], <del> [0x2050,0x0020,"PresentationLUTShape","CS"], <del> [0x2050,0x0500,"ReferencedPresentationLUTSequence","SQ"], <del> [0x2100,0x0010,"PrintJobID","SH"], <del> [0x2100,0x0020,"ExecutionStatus","CS"], <del> [0x2100,0x0030,"ExecutionStatusInfo","CS"], <del> [0x2100,0x0040,"CreationDate","DA"], <del> [0x2100,0x0050,"CreationTime","TM"], <del> [0x2100,0x0070,"Originator","AE"], <del> [0x2100,0x0140,"DestinationAE","AE"], <del> [0x2100,0x0160,"OwnerID","SH"], <del> [0x2100,0x0170,"NumberOfFilms","IS"], <del> [0x2100,0x0500,"ReferencedPrintJobSequencePullStoredPrint","SQ"], <del> [0x2110,0x0010,"PrinterStatus","CS"], <del> [0x2110,0x0020,"PrinterStatusInfo","CS"], <del> [0x2110,0x0030,"PrinterName","LO"], <del> [0x2110,0x0099,"PrintQueueID","SH"], <del> [0x2120,0x0010,"QueueStatus","CS"], <del> [0x2120,0x0050,"PrintJobDescriptionSequence","SQ"], <del> [0x2120,0x0070,"ReferencedPrintJobSequence","SQ"], <del> [0x2130,0x0010,"PrintManagementCapabilitiesSequence","SQ"], <del> [0x2130,0x0015,"PrinterCharacteristicsSequence","SQ"], <del> [0x2130,0x0030,"FilmBoxContentSequence","SQ"], <del> [0x2130,0x0040,"ImageBoxContentSequence","SQ"], <del> [0x2130,0x0050,"AnnotationContentSequence","SQ"], <del> [0x2130,0x0060,"ImageOverlayBoxContentSequence","SQ"], <del> [0x2130,0x0080,"PresentationLUTContentSequence","SQ"], <del> [0x2130,0x00A0,"ProposedStudySequence","SQ"], <del> [0x2130,0x00C0,"OriginalImageSequence","SQ"], <del> [0x2200,0x0001,"LabelUsingInformationExtractedFromInstances","CS"], <del> [0x2200,0x0002,"LabelText","UT"], <del> [0x2200,0x0003,"LabelStyleSelection","CS"], <del> [0x2200,0x0004,"MediaDisposition","LT"], <del> [0x2200,0x0005,"BarcodeValue","LT"], <del> [0x2200,0x0006,"BarcodeSymbology","CS"], <del> [0x2200,0x0007,"AllowMediaSplitting","CS"], <del> [0x2200,0x0008,"IncludeNonDICOMObjects","CS"], <del> [0x2200,0x0009,"IncludeDisplayApplication","CS"], <del> [0x2200,0x000A,"PreserveCompositeInstancesAfterMediaCreation","CS"], <del> [0x2200,0x000B,"TotalNumberOfPiecesOfMediaCreated","US"], <del> [0x2200,0x000C,"RequestedMediaApplicationProfile","LO"], <del> [0x2200,0x000D,"ReferencedStorageMediaSequence","SQ"], <del> [0x2200,0x000E,"FailureAttributes","AT"], <del> [0x2200,0x000F,"AllowLossyCompression","CS"], <del> [0x2200,0x0020,"RequestPriority","CS"], <del> [0x3002,0x0002,"RTImageLabel","SH"], <del> [0x3002,0x0003,"RTImageName","LO"], <del> [0x3002,0x0004,"RTImageDescription","ST"], <del> [0x3002,0x000A,"ReportedValuesOrigin","CS"], <del> [0x3002,0x000C,"RTImagePlane","CS"], <del> [0x3002,0x000D,"XRayImageReceptorTranslation","DS"], <del> [0x3002,0x000E,"XRayImageReceptorAngle","DS"], <del> [0x3002,0x0010,"RTImageOrientation","DS"], <del> [0x3002,0x0011,"ImagePlanePixelSpacing","DS"], <del> [0x3002,0x0012,"RTImagePosition","DS"], <del> [0x3002,0x0020,"RadiationMachineName","SH"], <del> [0x3002,0x0022,"RadiationMachineSAD","DS"], <del> [0x3002,0x0024,"RadiationMachineSSD","DS"], <del> [0x3002,0x0026,"RTImageSID","DS"], <del> [0x3002,0x0028,"SourceToReferenceObjectDistance","DS"], <del> [0x3002,0x0029,"FractionNumber","IS"], <del> [0x3002,0x0030,"ExposureSequence","SQ"], <del> [0x3002,0x0032,"MetersetExposure","DS"], <del> [0x3002,0x0034,"DiaphragmPosition","DS"], <del> [0x3002,0x0040,"FluenceMapSequence","SQ"], <del> [0x3002,0x0041,"FluenceDataSource","CS"], <del> [0x3002,0x0042,"FluenceDataScale","DS"], <del> [0x3002,0x0050,"PrimaryFluenceModeSequence","SQ"], <del> [0x3002,0x0051,"FluenceMode","CS"], <del> [0x3002,0x0052,"FluenceModeID","SH"], <del> [0x3004,0x0001,"DVHType","CS"], <del> [0x3004,0x0002,"DoseUnits","CS"], <del> [0x3004,0x0004,"DoseType","CS"], <del> [0x3004,0x0006,"DoseComment","LO"], <del> [0x3004,0x0008,"NormalizationPoint","DS"], <del> [0x3004,0x000A,"DoseSummationType","CS"], <del> [0x3004,0x000C,"GridFrameOffsetVector","DS"], <del> [0x3004,0x000E,"DoseGridScaling","DS"], <del> [0x3004,0x0010,"RTDoseROISequence","SQ"], <del> [0x3004,0x0012,"DoseValue","DS"], <del> [0x3004,0x0014,"TissueHeterogeneityCorrection","CS"], <del> [0x3004,0x0040,"DVHNormalizationPoint","DS"], <del> [0x3004,0x0042,"DVHNormalizationDoseValue","DS"], <del> [0x3004,0x0050,"DVHSequence","SQ"], <del> [0x3004,0x0052,"DVHDoseScaling","DS"], <del> [0x3004,0x0054,"DVHVolumeUnits","CS"], <del> [0x3004,0x0056,"DVHNumberOfBins","IS"], <del> [0x3004,0x0058,"DVHData","DS"], <del> [0x3004,0x0060,"DVHReferencedROISequence","SQ"], <del> [0x3004,0x0062,"DVHROIContributionType","CS"], <del> [0x3004,0x0070,"DVHMinimumDose","DS"], <del> [0x3004,0x0072,"DVHMaximumDose","DS"], <del> [0x3004,0x0074,"DVHMeanDose","DS"], <del> [0x3006,0x0002,"StructureSetLabel","SH"], <del> [0x3006,0x0004,"StructureSetName","LO"], <del> [0x3006,0x0006,"StructureSetDescription","ST"], <del> [0x3006,0x0008,"StructureSetDate","DA"], <del> [0x3006,0x0009,"StructureSetTime","TM"], <del> [0x3006,0x0010,"ReferencedFrameOfReferenceSequence","SQ"], <del> [0x3006,0x0012,"RTReferencedStudySequence","SQ"], <del> [0x3006,0x0014,"RTReferencedSeriesSequence","SQ"], <del> [0x3006,0x0016,"ContourImageSequence","SQ"], <del> [0x3006,0x0020,"StructureSetROISequence","SQ"], <del> [0x3006,0x0022,"ROINumber","IS"], <del> [0x3006,0x0024,"ReferencedFrameOfReferenceUID","UI"], <del> [0x3006,0x0026,"ROIName","LO"], <del> [0x3006,0x0028,"ROIDescription","ST"], <del> [0x3006,0x002A,"ROIDisplayColor","IS"], <del> [0x3006,0x002C,"ROIVolume","DS"], <del> [0x3006,0x0030,"RTRelatedROISequence","SQ"], <del> [0x3006,0x0033,"RTROIRelationship","CS"], <del> [0x3006,0x0036,"ROIGenerationAlgorithm","CS"], <del> [0x3006,0x0038,"ROIGenerationDescription","LO"], <del> [0x3006,0x0039,"ROIContourSequence","SQ"], <del> [0x3006,0x0040,"ContourSequence","SQ"], <del> [0x3006,0x0042,"ContourGeometricType","CS"], <del> [0x3006,0x0044,"ContourSlabThickness","DS"], <del> [0x3006,0x0045,"ContourOffsetVector","DS"], <del> [0x3006,0x0046,"NumberOfContourPoints","IS"], <del> [0x3006,0x0048,"ContourNumber","IS"], <del> [0x3006,0x0049,"AttachedContours","IS"], <del> [0x3006,0x0050,"ContourData","DS"], <del> [0x3006,0x0080,"RTROIObservationsSequence","SQ"], <del> [0x3006,0x0082,"ObservationNumber","IS"], <del> [0x3006,0x0084,"ReferencedROINumber","IS"], <del> [0x3006,0x0085,"ROIObservationLabel","SH"], <del> [0x3006,0x0086,"RTROIIdentificationCodeSequence","SQ"], <del> [0x3006,0x0088,"ROIObservationDescription","ST"], <del> [0x3006,0x00A0,"RelatedRTROIObservationsSequence","SQ"], <del> [0x3006,0x00A4,"RTROIInterpretedType","CS"], <del> [0x3006,0x00A6,"ROIInterpreter","PN"], <del> [0x3006,0x00B0,"ROIPhysicalPropertiesSequence","SQ"], <del> [0x3006,0x00B2,"ROIPhysicalProperty","CS"], <del> [0x3006,0x00B4,"ROIPhysicalPropertyValue","DS"], <del> [0x3006,0x00B6,"ROIElementalCompositionSequence","SQ"], <del> [0x3006,0x00B7,"ROIElementalCompositionAtomicNumber","US"], <del> [0x3006,0x00B8,"ROIElementalCompositionAtomicMassFraction","FL"], <del> [0x3006,0x00C0,"FrameOfReferenceRelationshipSequence","SQ"], <del> [0x3006,0x00C2,"RelatedFrameOfReferenceUID","UI"], <del> [0x3006,0x00C4,"FrameOfReferenceTransformationType","CS"], <del> [0x3006,0x00C6,"FrameOfReferenceTransformationMatrix","DS"], <del> [0x3006,0x00C8,"FrameOfReferenceTransformationComment","LO"], <del> [0x3008,0x0010,"MeasuredDoseReferenceSequence","SQ"], <del> [0x3008,0x0012,"MeasuredDoseDescription","ST"], <del> [0x3008,0x0014,"MeasuredDoseType","CS"], <del> [0x3008,0x0016,"MeasuredDoseValue","DS"], <del> [0x3008,0x0020,"TreatmentSessionBeamSequence","SQ"], <del> [0x3008,0x0021,"TreatmentSessionIonBeamSequence","SQ"], <del> [0x3008,0x0022,"CurrentFractionNumber","IS"], <del> [0x3008,0x0024,"TreatmentControlPointDate","DA"], <del> [0x3008,0x0025,"TreatmentControlPointTime","TM"], <del> [0x3008,0x002A,"TreatmentTerminationStatus","CS"], <del> [0x3008,0x002B,"TreatmentTerminationCode","SH"], <del> [0x3008,0x002C,"TreatmentVerificationStatus","CS"], <del> [0x3008,0x0030,"ReferencedTreatmentRecordSequence","SQ"], <del> [0x3008,0x0032,"SpecifiedPrimaryMeterset","DS"], <del> [0x3008,0x0033,"SpecifiedSecondaryMeterset","DS"], <del> [0x3008,0x0036,"DeliveredPrimaryMeterset","DS"], <del> [0x3008,0x0037,"DeliveredSecondaryMeterset","DS"], <del> [0x3008,0x003A,"SpecifiedTreatmentTime","DS"], <del> [0x3008,0x003B,"DeliveredTreatmentTime","DS"], <del> [0x3008,0x0040,"ControlPointDeliverySequence","SQ"], <del> [0x3008,0x0041,"IonControlPointDeliverySequence","SQ"], <del> [0x3008,0x0042,"SpecifiedMeterset","DS"], <del> [0x3008,0x0044,"DeliveredMeterset","DS"], <del> [0x3008,0x0045,"MetersetRateSet","FL"], <del> [0x3008,0x0046,"MetersetRateDelivered","FL"], <del> [0x3008,0x0047,"ScanSpotMetersetsDelivered","FL"], <del> [0x3008,0x0048,"DoseRateDelivered","DS"], <del> [0x3008,0x0050,"TreatmentSummaryCalculatedDoseReferenceSequence","SQ"], <del> [0x3008,0x0052,"CumulativeDoseToDoseReference","DS"], <del> [0x3008,0x0054,"FirstTreatmentDate","DA"], <del> [0x3008,0x0056,"MostRecentTreatmentDate","DA"], <del> [0x3008,0x005A,"NumberOfFractionsDelivered","IS"], <del> [0x3008,0x0060,"OverrideSequence","SQ"], <del> [0x3008,0x0061,"ParameterSequencePointer","AT"], <del> [0x3008,0x0062,"OverrideParameterPointer","AT"], <del> [0x3008,0x0063,"ParameterItemIndex","IS"], <del> [0x3008,0x0064,"MeasuredDoseReferenceNumber","IS"], <del> [0x3008,0x0065,"ParameterPointer","AT"], <del> [0x3008,0x0066,"OverrideReason","ST"], <del> [0x3008,0x0068,"CorrectedParameterSequence","SQ"], <del> [0x3008,0x006A,"CorrectionValue","FL"], <del> [0x3008,0x0070,"CalculatedDoseReferenceSequence","SQ"], <del> [0x3008,0x0072,"CalculatedDoseReferenceNumber","IS"], <del> [0x3008,0x0074,"CalculatedDoseReferenceDescription","ST"], <del> [0x3008,0x0076,"CalculatedDoseReferenceDoseValue","DS"], <del> [0x3008,0x0078,"StartMeterset","DS"], <del> [0x3008,0x007A,"EndMeterset","DS"], <del> [0x3008,0x0080,"ReferencedMeasuredDoseReferenceSequence","SQ"], <del> [0x3008,0x0082,"ReferencedMeasuredDoseReferenceNumber","IS"], <del> [0x3008,0x0090,"ReferencedCalculatedDoseReferenceSequence","SQ"], <del> [0x3008,0x0092,"ReferencedCalculatedDoseReferenceNumber","IS"], <del> [0x3008,0x00A0,"BeamLimitingDeviceLeafPairsSequence","SQ"], <del> [0x3008,0x00B0,"RecordedWedgeSequence","SQ"], <del> [0x3008,0x00C0,"RecordedCompensatorSequence","SQ"], <del> [0x3008,0x00D0,"RecordedBlockSequence","SQ"], <del> [0x3008,0x00E0,"TreatmentSummaryMeasuredDoseReferenceSequence","SQ"], <del> [0x3008,0x00F0,"RecordedSnoutSequence","SQ"], <del> [0x3008,0x00F2,"RecordedRangeShifterSequence","SQ"], <del> [0x3008,0x00F4,"RecordedLateralSpreadingDeviceSequence","SQ"], <del> [0x3008,0x00F6,"RecordedRangeModulatorSequence","SQ"], <del> [0x3008,0x0100,"RecordedSourceSequence","SQ"], <del> [0x3008,0x0105,"SourceSerialNumber","LO"], <del> [0x3008,0x0110,"TreatmentSessionApplicationSetupSequence","SQ"], <del> [0x3008,0x0116,"ApplicationSetupCheck","CS"], <del> [0x3008,0x0120,"RecordedBrachyAccessoryDeviceSequence","SQ"], <del> [0x3008,0x0122,"ReferencedBrachyAccessoryDeviceNumber","IS"], <del> [0x3008,0x0130,"RecordedChannelSequence","SQ"], <del> [0x3008,0x0132,"SpecifiedChannelTotalTime","DS"], <del> [0x3008,0x0134,"DeliveredChannelTotalTime","DS"], <del> [0x3008,0x0136,"SpecifiedNumberOfPulses","IS"], <del> [0x3008,0x0138,"DeliveredNumberOfPulses","IS"], <del> [0x3008,0x013A,"SpecifiedPulseRepetitionInterval","DS"], <del> [0x3008,0x013C,"DeliveredPulseRepetitionInterval","DS"], <del> [0x3008,0x0140,"RecordedSourceApplicatorSequence","SQ"], <del> [0x3008,0x0142,"ReferencedSourceApplicatorNumber","IS"], <del> [0x3008,0x0150,"RecordedChannelShieldSequence","SQ"], <del> [0x3008,0x0152,"ReferencedChannelShieldNumber","IS"], <del> [0x3008,0x0160,"BrachyControlPointDeliveredSequence","SQ"], <del> [0x3008,0x0162,"SafePositionExitDate","DA"], <del> [0x3008,0x0164,"SafePositionExitTime","TM"], <del> [0x3008,0x0166,"SafePositionReturnDate","DA"], <del> [0x3008,0x0168,"SafePositionReturnTime","TM"], <del> [0x3008,0x0200,"CurrentTreatmentStatus","CS"], <del> [0x3008,0x0202,"TreatmentStatusComment","ST"], <del> [0x3008,0x0220,"FractionGroupSummarySequence","SQ"], <del> [0x3008,0x0223,"ReferencedFractionNumber","IS"], <del> [0x3008,0x0224,"FractionGroupType","CS"], <del> [0x3008,0x0230,"BeamStopperPosition","CS"], <del> [0x3008,0x0240,"FractionStatusSummarySequence","SQ"], <del> [0x3008,0x0250,"TreatmentDate","DA"], <del> [0x3008,0x0251,"TreatmentTime","TM"], <del> [0x300A,0x0002,"RTPlanLabel","SH"], <del> [0x300A,0x0003,"RTPlanName","LO"], <del> [0x300A,0x0004,"RTPlanDescription","ST"], <del> [0x300A,0x0006,"RTPlanDate","DA"], <del> [0x300A,0x0007,"RTPlanTime","TM"], <del> [0x300A,0x0009,"TreatmentProtocols","LO"], <del> [0x300A,0x000A,"PlanIntent","CS"], <del> [0x300A,0x000B,"TreatmentSites","LO"], <del> [0x300A,0x000C,"RTPlanGeometry","CS"], <del> [0x300A,0x000E,"PrescriptionDescription","ST"], <del> [0x300A,0x0010,"DoseReferenceSequence","SQ"], <del> [0x300A,0x0012,"DoseReferenceNumber","IS"], <del> [0x300A,0x0013,"DoseReferenceUID","UI"], <del> [0x300A,0x0014,"DoseReferenceStructureType","CS"], <del> [0x300A,0x0015,"NominalBeamEnergyUnit","CS"], <del> [0x300A,0x0016,"DoseReferenceDescription","LO"], <del> [0x300A,0x0018,"DoseReferencePointCoordinates","DS"], <del> [0x300A,0x001A,"NominalPriorDose","DS"], <del> [0x300A,0x0020,"DoseReferenceType","CS"], <del> [0x300A,0x0021,"ConstraintWeight","DS"], <del> [0x300A,0x0022,"DeliveryWarningDose","DS"], <del> [0x300A,0x0023,"DeliveryMaximumDose","DS"], <del> [0x300A,0x0025,"TargetMinimumDose","DS"], <del> [0x300A,0x0026,"TargetPrescriptionDose","DS"], <del> [0x300A,0x0027,"TargetMaximumDose","DS"], <del> [0x300A,0x0028,"TargetUnderdoseVolumeFraction","DS"], <del> [0x300A,0x002A,"OrganAtRiskFullVolumeDose","DS"], <del> [0x300A,0x002B,"OrganAtRiskLimitDose","DS"], <del> [0x300A,0x002C,"OrganAtRiskMaximumDose","DS"], <del> [0x300A,0x002D,"OrganAtRiskOverdoseVolumeFraction","DS"], <del> [0x300A,0x0040,"ToleranceTableSequence","SQ"], <del> [0x300A,0x0042,"ToleranceTableNumber","IS"], <del> [0x300A,0x0043,"ToleranceTableLabel","SH"], <del> [0x300A,0x0044,"GantryAngleTolerance","DS"], <del> [0x300A,0x0046,"BeamLimitingDeviceAngleTolerance","DS"], <del> [0x300A,0x0048,"BeamLimitingDeviceToleranceSequence","SQ"], <del> [0x300A,0x004A,"BeamLimitingDevicePositionTolerance","DS"], <del> [0x300A,0x004B,"SnoutPositionTolerance","FL"], <del> [0x300A,0x004C,"PatientSupportAngleTolerance","DS"], <del> [0x300A,0x004E,"TableTopEccentricAngleTolerance","DS"], <del> [0x300A,0x004F,"TableTopPitchAngleTolerance","FL"], <del> [0x300A,0x0050,"TableTopRollAngleTolerance","FL"], <del> [0x300A,0x0051,"TableTopVerticalPositionTolerance","DS"], <del> [0x300A,0x0052,"TableTopLongitudinalPositionTolerance","DS"], <del> [0x300A,0x0053,"TableTopLateralPositionTolerance","DS"], <del> [0x300A,0x0055,"RTPlanRelationship","CS"], <del> [0x300A,0x0070,"FractionGroupSequence","SQ"], <del> [0x300A,0x0071,"FractionGroupNumber","IS"], <del> [0x300A,0x0072,"FractionGroupDescription","LO"], <del> [0x300A,0x0078,"NumberOfFractionsPlanned","IS"], <del> [0x300A,0x0079,"NumberOfFractionPatternDigitsPerDay","IS"], <del> [0x300A,0x007A,"RepeatFractionCycleLength","IS"], <del> [0x300A,0x007B,"FractionPattern","LT"], <del> [0x300A,0x0080,"NumberOfBeams","IS"], <del> [0x300A,0x0082,"BeamDoseSpecificationPoint","DS"], <del> [0x300A,0x0084,"BeamDose","DS"], <del> [0x300A,0x0086,"BeamMeterset","DS"], <del> [0x300A,0x0088,"BeamDosePointDepth","FL"], <del> [0x300A,0x0089,"BeamDosePointEquivalentDepth","FL"], <del> [0x300A,0x008A,"BeamDosePointSSD","FL"], <del> [0x300A,0x00A0,"NumberOfBrachyApplicationSetups","IS"], <del> [0x300A,0x00A2,"BrachyApplicationSetupDoseSpecificationPoint","DS"], <del> [0x300A,0x00A4,"BrachyApplicationSetupDose","DS"], <del> [0x300A,0x00B0,"BeamSequence","SQ"], <del> [0x300A,0x00B2,"TreatmentMachineName","SH"], <del> [0x300A,0x00B3,"PrimaryDosimeterUnit","CS"], <del> [0x300A,0x00B4,"SourceAxisDistance","DS"], <del> [0x300A,0x00B6,"BeamLimitingDeviceSequence","SQ"], <del> [0x300A,0x00B8,"RTBeamLimitingDeviceType","CS"], <del> [0x300A,0x00BA,"SourceToBeamLimitingDeviceDistance","DS"], <del> [0x300A,0x00BB,"IsocenterToBeamLimitingDeviceDistance","FL"], <del> [0x300A,0x00BC,"NumberOfLeafJawPairs","IS"], <del> [0x300A,0x00BE,"LeafPositionBoundaries","DS"], <del> [0x300A,0x00C0,"BeamNumber","IS"], <del> [0x300A,0x00C2,"BeamName","LO"], <del> [0x300A,0x00C3,"BeamDescription","ST"], <del> [0x300A,0x00C4,"BeamType","CS"], <del> [0x300A,0x00C6,"RadiationType","CS"], <del> [0x300A,0x00C7,"HighDoseTechniqueType","CS"], <del> [0x300A,0x00C8,"ReferenceImageNumber","IS"], <del> [0x300A,0x00CA,"PlannedVerificationImageSequence","SQ"], <del> [0x300A,0x00CC,"ImagingDeviceSpecificAcquisitionParameters","LO"], <del> [0x300A,0x00CE,"TreatmentDeliveryType","CS"], <del> [0x300A,0x00D0,"NumberOfWedges","IS"], <del> [0x300A,0x00D1,"WedgeSequence","SQ"], <del> [0x300A,0x00D2,"WedgeNumber","IS"], <del> [0x300A,0x00D3,"WedgeType","CS"], <del> [0x300A,0x00D4,"WedgeID","SH"], <del> [0x300A,0x00D5,"WedgeAngle","IS"], <del> [0x300A,0x00D6,"WedgeFactor","DS"], <del> [0x300A,0x00D7,"TotalWedgeTrayWaterEquivalentThickness","FL"], <del> [0x300A,0x00D8,"WedgeOrientation","DS"], <del> [0x300A,0x00D9,"IsocenterToWedgeTrayDistance","FL"], <del> [0x300A,0x00DA,"SourceToWedgeTrayDistance","DS"], <del> [0x300A,0x00DB,"WedgeThinEdgePosition","FL"], <del> [0x300A,0x00DC,"BolusID","SH"], <del> [0x300A,0x00DD,"BolusDescription","ST"], <del> [0x300A,0x00E0,"NumberOfCompensators","IS"], <del> [0x300A,0x00E1,"MaterialID","SH"], <del> [0x300A,0x00E2,"TotalCompensatorTrayFactor","DS"], <del> [0x300A,0x00E3,"CompensatorSequence","SQ"], <del> [0x300A,0x00E4,"CompensatorNumber","IS"], <del> [0x300A,0x00E5,"CompensatorID","SH"], <del> [0x300A,0x00E6,"SourceToCompensatorTrayDistance","DS"], <del> [0x300A,0x00E7,"CompensatorRows","IS"], <del> [0x300A,0x00E8,"CompensatorColumns","IS"], <del> [0x300A,0x00E9,"CompensatorPixelSpacing","DS"], <del> [0x300A,0x00EA,"CompensatorPosition","DS"], <del> [0x300A,0x00EB,"CompensatorTransmissionData","DS"], <del> [0x300A,0x00EC,"CompensatorThicknessData","DS"], <del> [0x300A,0x00ED,"NumberOfBoli","IS"], <del> [0x300A,0x00EE,"CompensatorType","CS"], <del> [0x300A,0x00F0,"NumberOfBlocks","IS"], <del> [0x300A,0x00F2,"TotalBlockTrayFactor","DS"], <del> [0x300A,0x00F3,"TotalBlockTrayWaterEquivalentThickness","FL"], <del> [0x300A,0x00F4,"BlockSequence","SQ"], <del> [0x300A,0x00F5,"BlockTrayID","SH"], <del> [0x300A,0x00F6,"SourceToBlockTrayDistance","DS"], <del> [0x300A,0x00F7,"IsocenterToBlockTrayDistance","FL"], <del> [0x300A,0x00F8,"BlockType","CS"], <del> [0x300A,0x00F9,"AccessoryCode","LO"], <del> [0x300A,0x00FA,"BlockDivergence","CS"], <del> [0x300A,0x00FB,"BlockMountingPosition","CS"], <del> [0x300A,0x00FC,"BlockNumber","IS"], <del> [0x300A,0x00FE,"BlockName","LO"], <del> [0x300A,0x0100,"BlockThickness","DS"], <del> [0x300A,0x0102,"BlockTransmission","DS"], <del> [0x300A,0x0104,"BlockNumberOfPoints","IS"], <del> [0x300A,0x0106,"BlockData","DS"], <del> [0x300A,0x0107,"ApplicatorSequence","SQ"], <del> [0x300A,0x0108,"ApplicatorID","SH"], <del> [0x300A,0x0109,"ApplicatorType","CS"], <del> [0x300A,0x010A,"ApplicatorDescription","LO"], <del> [0x300A,0x010C,"CumulativeDoseReferenceCoefficient","DS"], <del> [0x300A,0x010E,"FinalCumulativeMetersetWeight","DS"], <del> [0x300A,0x0110,"NumberOfControlPoints","IS"], <del> [0x300A,0x0111,"ControlPointSequence","SQ"], <del> [0x300A,0x0112,"ControlPointIndex","IS"], <del> [0x300A,0x0114,"NominalBeamEnergy","DS"], <del> [0x300A,0x0115,"DoseRateSet","DS"], <del> [0x300A,0x0116,"WedgePositionSequence","SQ"], <del> [0x300A,0x0118,"WedgePosition","CS"], <del> [0x300A,0x011A,"BeamLimitingDevicePositionSequence","SQ"], <del> [0x300A,0x011C,"LeafJawPositions","DS"], <del> [0x300A,0x011E,"GantryAngle","DS"], <del> [0x300A,0x011F,"GantryRotationDirection","CS"], <del> [0x300A,0x0120,"BeamLimitingDeviceAngle","DS"], <del> [0x300A,0x0121,"BeamLimitingDeviceRotationDirection","CS"], <del> [0x300A,0x0122,"PatientSupportAngle","DS"], <del> [0x300A,0x0123,"PatientSupportRotationDirection","CS"], <del> [0x300A,0x0124,"TableTopEccentricAxisDistance","DS"], <del> [0x300A,0x0125,"TableTopEccentricAngle","DS"], <del> [0x300A,0x0126,"TableTopEccentricRotationDirection","CS"], <del> [0x300A,0x0128,"TableTopVerticalPosition","DS"], <del> [0x300A,0x0129,"TableTopLongitudinalPosition","DS"], <del> [0x300A,0x012A,"TableTopLateralPosition","DS"], <del> [0x300A,0x012C,"IsocenterPosition","DS"], <del> [0x300A,0x012E,"SurfaceEntryPoint","DS"], <del> [0x300A,0x0130,"SourceToSurfaceDistance","DS"], <del> [0x300A,0x0134,"CumulativeMetersetWeight","DS"], <del> [0x300A,0x0140,"TableTopPitchAngle","FL"], <del> [0x300A,0x0142,"TableTopPitchRotationDirection","CS"], <del> [0x300A,0x0144,"TableTopRollAngle","FL"], <del> [0x300A,0x0146,"TableTopRollRotationDirection","CS"], <del> [0x300A,0x0148,"HeadFixationAngle","FL"], <del> [0x300A,0x014A,"GantryPitchAngle","FL"], <del> [0x300A,0x014C,"GantryPitchRotationDirection","CS"], <del> [0x300A,0x014E,"GantryPitchAngleTolerance","FL"], <del> [0x300A,0x0180,"PatientSetupSequence","SQ"], <del> [0x300A,0x0182,"PatientSetupNumber","IS"], <del> [0x300A,0x0183,"PatientSetupLabel","LO"], <del> [0x300A,0x0184,"PatientAdditionalPosition","LO"], <del> [0x300A,0x0190,"FixationDeviceSequence","SQ"], <del> [0x300A,0x0192,"FixationDeviceType","CS"], <del> [0x300A,0x0194,"FixationDeviceLabel","SH"], <del> [0x300A,0x0196,"FixationDeviceDescription","ST"], <del> [0x300A,0x0198,"FixationDevicePosition","SH"], <del> [0x300A,0x0199,"FixationDevicePitchAngle","FL"], <del> [0x300A,0x019A,"FixationDeviceRollAngle","FL"], <del> [0x300A,0x01A0,"ShieldingDeviceSequence","SQ"], <del> [0x300A,0x01A2,"ShieldingDeviceType","CS"], <del> [0x300A,0x01A4,"ShieldingDeviceLabel","SH"], <del> [0x300A,0x01A6,"ShieldingDeviceDescription","ST"], <del> [0x300A,0x01A8,"ShieldingDevicePosition","SH"], <del> [0x300A,0x01B0,"SetupTechnique","CS"], <del> [0x300A,0x01B2,"SetupTechniqueDescription","ST"], <del> [0x300A,0x01B4,"SetupDeviceSequence","SQ"], <del> [0x300A,0x01B6,"SetupDeviceType","CS"], <del> [0x300A,0x01B8,"SetupDeviceLabel","SH"], <del> [0x300A,0x01BA,"SetupDeviceDescription","ST"], <del> [0x300A,0x01BC,"SetupDeviceParameter","DS"], <del> [0x300A,0x01D0,"SetupReferenceDescription","ST"], <del> [0x300A,0x01D2,"TableTopVerticalSetupDisplacement","DS"], <del> [0x300A,0x01D4,"TableTopLongitudinalSetupDisplacement","DS"], <del> [0x300A,0x01D6,"TableTopLateralSetupDisplacement","DS"], <del> [0x300A,0x0200,"BrachyTreatmentTechnique","CS"], <del> [0x300A,0x0202,"BrachyTreatmentType","CS"], <del> [0x300A,0x0206,"TreatmentMachineSequence","SQ"], <del> [0x300A,0x0210,"SourceSequence","SQ"], <del> [0x300A,0x0212,"SourceNumber","IS"], <del> [0x300A,0x0214,"SourceType","CS"], <del> [0x300A,0x0216,"SourceManufacturer","LO"], <del> [0x300A,0x0218,"ActiveSourceDiameter","DS"], <del> [0x300A,0x021A,"ActiveSourceLength","DS"], <del> [0x300A,0x0222,"SourceEncapsulationNominalThickness","DS"], <del> [0x300A,0x0224,"SourceEncapsulationNominalTransmission","DS"], <del> [0x300A,0x0226,"SourceIsotopeName","LO"], <del> [0x300A,0x0228,"SourceIsotopeHalfLife","DS"], <del> [0x300A,0x0229,"SourceStrengthUnits","CS"], <del> [0x300A,0x022A,"ReferenceAirKermaRate","DS"], <del> [0x300A,0x022B,"SourceStrength","DS"], <del> [0x300A,0x022C,"SourceStrengthReferenceDate","DA"], <del> [0x300A,0x022E,"SourceStrengthReferenceTime","TM"], <del> [0x300A,0x0230,"ApplicationSetupSequence","SQ"], <del> [0x300A,0x0232,"ApplicationSetupType","CS"], <del> [0x300A,0x0234,"ApplicationSetupNumber","IS"], <del> [0x300A,0x0236,"ApplicationSetupName","LO"], <del> [0x300A,0x0238,"ApplicationSetupManufacturer","LO"], <del> [0x300A,0x0240,"TemplateNumber","IS"], <del> [0x300A,0x0242,"TemplateType","SH"], <del> [0x300A,0x0244,"TemplateName","LO"], <del> [0x300A,0x0250,"TotalReferenceAirKerma","DS"], <del> [0x300A,0x0260,"BrachyAccessoryDeviceSequence","SQ"], <del> [0x300A,0x0262,"BrachyAccessoryDeviceNumber","IS"], <del> [0x300A,0x0263,"BrachyAccessoryDeviceID","SH"], <del> [0x300A,0x0264,"BrachyAccessoryDeviceType","CS"], <del> [0x300A,0x0266,"BrachyAccessoryDeviceName","LO"], <del> [0x300A,0x026A,"BrachyAccessoryDeviceNominalThickness","DS"], <del> [0x300A,0x026C,"BrachyAccessoryDeviceNominalTransmission","DS"], <del> [0x300A,0x0280,"ChannelSequence","SQ"], <del> [0x300A,0x0282,"ChannelNumber","IS"], <del> [0x300A,0x0284,"ChannelLength","DS"], <del> [0x300A,0x0286,"ChannelTotalTime","DS"], <del> [0x300A,0x0288,"SourceMovementType","CS"], <del> [0x300A,0x028A,"NumberOfPulses","IS"], <del> [0x300A,0x028C,"PulseRepetitionInterval","DS"], <del> [0x300A,0x0290,"SourceApplicatorNumber","IS"], <del> [0x300A,0x0291,"SourceApplicatorID","SH"], <del> [0x300A,0x0292,"SourceApplicatorType","CS"], <del> [0x300A,0x0294,"SourceApplicatorName","LO"], <del> [0x300A,0x0296,"SourceApplicatorLength","DS"], <del> [0x300A,0x0298,"SourceApplicatorManufacturer","LO"], <del> [0x300A,0x029C,"SourceApplicatorWallNominalThickness","DS"], <del> [0x300A,0x029E,"SourceApplicatorWallNominalTransmission","DS"], <del> [0x300A,0x02A0,"SourceApplicatorStepSize","DS"], <del> [0x300A,0x02A2,"TransferTubeNumber","IS"], <del> [0x300A,0x02A4,"TransferTubeLength","DS"], <del> [0x300A,0x02B0,"ChannelShieldSequence","SQ"], <del> [0x300A,0x02B2,"ChannelShieldNumber","IS"], <del> [0x300A,0x02B3,"ChannelShieldID","SH"], <del> [0x300A,0x02B4,"ChannelShieldName","LO"], <del> [0x300A,0x02B8,"ChannelShieldNominalThickness","DS"], <del> [0x300A,0x02BA,"ChannelShieldNominalTransmission","DS"], <del> [0x300A,0x02C8,"FinalCumulativeTimeWeight","DS"], <del> [0x300A,0x02D0,"BrachyControlPointSequence","SQ"], <del> [0x300A,0x02D2,"ControlPointRelativePosition","DS"], <del> [0x300A,0x02D4,"ControlPoint3DPosition","DS"], <del> [0x300A,0x02D6,"CumulativeTimeWeight","DS"], <del> [0x300A,0x02E0,"CompensatorDivergence","CS"], <del> [0x300A,0x02E1,"CompensatorMountingPosition","CS"], <del> [0x300A,0x02E2,"SourceToCompensatorDistance","DS"], <del> [0x300A,0x02E3,"TotalCompensatorTrayWaterEquivalentThickness","FL"], <del> [0x300A,0x02E4,"IsocenterToCompensatorTrayDistance","FL"], <del> [0x300A,0x02E5,"CompensatorColumnOffset","FL"], <del> [0x300A,0x02E6,"IsocenterToCompensatorDistances","FL"], <del> [0x300A,0x02E7,"CompensatorRelativeStoppingPowerRatio","FL"], <del> [0x300A,0x02E8,"CompensatorMillingToolDiameter","FL"], <del> [0x300A,0x02EA,"IonRangeCompensatorSequence","SQ"], <del> [0x300A,0x02EB,"CompensatorDescription","LT"], <del> [0x300A,0x0302,"RadiationMassNumber","IS"], <del> [0x300A,0x0304,"RadiationAtomicNumber","IS"], <del> [0x300A,0x0306,"RadiationChargeState","SS"], <del> [0x300A,0x0308,"ScanMode","CS"], <del> [0x300A,0x030A,"VirtualSourceAxisDistances","FL"], <del> [0x300A,0x030C,"SnoutSequence","SQ"], <del> [0x300A,0x030D,"SnoutPosition","FL"], <del> [0x300A,0x030F,"SnoutID","SH"], <del> [0x300A,0x0312,"NumberOfRangeShifters","IS"], <del> [0x300A,0x0314,"RangeShifterSequence","SQ"], <del> [0x300A,0x0316,"RangeShifterNumber","IS"], <del> [0x300A,0x0318,"RangeShifterID","SH"], <del> [0x300A,0x0320,"RangeShifterType","CS"], <del> [0x300A,0x0322,"RangeShifterDescription","LO"], <del> [0x300A,0x0330,"NumberOfLateralSpreadingDevices","IS"], <del> [0x300A,0x0332,"LateralSpreadingDeviceSequence","SQ"], <del> [0x300A,0x0334,"LateralSpreadingDeviceNumber","IS"], <del> [0x300A,0x0336,"LateralSpreadingDeviceID","SH"], <del> [0x300A,0x0338,"LateralSpreadingDeviceType","CS"], <del> [0x300A,0x033A,"LateralSpreadingDeviceDescription","LO"], <del> [0x300A,0x033C,"LateralSpreadingDeviceWaterEquivalentThickness","FL"], <del> [0x300A,0x0340,"NumberOfRangeModulators","IS"], <del> [0x300A,0x0342,"RangeModulatorSequence","SQ"], <del> [0x300A,0x0344,"RangeModulatorNumber","IS"], <del> [0x300A,0x0346,"RangeModulatorID","SH"], <del> [0x300A,0x0348,"RangeModulatorType","CS"], <del> [0x300A,0x034A,"RangeModulatorDescription","LO"], <del> [0x300A,0x034C,"BeamCurrentModulationID","SH"], <del> [0x300A,0x0350,"PatientSupportType","CS"], <del> [0x300A,0x0352,"PatientSupportID","SH"], <del> [0x300A,0x0354,"PatientSupportAccessoryCode","LO"], <del> [0x300A,0x0356,"FixationLightAzimuthalAngle","FL"], <del> [0x300A,0x0358,"FixationLightPolarAngle","FL"], <del> [0x300A,0x035A,"MetersetRate","FL"], <del> [0x300A,0x0360,"RangeShifterSettingsSequence","SQ"], <del> [0x300A,0x0362,"RangeShifterSetting","LO"], <del> [0x300A,0x0364,"IsocenterToRangeShifterDistance","FL"], <del> [0x300A,0x0366,"RangeShifterWaterEquivalentThickness","FL"], <del> [0x300A,0x0370,"LateralSpreadingDeviceSettingsSequence","SQ"], <del> [0x300A,0x0372,"LateralSpreadingDeviceSetting","LO"], <del> [0x300A,0x0374,"IsocenterToLateralSpreadingDeviceDistance","FL"], <del> [0x300A,0x0380,"RangeModulatorSettingsSequence","SQ"], <del> [0x300A,0x0382,"RangeModulatorGatingStartValue","FL"], <del> [0x300A,0x0384,"RangeModulatorGatingStopValue","FL"], <del> [0x300A,0x0386,"RangeModulatorGatingStartWaterEquivalentThickness","FL"], <del> [0x300A,0x0388,"RangeModulatorGatingStopWaterEquivalentThickness","FL"], <del> [0x300A,0x038A,"IsocenterToRangeModulatorDistance","FL"], <del> [0x300A,0x0390,"ScanSpotTuneID","SH"], <del> [0x300A,0x0392,"NumberOfScanSpotPositions","IS"], <del> [0x300A,0x0394,"ScanSpotPositionMap","FL"], <del> [0x300A,0x0396,"ScanSpotMetersetWeights","FL"], <del> [0x300A,0x0398,"ScanningSpotSize","FL"], <del> [0x300A,0x039A,"NumberOfPaintings","IS"], <del> [0x300A,0x03A0,"IonToleranceTableSequence","SQ"], <del> [0x300A,0x03A2,"IonBeamSequence","SQ"], <del> [0x300A,0x03A4,"IonBeamLimitingDeviceSequence","SQ"], <del> [0x300A,0x03A6,"IonBlockSequence","SQ"], <del> [0x300A,0x03A8,"IonControlPointSequence","SQ"], <del> [0x300A,0x03AA,"IonWedgeSequence","SQ"], <del> [0x300A,0x03AC,"IonWedgePositionSequence","SQ"], <del> [0x300A,0x0401,"ReferencedSetupImageSequence","SQ"], <del> [0x300A,0x0402,"SetupImageComment","ST"], <del> [0x300A,0x0410,"MotionSynchronizationSequence","SQ"], <del> [0x300A,0x0412,"ControlPointOrientation","FL"], <del> [0x300A,0x0420,"GeneralAccessorySequence","SQ"], <del> [0x300A,0x0421,"GeneralAccessoryID","SH"], <del> [0x300A,0x0422,"GeneralAccessoryDescription","ST"], <del> [0x300A,0x0423,"GeneralAccessoryType","CS"], <del> [0x300A,0x0424,"GeneralAccessoryNumber","IS"], <del> [0x300A,0x0431,"ApplicatorGeometrySequence","SQ"], <del> [0x300A,0x0432,"ApplicatorApertureShape","CS"], <del> [0x300A,0x0433,"ApplicatorOpening","FL"], <del> [0x300A,0x0434,"ApplicatorOpeningX","FL"], <del> [0x300A,0x0435,"ApplicatorOpeningY","FL"], <del> [0x300A,0x0436,"SourceToApplicatorMountingPositionDistance","FL"], <del> [0x300C,0x0002,"ReferencedRTPlanSequence","SQ"], <del> [0x300C,0x0004,"ReferencedBeamSequence","SQ"], <del> [0x300C,0x0006,"ReferencedBeamNumber","IS"], <del> [0x300C,0x0007,"ReferencedReferenceImageNumber","IS"], <del> [0x300C,0x0008,"StartCumulativeMetersetWeight","DS"], <del> [0x300C,0x0009,"EndCumulativeMetersetWeight","DS"], <del> [0x300C,0x000A,"ReferencedBrachyApplicationSetupSequence","SQ"], <del> [0x300C,0x000C,"ReferencedBrachyApplicationSetupNumber","IS"], <del> [0x300C,0x000E,"ReferencedSourceNumber","IS"], <del> [0x300C,0x0020,"ReferencedFractionGroupSequence","SQ"], <del> [0x300C,0x0022,"ReferencedFractionGroupNumber","IS"], <del> [0x300C,0x0040,"ReferencedVerificationImageSequence","SQ"], <del> [0x300C,0x0042,"ReferencedReferenceImageSequence","SQ"], <del> [0x300C,0x0050,"ReferencedDoseReferenceSequence","SQ"], <del> [0x300C,0x0051,"ReferencedDoseReferenceNumber","IS"], <del> [0x300C,0x0055,"BrachyReferencedDoseReferenceSequence","SQ"], <del> [0x300C,0x0060,"ReferencedStructureSetSequence","SQ"], <del> [0x300C,0x006A,"ReferencedPatientSetupNumber","IS"], <del> [0x300C,0x0080,"ReferencedDoseSequence","SQ"], <del> [0x300C,0x00A0,"ReferencedToleranceTableNumber","IS"], <del> [0x300C,0x00B0,"ReferencedBolusSequence","SQ"], <del> [0x300C,0x00C0,"ReferencedWedgeNumber","IS"], <del> [0x300C,0x00D0,"ReferencedCompensatorNumber","IS"], <del> [0x300C,0x00E0,"ReferencedBlockNumber","IS"], <del> [0x300C,0x00F0,"ReferencedControlPointIndex","IS"], <del> [0x300C,0x00F2,"ReferencedControlPointSequence","SQ"], <del> [0x300C,0x00F4,"ReferencedStartControlPointIndex","IS"], <del> [0x300C,0x00F6,"ReferencedStopControlPointIndex","IS"], <del> [0x300C,0x0100,"ReferencedRangeShifterNumber","IS"], <del> [0x300C,0x0102,"ReferencedLateralSpreadingDeviceNumber","IS"], <del> [0x300C,0x0104,"ReferencedRangeModulatorNumber","IS"], <del> [0x300E,0x0002,"ApprovalStatus","CS"], <del> [0x300E,0x0004,"ReviewDate","DA"], <del> [0x300E,0x0005,"ReviewTime","TM"], <del> [0x300E,0x0008,"ReviewerName","PN"], <del> [0x4000,0x0010,"Arbitrary","LT"], <del> [0x4000,0x4000,"TextComments","LT"], <del> [0x4008,0x0040,"ResultsID","SH"], <del> [0x4008,0x0042,"ResultsIDIssuer","LO"], <del> [0x4008,0x0050,"ReferencedInterpretationSequence","SQ"], <del> [0x4008,0x00FF,"ReportProductionStatusTrial","CS"], <del> [0x4008,0x0100,"InterpretationRecordedDate","DA"], <del> [0x4008,0x0101,"InterpretationRecordedTime","TM"], <del> [0x4008,0x0102,"InterpretationRecorder","PN"], <del> [0x4008,0x0103,"ReferenceToRecordedSound","LO"], <del> [0x4008,0x0108,"InterpretationTranscriptionDate","DA"], <del> [0x4008,0x0109,"InterpretationTranscriptionTime","TM"], <del> [0x4008,0x010A,"InterpretationTranscriber","PN"], <del> [0x4008,0x010B,"InterpretationText","ST"], <del> [0x4008,0x010C,"InterpretationAuthor","PN"], <del> [0x4008,0x0111,"InterpretationApproverSequence","SQ"], <del> [0x4008,0x0112,"InterpretationApprovalDate","DA"], <del> [0x4008,0x0113,"InterpretationApprovalTime","TM"], <del> [0x4008,0x0114,"PhysicianApprovingInterpretation","PN"], <del> [0x4008,0x0115,"InterpretationDiagnosisDescription","LT"], <del> [0x4008,0x0117,"InterpretationDiagnosisCodeSequence","SQ"], <del> [0x4008,0x0118,"ResultsDistributionListSequence","SQ"], <del> [0x4008,0x0119,"DistributionName","PN"], <del> [0x4008,0x011A,"DistributionAddress","LO"], <del> [0x4008,0x0200,"InterpretationID","SH"], <del> [0x4008,0x0202,"InterpretationIDIssuer","LO"], <del> [0x4008,0x0210,"InterpretationTypeID","CS"], <del> [0x4008,0x0212,"InterpretationStatusID","CS"], <del> [0x4008,0x0300,"Impressions","ST"], <del> [0x4008,0x4000,"ResultsComments","ST"], <del> [0x4010,0x0001,"LowEnergyDetectors","CS"], <del> [0x4010,0x0002,"HighEnergyDetectors","CS"], <del> [0x4010,0x0004,"DetectorGeometrySequence","SQ"], <del> [0x4010,0x1001,"ThreatROIVoxelSequence","SQ"], <del> [0x4010,0x1004,"ThreatROIBase","FL"], <del> [0x4010,0x1005,"ThreatROIExtents","FL"], <del> [0x4010,0x1006,"ThreatROIBitmap","OB"], <del> [0x4010,0x1007,"RouteSegmentID","SH"], <del> [0x4010,0x1008,"GantryType","CS"], <del> [0x4010,0x1009,"OOIOwnerType","CS"], <del> [0x4010,0x100A,"RouteSegmentSequence","SQ"], <del> [0x4010,0x1010,"PotentialThreatObjectID","US"], <del> [0x4010,0x1011,"ThreatSequence","SQ"], <del> [0x4010,0x1012,"ThreatCategory","CS"], <del> [0x4010,0x1013,"ThreatCategoryDescription","LT"], <del> [0x4010,0x1014,"ATDAbilityAssessment","CS"], <del> [0x4010,0x1015,"ATDAssessmentFlag","CS"], <del> [0x4010,0x1016,"ATDAssessmentProbability","FL"], <del> [0x4010,0x1017,"Mass","FL"], <del> [0x4010,0x1018,"Density","FL"], <del> [0x4010,0x1019,"ZEffective","FL"], <del> [0x4010,0x101A,"BoardingPassID","SH"], <del> [0x4010,0x101B,"CenterOfMass","FL"], <del> [0x4010,0x101C,"CenterOfPTO","FL"], <del> [0x4010,0x101D,"BoundingPolygon","FL"], <del> [0x4010,0x101E,"RouteSegmentStartLocationID","SH"], <del> [0x4010,0x101F,"RouteSegmentEndLocationID","SH"], <del> [0x4010,0x1020,"RouteSegmentLocationIDType","CS"], <del> [0x4010,0x1021,"AbortReason","CS"], <del> [0x4010,0x1023,"VolumeOfPTO","FL"], <del> [0x4010,0x1024,"AbortFlag","CS"], <del> [0x4010,0x1025,"RouteSegmentStartTime","DT"], <del> [0x4010,0x1026,"RouteSegmentEndTime","DT"], <del> [0x4010,0x1027,"TDRType","CS"], <del> [0x4010,0x1028,"InternationalRouteSegment","CS"], <del> [0x4010,0x1029,"ThreatDetectionAlgorithmandVersion","LO"], <del> [0x4010,0x102A,"AssignedLocation","SH"], <del> [0x4010,0x102B,"AlarmDecisionTime","DT"], <del> [0x4010,0x1031,"AlarmDecision","CS"], <del> [0x4010,0x1033,"NumberOfTotalObjects","US"], <del> [0x4010,0x1034,"NumberOfAlarmObjects","US"], <del> [0x4010,0x1037,"PTORepresentationSequence","SQ"], <del> [0x4010,0x1038,"ATDAssessmentSequence","SQ"], <del> [0x4010,0x1039,"TIPType","CS"], <del> [0x4010,0x103A,"DICOSVersion","CS"], <del> [0x4010,0x1041,"OOIOwnerCreationTime","DT"], <del> [0x4010,0x1042,"OOIType","CS"], <del> [0x4010,0x1043,"OOISize","FL"], <del> [0x4010,0x1044,"AcquisitionStatus","CS"], <del> [0x4010,0x1045,"BasisMaterialsCodeSequence","SQ"], <del> [0x4010,0x1046,"PhantomType","CS"], <del> [0x4010,0x1047,"OOIOwnerSequence","SQ"], <del> [0x4010,0x1048,"ScanType","CS"], <del> [0x4010,0x1051,"ItineraryID","LO"], <del> [0x4010,0x1052,"ItineraryIDType","SH"], <del> [0x4010,0x1053,"ItineraryIDAssigningAuthority","LO"], <del> [0x4010,0x1054,"RouteID","SH"], <del> [0x4010,0x1055,"RouteIDAssigningAuthority","SH"], <del> [0x4010,0x1056,"InboundArrivalType","CS"], <del> [0x4010,0x1058,"CarrierID","SH"], <del> [0x4010,0x1059,"CarrierIDAssigningAuthority","CS"], <del> [0x4010,0x1060,"SourceOrientation","FL"], <del> [0x4010,0x1061,"SourcePosition","FL"], <del> [0x4010,0x1062,"BeltHeight","FL"], <del> [0x4010,0x1064,"AlgorithmRoutingCodeSequence","SQ"], <del> [0x4010,0x1067,"TransportClassification","CS"], <del> [0x4010,0x1068,"OOITypeDescriptor","LT"], <del> [0x4010,0x1069,"TotalProcessingTime","FL"], <del> [0x4010,0x106C,"DetectorCalibrationData","OB"] <del>]; <add>daikon.Dictionary.dictPrivate = { <add> "0207" : { <add> "101F" : ["FE", "ElscintDataScale"] // uses special Elscint double type (see Tag class) <add> } <add>}; <add> <add> <add>daikon.Dictionary.dict = { <add> "0002" : { <add> "0000" : ["UL", "Group0002Length"], <add> "0001" : ["OB", "FileMetaInformationVersion"], <add> "0002" : ["UI", "MediaStoredSOPClassUID"], <add> "0003" : ["UI", "MediaStoredSOPInstanceUID"], <add> "0010" : ["UI", "TransferSyntaxUID"], <add> "0012" : ["UI", "ImplementationClassUID"], <add> "0013" : ["SH", "ImplementationVersionName"], <add> "0016" : ["AE", "SourceApplicationEntityTitle"], <add> "0100" : ["UI", "PrivateInformationCreatorUID"], <add> "0102" : ["OB", "PrivateInformation"] <add> }, <add> "0004" : { <add> "0000" : ["UL", "Group0004Length"], <add> "1130" : ["CS", "FilesetID"], <add> "1141" : ["CS", "FilesetDescriptorFileFileID"], <add> "1142" : ["CS", "FilesetDescriptorFileFormat"], <add> "1200" : ["UL", "RootDirectoryEntitysFirstDirectoryRecordOffset"], <add> "1202" : ["UL", "RootDirectoryEntitysLastDirectoryRecordOffset"], <add> "1212" : ["US", "File-setConsistenceFlag"], <add> "1220" : ["SQ", "DirectoryRecordSequence"], <add> "1400" : ["UL", "NextDirectoryRecordOffset"], <add> "1410" : ["US", "RecordInuseFlag"], <add> "1420" : ["UL", "ReferencedLowerlevelDirectoryEntityOffset"], <add> "1430" : ["CS", "DirectoryRecordType"], <add> "1432" : ["UI", "PrivateRecordUID"], <add> "1500" : ["CS", "ReferencedFileID"], <add> "1510" : ["UI", "ReferencedSOPClassUIDInFile"], <add> "1511" : ["UI", "ReferencedSOPInstanceUIDInFile"], <add> "1600" : ["UL", "NumberOfReferences"] <add> }, <add> "0008" : { <add> "0001" : ["UL", "LengthToEnd"], <add> "0005" : ["CS", "SpecificCharacterSet"], <add> "0006" : ["SQ", "LanguageCodeSequence"], <add> "0008" : ["CS", "ImageType"], <add> "0010" : ["SH", "RecognitionCode"], <add> "0012" : ["DA", "InstanceCreationDate"], <add> "0013" : ["TM", "InstanceCreationTime"], <add> "0014" : ["UI", "InstanceCreatorUID"], <add> "0016" : ["UI", "SOPClassUID"], <add> "0018" : ["UI", "SOPInstanceUID"], <add> "001A" : ["UI", "RelatedGeneralSOPClassUID"], <add> "001B" : ["UI", "OriginalSpecializedSOPClassUID"], <add> "0020" : ["DA", "StudyDate"], <add> "0021" : ["DA", "SeriesDate"], <add> "0022" : ["DA", "AcquisitionDate"], <add> "0023" : ["DA", "ContentDate"], <add> "0024" : ["DA", "OverlayDate"], <add> "0025" : ["DA", "CurveDate"], <add> "002A" : ["DT", "AcquisitionDateTime"], <add> "0030" : ["TM", "StudyTime"], <add> "0031" : ["TM", "SeriesTime"], <add> "0032" : ["TM", "AcquisitionTime"], <add> "0033" : ["TM", "ContentTime"], <add> "0034" : ["TM", "OverlayTime"], <add> "0035" : ["TM", "CurveTime"], <add> "0040" : ["US", "DataSetType"], <add> "0041" : ["LO", "DataSetSubtype"], <add> "0042" : ["CS", "NuclearMedicineSeriesType"], <add> "0050" : ["SH", "AccessionNumber"], <add> "0051" : ["SQ", "IssuerOfAccessionNumberSequence"], <add> "0052" : ["CS", "QueryRetrieveLevel"], <add> "0054" : ["AE", "RetrieveAETitle"], <add> "0056" : ["CS", "InstanceAvailability"], <add> "0058" : ["UI", "FailedSOPInstanceUIDList"], <add> "0060" : ["CS", "Modality"], <add> "0061" : ["CS", "ModalitiesInStudy"], <add> "0062" : ["UI", "SOPClassesInStudy"], <add> "0064" : ["CS", "ConversionType"], <add> "0068" : ["CS", "PresentationIntentType"], <add> "0070" : ["LO", "Manufacturer"], <add> "0080" : ["LO", "InstitutionName"], <add> "0081" : ["ST", "InstitutionAddress"], <add> "0082" : ["SQ", "InstitutionCodeSequence"], <add> "0090" : ["PN", "ReferringPhysicianName"], <add> "0092" : ["ST", "ReferringPhysicianAddress"], <add> "0094" : ["SH", "ReferringPhysicianTelephoneNumbers"], <add> "0096" : ["SQ", "ReferringPhysicianIdentificationSequence"], <add> "0100" : ["SH", "CodeValue"], <add> "0102" : ["SH", "CodingSchemeDesignator"], <add> "0103" : ["SH", "CodingSchemeVersion"], <add> "0104" : ["LO", "CodeMeaning"], <add> "0105" : ["CS", "MappingResource"], <add> "0106" : ["DT", "ContextGroupVersion"], <add> "0107" : ["DT", "ContextGroupLocalVersion"], <add> "010B" : ["CS", "ContextGroupExtensionFlag"], <add> "010C" : ["UI", "CodingSchemeUID"], <add> "010D" : ["UI", "ContextGroupExtensionCreatorUID"], <add> "010F" : ["CS", "ContextIdentifier"], <add> "0110" : ["SQ", "CodingSchemeIdentificationSequence"], <add> "0112" : ["LO", "CodingSchemeRegistry"], <add> "0114" : ["ST", "CodingSchemeExternalID"], <add> "0115" : ["ST", "CodingSchemeName"], <add> "0116" : ["ST", "CodingSchemeResponsibleOrganization"], <add> "0117" : ["UI", "ContextUID"], <add> "0201" : ["SH", "TimezoneOffsetFromUTC"], <add> "1000" : ["AE", "NetworkID"], <add> "1010" : ["SH", "StationName"], <add> "1030" : ["LO", "StudyDescription"], <add> "1032" : ["SQ", "ProcedureCodeSequence"], <add> "103E" : ["LO", "SeriesDescription"], <add> "103F" : ["SQ", "SeriesDescriptionCodeSequence"], <add> "1040" : ["LO", "InstitutionalDepartmentName"], <add> "1048" : ["PN", "PhysiciansOfRecord"], <add> "1049" : ["SQ", "PhysiciansOfRecordIdentificationSequence"], <add> "1050" : ["PN", "PerformingPhysicianName"], <add> "1052" : ["SQ", "PerformingPhysicianIdentificationSequence"], <add> "1060" : ["PN", "NameOfPhysiciansReadingStudy"], <add> "1062" : ["SQ", "PhysiciansReadingStudyIdentificationSequence"], <add> "1070" : ["PN", "OperatorsName"], <add> "1072" : ["SQ", "OperatorIdentificationSequence"], <add> "1080" : ["LO", "AdmittingDiagnosesDescription"], <add> "1084" : ["SQ", "AdmittingDiagnosesCodeSequence"], <add> "1090" : ["LO", "ManufacturerModelName"], <add> "1100" : ["SQ", "ReferencedResultsSequence"], <add> "1110" : ["SQ", "ReferencedStudySequence"], <add> "1111" : ["SQ", "ReferencedPerformedProcedureStepSequence"], <add> "1115" : ["SQ", "ReferencedSeriesSequence"], <add> "1120" : ["SQ", "ReferencedPatientSequence"], <add> "1125" : ["SQ", "ReferencedVisitSequence"], <add> "1130" : ["SQ", "ReferencedOverlaySequence"], <add> "1134" : ["SQ", "ReferencedStereometricInstanceSequence"], <add> "113A" : ["SQ", "ReferencedWaveformSequence"], <add> "1140" : ["SQ", "ReferencedImageSequence"], <add> "1145" : ["SQ", "ReferencedCurveSequence"], <add> "114A" : ["SQ", "ReferencedInstanceSequence"], <add> "114B" : ["SQ", "ReferencedRealWorldValueMappingInstanceSequence"], <add> "1150" : ["UI", "ReferencedSOPClassUID"], <add> "1155" : ["UI", "ReferencedSOPInstanceUID"], <add> "115A" : ["UI", "SOPClassesSupported"], <add> "1160" : ["IS", "ReferencedFrameNumber"], <add> "1161" : ["UL", "SimpleFrameList"], <add> "1162" : ["UL", "CalculatedFrameList"], <add> "1163" : ["FD", "TimeRange"], <add> "1164" : ["SQ", "FrameExtractionSequence"], <add> "1167" : ["UI", "MultiFrameSourceSOPInstanceUID"], <add> "1195" : ["UI", "TransactionUID"], <add> "1197" : ["US", "FailureReason"], <add> "1198" : ["SQ", "FailedSOPSequence"], <add> "1199" : ["SQ", "ReferencedSOPSequence"], <add> "1200" : ["SQ", "StudiesContainingOtherReferencedInstancesSequence"], <add> "1250" : ["SQ", "RelatedSeriesSequence"], <add> "2110" : ["CS", "LossyImageCompressionRetired"], <add> "2111" : ["ST", "DerivationDescription"], <add> "2112" : ["SQ", "SourceImageSequence"], <add> "2120" : ["SH", "StageName"], <add> "2122" : ["IS", "StageNumber"], <add> "2124" : ["IS", "NumberOfStages"], <add> "2127" : ["SH", "ViewName"], <add> "2128" : ["IS", "ViewNumber"], <add> "2129" : ["IS", "NumberOfEventTimers"], <add> "212A" : ["IS", "NumberOfViewsInStage"], <add> "2130" : ["DS", "EventElapsedTimes"], <add> "2132" : ["LO", "EventTimerNames"], <add> "2133" : ["SQ", "EventTimerSequence"], <add> "2134" : ["FD", "EventTimeOffset"], <add> "2135" : ["SQ", "EventCodeSequence"], <add> "2142" : ["IS", "StartTrim"], <add> "2143" : ["IS", "StopTrim"], <add> "2144" : ["IS", "RecommendedDisplayFrameRate"], <add> "2200" : ["CS", "TransducerPosition"], <add> "2204" : ["CS", "TransducerOrientation"], <add> "2208" : ["CS", "AnatomicStructure"], <add> "2218" : ["SQ", "AnatomicRegionSequence"], <add> "2220" : ["SQ", "AnatomicRegionModifierSequence"], <add> "2228" : ["SQ", "PrimaryAnatomicStructureSequence"], <add> "2229" : ["SQ", "AnatomicStructureSpaceOrRegionSequence"], <add> "2230" : ["SQ", "PrimaryAnatomicStructureModifierSequence"], <add> "2240" : ["SQ", "TransducerPositionSequence"], <add> "2242" : ["SQ", "TransducerPositionModifierSequence"], <add> "2244" : ["SQ", "TransducerOrientationSequence"], <add> "2246" : ["SQ", "TransducerOrientationModifierSequence"], <add> "2251" : ["SQ", "AnatomicStructureSpaceOrRegionCodeSequenceTrial"], <add> "2253" : ["SQ", "AnatomicPortalOfEntranceCodeSequenceTrial"], <add> "2255" : ["SQ", "AnatomicApproachDirectionCodeSequenceTrial"], <add> "2256" : ["ST", "AnatomicPerspectiveDescriptionTrial"], <add> "2257" : ["SQ", "AnatomicPerspectiveCodeSequenceTrial"], <add> "2258" : ["ST", "AnatomicLocationOfExaminingInstrumentDescriptionTrial"], <add> "2259" : ["SQ", "AnatomicLocationOfExaminingInstrumentCodeSequenceTrial"], <add> "225A" : ["SQ", "AnatomicStructureSpaceOrRegionModifierCodeSequenceTrial"], <add> "225C" : ["SQ", "OnAxisBackgroundAnatomicStructureCodeSequenceTrial"], <add> "3001" : ["SQ", "AlternateRepresentationSequence"], <add> "3010" : ["UI", "IrradiationEventUID"], <add> "4000" : ["LT", "IdentifyingComments"], <add> "9007" : ["CS", "FrameType"], <add> "9092" : ["SQ", "ReferencedImageEvidenceSequence"], <add> "9121" : ["SQ", "ReferencedRawDataSequence"], <add> "9123" : ["UI", "CreatorVersionUID"], <add> "9124" : ["SQ", "DerivationImageSequence"], <add> "9154" : ["SQ", "SourceImageEvidenceSequence"], <add> "9205" : ["CS", "PixelPresentation"], <add> "9206" : ["CS", "VolumetricProperties"], <add> "9207" : ["CS", "VolumeBasedCalculationTechnique"], <add> "9208" : ["CS", "ComplexImageComponent"], <add> "9209" : ["CS", "AcquisitionContrast"], <add> "9215" : ["SQ", "DerivationCodeSequence"], <add> "9237" : ["SQ", "ReferencedPresentationStateSequence"], <add> "9410" : ["SQ", "ReferencedOtherPlaneSequence"], <add> "9458" : ["SQ", "FrameDisplaySequence"], <add> "9459" : ["FL", "RecommendedDisplayFrameRateInFloat"], <add> "9460" : ["CS", "SkipFrameRangeFlag"] <add> }, <add> "0010" : { <add> "0010" : ["PN", "PatientName"], <add> "0020" : ["LO", "PatientID"], <add> "0021" : ["LO", "IssuerOfPatientID"], <add> "0022" : ["CS", "TypeOfPatientID"], <add> "0024" : ["SQ", "IssuerOfPatientIDQualifiersSequence"], <add> "0030" : ["DA", "PatientBirthDate"], <add> "0032" : ["TM", "PatientBirthTime"], <add> "0040" : ["CS", "PatientSex"], <add> "0050" : ["SQ", "PatientInsurancePlanCodeSequence"], <add> "0101" : ["SQ", "PatientPrimaryLanguageCodeSequence"], <add> "0102" : ["SQ", "PatientPrimaryLanguageModifierCodeSequence"], <add> "1000" : ["LO", "OtherPatientIDs"], <add> "1001" : ["PN", "OtherPatientNames"], <add> "1002" : ["SQ", "OtherPatientIDsSequence"], <add> "1005" : ["PN", "PatientBirthName"], <add> "1010" : ["AS", "PatientAge"], <add> "1020" : ["DS", "PatientSize"], <add> "1021" : ["SQ", "PatientSizeCodeSequence"], <add> "1030" : ["DS", "PatientWeight"], <add> "1040" : ["LO", "PatientAddress"], <add> "1050" : ["LO", "InsurancePlanIdentification"], <add> "1060" : ["PN", "PatientMotherBirthName"], <add> "1080" : ["LO", "MilitaryRank"], <add> "1081" : ["LO", "BranchOfService"], <add> "1090" : ["LO", "MedicalRecordLocator"], <add> "2000" : ["LO", "MedicalAlerts"], <add> "2110" : ["LO", "Allergies"], <add> "2150" : ["LO", "CountryOfResidence"], <add> "2152" : ["LO", "RegionOfResidence"], <add> "2154" : ["SH", "PatientTelephoneNumbers"], <add> "2160" : ["SH", "EthnicGroup"], <add> "2180" : ["SH", "Occupation"], <add> "21A0" : ["CS", "SmokingStatus"], <add> "21B0" : ["LT", "AdditionalPatientHistory"], <add> "21C0" : ["US", "PregnancyStatus"], <add> "21D0" : ["DA", "LastMenstrualDate"], <add> "21F0" : ["LO", "PatientReligiousPreference"], <add> "2201" : ["LO", "PatientSpeciesDescription"], <add> "2202" : ["SQ", "PatientSpeciesCodeSequence"], <add> "2203" : ["CS", "PatientSexNeutered"], <add> "2210" : ["CS", "AnatomicalOrientationType"], <add> "2292" : ["LO", "PatientBreedDescription"], <add> "2293" : ["SQ", "PatientBreedCodeSequence"], <add> "2294" : ["SQ", "BreedRegistrationSequence"], <add> "2295" : ["LO", "BreedRegistrationNumber"], <add> "2296" : ["SQ", "BreedRegistryCodeSequence"], <add> "2297" : ["PN", "ResponsiblePerson"], <add> "2298" : ["CS", "ResponsiblePersonRole"], <add> "2299" : ["LO", "ResponsibleOrganization"], <add> "4000" : ["LT", "PatientComments"], <add> "9431" : ["FL", "ExaminedBodyThickness"] <add> }, <add> "0012" : { <add> "0010" : ["LO", "ClinicalTrialSponsorName"], <add> "0020" : ["LO", "ClinicalTrialProtocolID"], <add> "0021" : ["LO", "ClinicalTrialProtocolName"], <add> "0030" : ["LO", "ClinicalTrialSiteID"], <add> "0031" : ["LO", "ClinicalTrialSiteName"], <add> "0040" : ["LO", "ClinicalTrialSubjectID"], <add> "0042" : ["LO", "ClinicalTrialSubjectReadingID"], <add> "0050" : ["LO", "ClinicalTrialTimePointID"], <add> "0051" : ["ST", "ClinicalTrialTimePointDescription"], <add> "0060" : ["LO", "ClinicalTrialCoordinatingCenterName"], <add> "0062" : ["CS", "PatientIdentityRemoved"], <add> "0063" : ["LO", "DeidentificationMethod"], <add> "0064" : ["SQ", "DeidentificationMethodCodeSequence"], <add> "0071" : ["LO", "ClinicalTrialSeriesID"], <add> "0072" : ["LO", "ClinicalTrialSeriesDescription"], <add> "0081" : ["LO", "ClinicalTrialProtocolEthicsCommitteeName"], <add> "0082" : ["LO", "ClinicalTrialProtocolEthicsCommitteeApprovalNumber"], <add> "0083" : ["SQ", "ConsentForClinicalTrialUseSequence"], <add> "0084" : ["CS", "DistributionType"], <add> "0085" : ["CS", "ConsentForDistributionFlag"] <add> }, <add> "0014" : { <add> "0023" : ["ST", "CADFileFormat"], <add> "0024" : ["ST", "ComponentReferenceSystem"], <add> "0025" : ["ST", "ComponentManufacturingProcedure"], <add> "0028" : ["ST", "ComponentManufacturer"], <add> "0030" : ["DS", "MaterialThickness"], <add> "0032" : ["DS", "MaterialPipeDiameter"], <add> "0034" : ["DS", "MaterialIsolationDiameter"], <add> "0042" : ["ST", "MaterialGrade"], <add> "0044" : ["ST", "MaterialPropertiesFileID"], <add> "0045" : ["ST", "MaterialPropertiesFileFormat"], <add> "0046" : ["LT", "MaterialNotes"], <add> "0050" : ["CS", "ComponentShape"], <add> "0052" : ["CS", "CurvatureType"], <add> "0054" : ["DS", "OuterDiameter"], <add> "0056" : ["DS", "InnerDiameter"], <add> "1010" : ["ST", "ActualEnvironmentalConditions"], <add> "1020" : ["DA", "ExpiryDate"], <add> "1040" : ["ST", "EnvironmentalConditions"], <add> "2002" : ["SQ", "EvaluatorSequence"], <add> "2004" : ["IS", "EvaluatorNumber"], <add> "2006" : ["PN", "EvaluatorName"], <add> "2008" : ["IS", "EvaluationAttempt"], <add> "2012" : ["SQ", "IndicationSequence"], <add> "2014" : ["IS", "IndicationNumber "], <add> "2016" : ["SH", "IndicationLabel"], <add> "2018" : ["ST", "IndicationDescription"], <add> "201A" : ["CS", "IndicationType"], <add> "201C" : ["CS", "IndicationDisposition"], <add> "201E" : ["SQ", "IndicationROISequence"], <add> "2030" : ["SQ", "IndicationPhysicalPropertySequence"], <add> "2032" : ["SH", "PropertyLabel"], <add> "2202" : ["IS", "CoordinateSystemNumberOfAxes "], <add> "2204" : ["SQ", "CoordinateSystemAxesSequence"], <add> "2206" : ["ST", "CoordinateSystemAxisDescription"], <add> "2208" : ["CS", "CoordinateSystemDataSetMapping"], <add> "220A" : ["IS", "CoordinateSystemAxisNumber"], <add> "220C" : ["CS", "CoordinateSystemAxisType"], <add> "220E" : ["CS", "CoordinateSystemAxisUnits"], <add> "2210" : ["OB", "CoordinateSystemAxisValues"], <add> "2220" : ["SQ", "CoordinateSystemTransformSequence"], <add> "2222" : ["ST", "TransformDescription"], <add> "2224" : ["IS", "TransformNumberOfAxes"], <add> "2226" : ["IS", "TransformOrderOfAxes"], <add> "2228" : ["CS", "TransformedAxisUnits"], <add> "222A" : ["DS", "CoordinateSystemTransformRotationAndScaleMatrix"], <add> "222C" : ["DS", "CoordinateSystemTransformTranslationMatrix"], <add> "3011" : ["DS", "InternalDetectorFrameTime"], <add> "3012" : ["DS", "NumberOfFramesIntegrated"], <add> "3020" : ["SQ", "DetectorTemperatureSequence"], <add> "3022" : ["DS", "SensorName"], <add> "3024" : ["DS", "HorizontalOffsetOfSensor"], <add> "3026" : ["DS", "VerticalOffsetOfSensor"], <add> "3028" : ["DS", "SensorTemperature"], <add> "3040" : ["SQ", "DarkCurrentSequence"], <add> "3050" : ["OB", "DarkCurrentCounts"], <add> "3060" : ["SQ", "GainCorrectionReferenceSequence"], <add> "3070" : ["OB", "AirCounts"], <add> "3071" : ["DS", "KVUsedInGainCalibration"], <add> "3072" : ["DS", "MAUsedInGainCalibration"], <add> "3073" : ["DS", "NumberOfFramesUsedForIntegration"], <add> "3074" : ["LO", "FilterMaterialUsedInGainCalibration"], <add> "3075" : ["DS", "FilterThicknessUsedInGainCalibration"], <add> "3076" : ["DA", "DateOfGainCalibration"], <add> "3077" : ["TM", "TimeOfGainCalibration"], <add> "3080" : ["OB", "BadPixelImage"], <add> "3099" : ["LT", "CalibrationNotes"], <add> "4002" : ["SQ", "PulserEquipmentSequence"], <add> "4004" : ["CS", "PulserType"], <add> "4006" : ["LT", "PulserNotes"], <add> "4008" : ["SQ", "ReceiverEquipmentSequence"], <add> "400A" : ["CS", "AmplifierType"], <add> "400C" : ["LT", "ReceiverNotes"], <add> "400E" : ["SQ", "PreAmplifierEquipmentSequence"], <add> "400F" : ["LT", "PreAmplifierNotes"], <add> "4010" : ["SQ", "TransmitTransducerSequence"], <add> "4011" : ["SQ", "ReceiveTransducerSequence"], <add> "4012" : ["US", "NumberOfElements"], <add> "4013" : ["CS", "ElementShape"], <add> "4014" : ["DS", "ElementDimensionA"], <add> "4015" : ["DS", "ElementDimensionB"], <add> "4016" : ["DS", "ElementPitch"], <add> "4017" : ["DS", "MeasuredBeamDimensionA"], <add> "4018" : ["DS", "MeasuredBeamDimensionB"], <add> "4019" : ["DS", "LocationOfMeasuredBeamDiameter"], <add> "401A" : ["DS", "NominalFrequency"], <add> "401B" : ["DS", "MeasuredCenterFrequency"], <add> "401C" : ["DS", "MeasuredBandwidth"], <add> "4020" : ["SQ", "PulserSettingsSequence"], <add> "4022" : ["DS", "PulseWidth"], <add> "4024" : ["DS", "ExcitationFrequency"], <add> "4026" : ["CS", "ModulationType"], <add> "4028" : ["DS", "Damping"], <add> "4030" : ["SQ", "ReceiverSettingsSequence"], <add> "4031" : ["DS", "AcquiredSoundpathLength"], <add> "4032" : ["CS", "AcquisitionCompressionType"], <add> "4033" : ["IS", "AcquisitionSampleSize"], <add> "4034" : ["DS", "RectifierSmoothing"], <add> "4035" : ["SQ", "DACSequence"], <add> "4036" : ["CS", "DACType"], <add> "4038" : ["DS", "DACGainPoints"], <add> "403A" : ["DS", "DACTimePoints"], <add> "403C" : ["DS", "DACAmplitude"], <add> "4040" : ["SQ", "PreAmplifierSettingsSequence"], <add> "4050" : ["SQ", "TransmitTransducerSettingsSequence"], <add> "4051" : ["SQ", "ReceiveTransducerSettingsSequence"], <add> "4052" : ["DS", "IncidentAngle"], <add> "4054" : ["ST", "CouplingTechnique"], <add> "4056" : ["ST", "CouplingMedium"], <add> "4057" : ["DS", "CouplingVelocity"], <add> "4058" : ["DS", "CrystalCenterLocationX"], <add> "4059" : ["DS", "CrystalCenterLocationZ"], <add> "405A" : ["DS", "SoundPathLength"], <add> "405C" : ["ST", "DelayLawIdentifier"], <add> "4060" : ["SQ", "GateSettingsSequence"], <add> "4062" : ["DS", "GateThreshold"], <add> "4064" : ["DS", "VelocityOfSound"], <add> "4070" : ["SQ", "CalibrationSettingsSequence"], <add> "4072" : ["ST", "CalibrationProcedure"], <add> "4074" : ["SH", "ProcedureVersion"], <add> "4076" : ["DA", "ProcedureCreationDate"], <add> "4078" : ["DA", "ProcedureExpirationDate"], <add> "407A" : ["DA", "ProcedureLastModifiedDate"], <add> "407C" : ["TM", "CalibrationTime"], <add> "407E" : ["DA", "CalibrationDate"], <add> "5002" : ["IS", "LINACEnergy"], <add> "5004" : ["IS", "LINACOutput"] <add> }, <add> "0018" : { <add> "0010" : ["LO", "ContrastBolusAgent"], <add> "0012" : ["SQ", "ContrastBolusAgentSequence"], <add> "0014" : ["SQ", "ContrastBolusAdministrationRouteSequence"], <add> "0015" : ["CS", "BodyPartExamined"], <add> "0020" : ["CS", "ScanningSequence"], <add> "0021" : ["CS", "SequenceVariant"], <add> "0022" : ["CS", "ScanOptions"], <add> "0023" : ["CS", "MRAcquisitionType"], <add> "0024" : ["SH", "SequenceName"], <add> "0025" : ["CS", "AngioFlag"], <add> "0026" : ["SQ", "InterventionDrugInformationSequence"], <add> "0027" : ["TM", "InterventionDrugStopTime"], <add> "0028" : ["DS", "InterventionDrugDose"], <add> "0029" : ["SQ", "InterventionDrugCodeSequence"], <add> "002A" : ["SQ", "AdditionalDrugSequence"], <add> "0030" : ["LO", "Radionuclide"], <add> "0031" : ["LO", "Radiopharmaceutical"], <add> "0032" : ["DS", "EnergyWindowCenterline"], <add> "0033" : ["DS", "EnergyWindowTotalWidth"], <add> "0034" : ["LO", "InterventionDrugName"], <add> "0035" : ["TM", "InterventionDrugStartTime"], <add> "0036" : ["SQ", "InterventionSequence"], <add> "0037" : ["CS", "TherapyType"], <add> "0038" : ["CS", "InterventionStatus"], <add> "0039" : ["CS", "TherapyDescription"], <add> "003A" : ["ST", "InterventionDescription"], <add> "0040" : ["IS", "CineRate"], <add> "0042" : ["CS", "InitialCineRunState"], <add> "0050" : ["DS", "SliceThickness"], <add> "0060" : ["DS", "KVP"], <add> "0070" : ["IS", "CountsAccumulated"], <add> "0071" : ["CS", "AcquisitionTerminationCondition"], <add> "0072" : ["DS", "EffectiveDuration"], <add> "0073" : ["CS", "AcquisitionStartCondition"], <add> "0074" : ["IS", "AcquisitionStartConditionData"], <add> "0075" : ["IS", "AcquisitionTerminationConditionData"], <add> "0080" : ["DS", "RepetitionTime"], <add> "0081" : ["DS", "EchoTime"], <add> "0082" : ["DS", "InversionTime"], <add> "0083" : ["DS", "NumberOfAverages"], <add> "0084" : ["DS", "ImagingFrequency"], <add> "0085" : ["SH", "ImagedNucleus"], <add> "0086" : ["IS", "EchoNumbers"], <add> "0087" : ["DS", "MagneticFieldStrength"], <add> "0088" : ["DS", "SpacingBetweenSlices"], <add> "0089" : ["IS", "NumberOfPhaseEncodingSteps"], <add> "0090" : ["DS", "DataCollectionDiameter"], <add> "0091" : ["IS", "EchoTrainLength"], <add> "0093" : ["DS", "PercentSampling"], <add> "0094" : ["DS", "PercentPhaseFieldOfView"], <add> "0095" : ["DS", "PixelBandwidth"], <add> "1000" : ["LO", "DeviceSerialNumber"], <add> "1002" : ["UI", "DeviceUID"], <add> "1003" : ["LO", "DeviceID"], <add> "1004" : ["LO", "PlateID"], <add> "1005" : ["LO", "GeneratorID"], <add> "1006" : ["LO", "GridID"], <add> "1007" : ["LO", "CassetteID"], <add> "1008" : ["LO", "GantryID"], <add> "1010" : ["LO", "SecondaryCaptureDeviceID"], <add> "1011" : ["LO", "HardcopyCreationDeviceID"], <add> "1012" : ["DA", "DateOfSecondaryCapture"], <add> "1014" : ["TM", "TimeOfSecondaryCapture"], <add> "1016" : ["LO", "SecondaryCaptureDeviceManufacturer"], <add> "1017" : ["LO", "HardcopyDeviceManufacturer"], <add> "1018" : ["LO", "SecondaryCaptureDeviceManufacturerModelName"], <add> "1019" : ["LO", "SecondaryCaptureDeviceSoftwareVersions"], <add> "101A" : ["LO", "HardcopyDeviceSoftwareVersion"], <add> "101B" : ["LO", "HardcopyDeviceManufacturerModelName"], <add> "1020" : ["LO", "SoftwareVersions"], <add> "1022" : ["SH", "VideoImageFormatAcquired"], <add> "1023" : ["LO", "DigitalImageFormatAcquired"], <add> "1030" : ["LO", "ProtocolName"], <add> "1040" : ["LO", "ContrastBolusRoute"], <add> "1041" : ["DS", "ContrastBolusVolume"], <add> "1042" : ["TM", "ContrastBolusStartTime"], <add> "1043" : ["TM", "ContrastBolusStopTime"], <add> "1044" : ["DS", "ContrastBolusTotalDose"], <add> "1045" : ["IS", "SyringeCounts"], <add> "1046" : ["DS", "ContrastFlowRate"], <add> "1047" : ["DS", "ContrastFlowDuration"], <add> "1048" : ["CS", "ContrastBolusIngredient"], <add> "1049" : ["DS", "ContrastBolusIngredientConcentration"], <add> "1050" : ["DS", "SpatialResolution"], <add> "1060" : ["DS", "TriggerTime"], <add> "1061" : ["LO", "TriggerSourceOrType"], <add> "1062" : ["IS", "NominalInterval"], <add> "1063" : ["DS", "FrameTime"], <add> "1064" : ["LO", "CardiacFramingType"], <add> "1065" : ["DS", "FrameTimeVector"], <add> "1066" : ["DS", "FrameDelay"], <add> "1067" : ["DS", "ImageTriggerDelay"], <add> "1068" : ["DS", "MultiplexGroupTimeOffset"], <add> "1069" : ["DS", "TriggerTimeOffset"], <add> "106A" : ["CS", "SynchronizationTrigger"], <add> "106C" : ["US", "SynchronizationChannel"], <add> "106E" : ["UL", "TriggerSamplePosition"], <add> "1070" : ["LO", "RadiopharmaceuticalRoute"], <add> "1071" : ["DS", "RadiopharmaceuticalVolume"], <add> "1072" : ["TM", "RadiopharmaceuticalStartTime"], <add> "1073" : ["TM", "RadiopharmaceuticalStopTime"], <add> "1074" : ["DS", "RadionuclideTotalDose"], <add> "1075" : ["DS", "RadionuclideHalfLife"], <add> "1076" : ["DS", "RadionuclidePositronFraction"], <add> "1077" : ["DS", "RadiopharmaceuticalSpecificActivity"], <add> "1078" : ["DT", "RadiopharmaceuticalStartDateTime"], <add> "1079" : ["DT", "RadiopharmaceuticalStopDateTime"], <add> "1080" : ["CS", "BeatRejectionFlag"], <add> "1081" : ["IS", "LowRRValue"], <add> "1082" : ["IS", "HighRRValue"], <add> "1083" : ["IS", "IntervalsAcquired"], <add> "1084" : ["IS", "IntervalsRejected"], <add> "1085" : ["LO", "PVCRejection"], <add> "1086" : ["IS", "SkipBeats"], <add> "1088" : ["IS", "HeartRate"], <add> "1090" : ["IS", "CardiacNumberOfImages"], <add> "1094" : ["IS", "TriggerWindow"], <add> "1100" : ["DS", "ReconstructionDiameter"], <add> "1110" : ["DS", "DistanceSourceToDetector"], <add> "1111" : ["DS", "DistanceSourceToPatient"], <add> "1114" : ["DS", "EstimatedRadiographicMagnificationFactor"], <add> "1120" : ["DS", "GantryDetectorTilt"], <add> "1121" : ["DS", "GantryDetectorSlew"], <add> "1130" : ["DS", "TableHeight"], <add> "1131" : ["DS", "TableTraverse"], <add> "1134" : ["CS", "TableMotion"], <add> "1135" : ["DS", "TableVerticalIncrement"], <add> "1136" : ["DS", "TableLateralIncrement"], <add> "1137" : ["DS", "TableLongitudinalIncrement"], <add> "1138" : ["DS", "TableAngle"], <add> "113A" : ["CS", "TableType"], <add> "1140" : ["CS", "RotationDirection"], <add> "1141" : ["DS", "AngularPosition"], <add> "1142" : ["DS", "RadialPosition"], <add> "1143" : ["DS", "ScanArc"], <add> "1144" : ["DS", "AngularStep"], <add> "1145" : ["DS", "CenterOfRotationOffset"], <add> "1146" : ["DS", "RotationOffset"], <add> "1147" : ["CS", "FieldOfViewShape"], <add> "1149" : ["IS", "FieldOfViewDimensions"], <add> "1150" : ["IS", "ExposureTime"], <add> "1151" : ["IS", "XRayTubeCurrent"], <add> "1152" : ["IS", "Exposure"], <add> "1153" : ["IS", "ExposureInuAs"], <add> "1154" : ["DS", "AveragePulseWidth"], <add> "1155" : ["CS", "RadiationSetting"], <add> "1156" : ["CS", "RectificationType"], <add> "115A" : ["CS", "RadiationMode"], <add> "115E" : ["DS", "ImageAndFluoroscopyAreaDoseProduct"], <add> "1160" : ["SH", "FilterType"], <add> "1161" : ["LO", "TypeOfFilters"], <add> "1162" : ["DS", "IntensifierSize"], <add> "1164" : ["DS", "ImagerPixelSpacing"], <add> "1166" : ["CS", "Grid"], <add> "1170" : ["IS", "GeneratorPower"], <add> "1180" : ["SH", "CollimatorGridName"], <add> "1181" : ["CS", "CollimatorType"], <add> "1182" : ["IS", "FocalDistance"], <add> "1183" : ["DS", "XFocusCenter"], <add> "1184" : ["DS", "YFocusCenter"], <add> "1190" : ["DS", "FocalSpots"], <add> "1191" : ["CS", "AnodeTargetMaterial"], <add> "11A0" : ["DS", "BodyPartThickness"], <add> "11A2" : ["DS", "CompressionForce"], <add> "1200" : ["DA", "DateOfLastCalibration"], <add> "1201" : ["TM", "TimeOfLastCalibration"], <add> "1210" : ["SH", "ConvolutionKernel"], <add> "1240" : ["IS", "UpperLowerPixelValues"], <add> "1242" : ["IS", "ActualFrameDuration"], <add> "1243" : ["IS", "CountRate"], <add> "1244" : ["US", "PreferredPlaybackSequencing"], <add> "1250" : ["SH", "ReceiveCoilName"], <add> "1251" : ["SH", "TransmitCoilName"], <add> "1260" : ["SH", "PlateType"], <add> "1261" : ["LO", "PhosphorType"], <add> "1300" : ["DS", "ScanVelocity"], <add> "1301" : ["CS", "WholeBodyTechnique"], <add> "1302" : ["IS", "ScanLength"], <add> "1310" : ["US", "AcquisitionMatrix"], <add> "1312" : ["CS", "InPlanePhaseEncodingDirection"], <add> "1314" : ["DS", "FlipAngle"], <add> "1315" : ["CS", "VariableFlipAngleFlag"], <add> "1316" : ["DS", "SAR"], <add> "1318" : ["DS", "dBdt"], <add> "1400" : ["LO", "AcquisitionDeviceProcessingDescription"], <add> "1401" : ["LO", "AcquisitionDeviceProcessingCode"], <add> "1402" : ["CS", "CassetteOrientation"], <add> "1403" : ["CS", "CassetteSize"], <add> "1404" : ["US", "ExposuresOnPlate"], <add> "1405" : ["IS", "RelativeXRayExposure"], <add> "1411" : ["DS", "ExposureIndex"], <add> "1412" : ["DS", "TargetExposureIndex"], <add> "1413" : ["DS", "DeviationIndex"], <add> "1450" : ["DS", "ColumnAngulation"], <add> "1460" : ["DS", "TomoLayerHeight"], <add> "1470" : ["DS", "TomoAngle"], <add> "1480" : ["DS", "TomoTime"], <add> "1490" : ["CS", "TomoType"], <add> "1491" : ["CS", "TomoClass"], <add> "1495" : ["IS", "NumberOfTomosynthesisSourceImages"], <add> "1500" : ["CS", "PositionerMotion"], <add> "1508" : ["CS", "PositionerType"], <add> "1510" : ["DS", "PositionerPrimaryAngle"], <add> "1511" : ["DS", "PositionerSecondaryAngle"], <add> "1520" : ["DS", "PositionerPrimaryAngleIncrement"], <add> "1521" : ["DS", "PositionerSecondaryAngleIncrement"], <add> "1530" : ["DS", "DetectorPrimaryAngle"], <add> "1531" : ["DS", "DetectorSecondaryAngle"], <add> "1600" : ["CS", "ShutterShape"], <add> "1602" : ["IS", "ShutterLeftVerticalEdge"], <add> "1604" : ["IS", "ShutterRightVerticalEdge"], <add> "1606" : ["IS", "ShutterUpperHorizontalEdge"], <add> "1608" : ["IS", "ShutterLowerHorizontalEdge"], <add> "1610" : ["IS", "CenterOfCircularShutter"], <add> "1612" : ["IS", "RadiusOfCircularShutter"], <add> "1620" : ["IS", "VerticesOfThePolygonalShutter"], <add> "1622" : ["US", "ShutterPresentationValue"], <add> "1623" : ["US", "ShutterOverlayGroup"], <add> "1624" : ["US", "ShutterPresentationColorCIELabValue"], <add> "1700" : ["CS", "CollimatorShape"], <add> "1702" : ["IS", "CollimatorLeftVerticalEdge"], <add> "1704" : ["IS", "CollimatorRightVerticalEdge"], <add> "1706" : ["IS", "CollimatorUpperHorizontalEdge"], <add> "1708" : ["IS", "CollimatorLowerHorizontalEdge"], <add> "1710" : ["IS", "CenterOfCircularCollimator"], <add> "1712" : ["IS", "RadiusOfCircularCollimator"], <add> "1720" : ["IS", "VerticesOfThePolygonalCollimator"], <add> "1800" : ["CS", "AcquisitionTimeSynchronized"], <add> "1801" : ["SH", "TimeSource"], <add> "1802" : ["CS", "TimeDistributionProtocol"], <add> "1803" : ["LO", "NTPSourceAddress"], <add> "2001" : ["IS", "PageNumberVector"], <add> "2002" : ["SH", "FrameLabelVector"], <add> "2003" : ["DS", "FramePrimaryAngleVector"], <add> "2004" : ["DS", "FrameSecondaryAngleVector"], <add> "2005" : ["DS", "SliceLocationVector"], <add> "2006" : ["SH", "DisplayWindowLabelVector"], <add> "2010" : ["DS", "NominalScannedPixelSpacing"], <add> "2020" : ["CS", "DigitizingDeviceTransportDirection"], <add> "2030" : ["DS", "RotationOfScannedFilm"], <add> "3100" : ["CS", "IVUSAcquisition"], <add> "3101" : ["DS", "IVUSPullbackRate"], <add> "3102" : ["DS", "IVUSGatedRate"], <add> "3103" : ["IS", "IVUSPullbackStartFrameNumber"], <add> "3104" : ["IS", "IVUSPullbackStopFrameNumber"], <add> "3105" : ["IS", "LesionNumber"], <add> "4000" : ["LT", "AcquisitionComments"], <add> "5000" : ["SH", "OutputPower"], <add> "5010" : ["LO", "TransducerData"], <add> "5012" : ["DS", "FocusDepth"], <add> "5020" : ["LO", "ProcessingFunction"], <add> "5021" : ["LO", "PostprocessingFunction"], <add> "5022" : ["DS", "MechanicalIndex"], <add> "5024" : ["DS", "BoneThermalIndex"], <add> "5026" : ["DS", "CranialThermalIndex"], <add> "5027" : ["DS", "SoftTissueThermalIndex"], <add> "5028" : ["DS", "SoftTissueFocusThermalIndex"], <add> "5029" : ["DS", "SoftTissueSurfaceThermalIndex"], <add> "5030" : ["DS", "DynamicRange"], <add> "5040" : ["DS", "TotalGain"], <add> "5050" : ["IS", "DepthOfScanField"], <add> "5100" : ["CS", "PatientPosition"], <add> "5101" : ["CS", "ViewPosition"], <add> "5104" : ["SQ", "ProjectionEponymousNameCodeSequence"], <add> "5210" : ["DS", "ImageTransformationMatrix"], <add> "5212" : ["DS", "ImageTranslationVector"], <add> "6000" : ["DS", "Sensitivity"], <add> "6011" : ["SQ", "SequenceOfUltrasoundRegions"], <add> "6012" : ["US", "RegionSpatialFormat"], <add> "6014" : ["US", "RegionDataType"], <add> "6016" : ["UL", "RegionFlags"], <add> "6018" : ["UL", "RegionLocationMinX0"], <add> "601A" : ["UL", "RegionLocationMinY0"], <add> "601C" : ["UL", "RegionLocationMaxX1"], <add> "601E" : ["UL", "RegionLocationMaxY1"], <add> "6020" : ["SL", "ReferencePixelX0"], <add> "6022" : ["SL", "ReferencePixelY0"], <add> "6024" : ["US", "PhysicalUnitsXDirection"], <add> "6026" : ["US", "PhysicalUnitsYDirection"], <add> "6028" : ["FD", "ReferencePixelPhysicalValueX"], <add> "602A" : ["FD", "ReferencePixelPhysicalValueY"], <add> "602C" : ["FD", "PhysicalDeltaX"], <add> "602E" : ["FD", "PhysicalDeltaY"], <add> "6030" : ["UL", "TransducerFrequency"], <add> "6031" : ["CS", "TransducerType"], <add> "6032" : ["UL", "PulseRepetitionFrequency"], <add> "6034" : ["FD", "DopplerCorrectionAngle"], <add> "6036" : ["FD", "SteeringAngle"], <add> "6038" : ["UL", "DopplerSampleVolumeXPositionRetired"], <add> "6039" : ["SL", "DopplerSampleVolumeXPosition"], <add> "603A" : ["UL", "DopplerSampleVolumeYPositionRetired"], <add> "603B" : ["SL", "DopplerSampleVolumeYPosition"], <add> "603C" : ["UL", "TMLinePositionX0Retired"], <add> "603D" : ["SL", "TMLinePositionX0"], <add> "603E" : ["UL", "TMLinePositionY0Retired"], <add> "603F" : ["SL", "TMLinePositionY0"], <add> "6040" : ["UL", "TMLinePositionX1Retired"], <add> "6041" : ["SL", "TMLinePositionX1"], <add> "6042" : ["UL", "TMLinePositionY1Retired"], <add> "6043" : ["SL", "TMLinePositionY1"], <add> "6044" : ["US", "PixelComponentOrganization"], <add> "6046" : ["UL", "PixelComponentMask"], <add> "6048" : ["UL", "PixelComponentRangeStart"], <add> "604A" : ["UL", "PixelComponentRangeStop"], <add> "604C" : ["US", "PixelComponentPhysicalUnits"], <add> "604E" : ["US", "PixelComponentDataType"], <add> "6050" : ["UL", "NumberOfTableBreakPoints"], <add> "6052" : ["UL", "TableOfXBreakPoints"], <add> "6054" : ["FD", "TableOfYBreakPoints"], <add> "6056" : ["UL", "NumberOfTableEntries"], <add> "6058" : ["UL", "TableOfPixelValues"], <add> "605A" : ["FL", "TableOfParameterValues"], <add> "6060" : ["FL", "RWaveTimeVector"], <add> "7000" : ["CS", "DetectorConditionsNominalFlag"], <add> "7001" : ["DS", "DetectorTemperature"], <add> "7004" : ["CS", "DetectorType"], <add> "7005" : ["CS", "DetectorConfiguration"], <add> "7006" : ["LT", "DetectorDescription"], <add> "7008" : ["LT", "DetectorMode"], <add> "700A" : ["SH", "DetectorID"], <add> "700C" : ["DA", "DateOfLastDetectorCalibration"], <add> "700E" : ["TM", "TimeOfLastDetectorCalibration"], <add> "7010" : ["IS", "ExposuresOnDetectorSinceLastCalibration"], <add> "7011" : ["IS", "ExposuresOnDetectorSinceManufactured"], <add> "7012" : ["DS", "DetectorTimeSinceLastExposure"], <add> "7014" : ["DS", "DetectorActiveTime"], <add> "7016" : ["DS", "DetectorActivationOffsetFromExposure"], <add> "701A" : ["DS", "DetectorBinning"], <add> "7020" : ["DS", "DetectorElementPhysicalSize"], <add> "7022" : ["DS", "DetectorElementSpacing"], <add> "7024" : ["CS", "DetectorActiveShape"], <add> "7026" : ["DS", "DetectorActiveDimensions"], <add> "7028" : ["DS", "DetectorActiveOrigin"], <add> "702A" : ["LO", "DetectorManufacturerName"], <add> "702B" : ["LO", "DetectorManufacturerModelName"], <add> "7030" : ["DS", "FieldOfViewOrigin"], <add> "7032" : ["DS", "FieldOfViewRotation"], <add> "7034" : ["CS", "FieldOfViewHorizontalFlip"], <add> "7036" : ["FL", "PixelDataAreaOriginRelativeToFOV"], <add> "7038" : ["FL", "PixelDataAreaRotationAngleRelativeToFOV"], <add> "7040" : ["LT", "GridAbsorbingMaterial"], <add> "7041" : ["LT", "GridSpacingMaterial"], <add> "7042" : ["DS", "GridThickness"], <add> "7044" : ["DS", "GridPitch"], <add> "7046" : ["IS", "GridAspectRatio"], <add> "7048" : ["DS", "GridPeriod"], <add> "704C" : ["DS", "GridFocalDistance"], <add> "7050" : ["CS", "FilterMaterial"], <add> "7052" : ["DS", "FilterThicknessMinimum"], <add> "7054" : ["DS", "FilterThicknessMaximum"], <add> "7056" : ["FL", "FilterBeamPathLengthMinimum"], <add> "7058" : ["FL", "FilterBeamPathLengthMaximum"], <add> "7060" : ["CS", "ExposureControlMode"], <add> "7062" : ["LT", "ExposureControlModeDescription"], <add> "7064" : ["CS", "ExposureStatus"], <add> "7065" : ["DS", "PhototimerSetting"], <add> "8150" : ["DS", "ExposureTimeInuS"], <add> "8151" : ["DS", "XRayTubeCurrentInuA"], <add> "9004" : ["CS", "ContentQualification"], <add> "9005" : ["SH", "PulseSequenceName"], <add> "9006" : ["SQ", "MRImagingModifierSequence"], <add> "9008" : ["CS", "EchoPulseSequence"], <add> "9009" : ["CS", "InversionRecovery"], <add> "9010" : ["CS", "FlowCompensation"], <add> "9011" : ["CS", "MultipleSpinEcho"], <add> "9012" : ["CS", "MultiPlanarExcitation"], <add> "9014" : ["CS", "PhaseContrast"], <add> "9015" : ["CS", "TimeOfFlightContrast"], <add> "9016" : ["CS", "Spoiling"], <add> "9017" : ["CS", "SteadyStatePulseSequence"], <add> "9018" : ["CS", "EchoPlanarPulseSequence"], <add> "9019" : ["FD", "TagAngleFirstAxis"], <add> "9020" : ["CS", "MagnetizationTransfer"], <add> "9021" : ["CS", "T2Preparation"], <add> "9022" : ["CS", "BloodSignalNulling"], <add> "9024" : ["CS", "SaturationRecovery"], <add> "9025" : ["CS", "SpectrallySelectedSuppression"], <add> "9026" : ["CS", "SpectrallySelectedExcitation"], <add> "9027" : ["CS", "SpatialPresaturation"], <add> "9028" : ["CS", "Tagging"], <add> "9029" : ["CS", "OversamplingPhase"], <add> "9030" : ["FD", "TagSpacingFirstDimension"], <add> "9032" : ["CS", "GeometryOfKSpaceTraversal"], <add> "9033" : ["CS", "SegmentedKSpaceTraversal"], <add> "9034" : ["CS", "RectilinearPhaseEncodeReordering"], <add> "9035" : ["FD", "TagThickness"], <add> "9036" : ["CS", "PartialFourierDirection"], <add> "9037" : ["CS", "CardiacSynchronizationTechnique"], <add> "9041" : ["LO", "ReceiveCoilManufacturerName"], <add> "9042" : ["SQ", "MRReceiveCoilSequence"], <add> "9043" : ["CS", "ReceiveCoilType"], <add> "9044" : ["CS", "QuadratureReceiveCoil"], <add> "9045" : ["SQ", "MultiCoilDefinitionSequence"], <add> "9046" : ["LO", "MultiCoilConfiguration"], <add> "9047" : ["SH", "MultiCoilElementName"], <add> "9048" : ["CS", "MultiCoilElementUsed"], <add> "9049" : ["SQ", "MRTransmitCoilSequence"], <add> "9050" : ["LO", "TransmitCoilManufacturerName"], <add> "9051" : ["CS", "TransmitCoilType"], <add> "9052" : ["FD", "SpectralWidth"], <add> "9053" : ["FD", "ChemicalShiftReference"], <add> "9054" : ["CS", "VolumeLocalizationTechnique"], <add> "9058" : ["US", "MRAcquisitionFrequencyEncodingSteps"], <add> "9059" : ["CS", "Decoupling"], <add> "9060" : ["CS", "DecoupledNucleus"], <add> "9061" : ["FD", "DecouplingFrequency"], <add> "9062" : ["CS", "DecouplingMethod"], <add> "9063" : ["FD", "DecouplingChemicalShiftReference"], <add> "9064" : ["CS", "KSpaceFiltering"], <add> "9065" : ["CS", "TimeDomainFiltering"], <add> "9066" : ["US", "NumberOfZeroFills"], <add> "9067" : ["CS", "BaselineCorrection"], <add> "9069" : ["FD", "ParallelReductionFactorInPlane"], <add> "9070" : ["FD", "CardiacRRIntervalSpecified"], <add> "9073" : ["FD", "AcquisitionDuration"], <add> "9074" : ["DT", "FrameAcquisitionDateTime"], <add> "9075" : ["CS", "DiffusionDirectionality"], <add> "9076" : ["SQ", "DiffusionGradientDirectionSequence"], <add> "9077" : ["CS", "ParallelAcquisition"], <add> "9078" : ["CS", "ParallelAcquisitionTechnique"], <add> "9079" : ["FD", "InversionTimes"], <add> "9080" : ["ST", "MetaboliteMapDescription"], <add> "9081" : ["CS", "PartialFourier"], <add> "9082" : ["FD", "EffectiveEchoTime"], <add> "9083" : ["SQ", "MetaboliteMapCodeSequence"], <add> "9084" : ["SQ", "ChemicalShiftSequence"], <add> "9085" : ["CS", "CardiacSignalSource"], <add> "9087" : ["FD", "DiffusionBValue"], <add> "9089" : ["FD", "DiffusionGradientOrientation"], <add> "9090" : ["FD", "VelocityEncodingDirection"], <add> "9091" : ["FD", "VelocityEncodingMinimumValue"], <add> "9092" : ["SQ", "VelocityEncodingAcquisitionSequence"], <add> "9093" : ["US", "NumberOfKSpaceTrajectories"], <add> "9094" : ["CS", "CoverageOfKSpace"], <add> "9095" : ["UL", "SpectroscopyAcquisitionPhaseRows"], <add> "9096" : ["FD", "ParallelReductionFactorInPlaneRetired"], <add> "9098" : ["FD", "TransmitterFrequency"], <add> "9100" : ["CS", "ResonantNucleus"], <add> "9101" : ["CS", "FrequencyCorrection"], <add> "9103" : ["SQ", "MRSpectroscopyFOVGeometrySequence"], <add> "9104" : ["FD", "SlabThickness"], <add> "9105" : ["FD", "SlabOrientation"], <add> "9106" : ["FD", "MidSlabPosition"], <add> "9107" : ["SQ", "MRSpatialSaturationSequence"], <add> "9112" : ["SQ", "MRTimingAndRelatedParametersSequence"], <add> "9114" : ["SQ", "MREchoSequence"], <add> "9115" : ["SQ", "MRModifierSequence"], <add> "9117" : ["SQ", "MRDiffusionSequence"], <add> "9118" : ["SQ", "CardiacSynchronizationSequence"], <add> "9119" : ["SQ", "MRAveragesSequence"], <add> "9125" : ["SQ", "MRFOVGeometrySequence"], <add> "9126" : ["SQ", "VolumeLocalizationSequence"], <add> "9127" : ["UL", "SpectroscopyAcquisitionDataColumns"], <add> "9147" : ["CS", "DiffusionAnisotropyType"], <add> "9151" : ["DT", "FrameReferenceDateTime"], <add> "9152" : ["SQ", "MRMetaboliteMapSequence"], <add> "9155" : ["FD", "ParallelReductionFactorOutOfPlane"], <add> "9159" : ["UL", "SpectroscopyAcquisitionOutOfPlanePhaseSteps"], <add> "9166" : ["CS", "BulkMotionStatus"], <add> "9168" : ["FD", "ParallelReductionFactorSecondInPlane"], <add> "9169" : ["CS", "CardiacBeatRejectionTechnique"], <add> "9170" : ["CS", "RespiratoryMotionCompensationTechnique"], <add> "9171" : ["CS", "RespiratorySignalSource"], <add> "9172" : ["CS", "BulkMotionCompensationTechnique"], <add> "9173" : ["CS", "BulkMotionSignalSource"], <add> "9174" : ["CS", "ApplicableSafetyStandardAgency"], <add> "9175" : ["LO", "ApplicableSafetyStandardDescription"], <add> "9176" : ["SQ", "OperatingModeSequence"], <add> "9177" : ["CS", "OperatingModeType"], <add> "9178" : ["CS", "OperatingMode"], <add> "9179" : ["CS", "SpecificAbsorptionRateDefinition"], <add> "9180" : ["CS", "GradientOutputType"], <add> "9181" : ["FD", "SpecificAbsorptionRateValue"], <add> "9182" : ["FD", "GradientOutput"], <add> "9183" : ["CS", "FlowCompensationDirection"], <add> "9184" : ["FD", "TaggingDelay"], <add> "9185" : ["ST", "RespiratoryMotionCompensationTechniqueDescription"], <add> "9186" : ["SH", "RespiratorySignalSourceID"], <add> "9195" : ["FD", "ChemicalShiftMinimumIntegrationLimitInHz"], <add> "9196" : ["FD", "ChemicalShiftMaximumIntegrationLimitInHz"], <add> "9197" : ["SQ", "MRVelocityEncodingSequence"], <add> "9198" : ["CS", "FirstOrderPhaseCorrection"], <add> "9199" : ["CS", "WaterReferencedPhaseCorrection"], <add> "9200" : ["CS", "MRSpectroscopyAcquisitionType"], <add> "9214" : ["CS", "RespiratoryCyclePosition"], <add> "9217" : ["FD", "VelocityEncodingMaximumValue"], <add> "9218" : ["FD", "TagSpacingSecondDimension"], <add> "9219" : ["SS", "TagAngleSecondAxis"], <add> "9220" : ["FD", "FrameAcquisitionDuration"], <add> "9226" : ["SQ", "MRImageFrameTypeSequence"], <add> "9227" : ["SQ", "MRSpectroscopyFrameTypeSequence"], <add> "9231" : ["US", "MRAcquisitionPhaseEncodingStepsInPlane"], <add> "9232" : ["US", "MRAcquisitionPhaseEncodingStepsOutOfPlane"], <add> "9234" : ["UL", "SpectroscopyAcquisitionPhaseColumns"], <add> "9236" : ["CS", "CardiacCyclePosition"], <add> "9239" : ["SQ", "SpecificAbsorptionRateSequence"], <add> "9240" : ["US", "RFEchoTrainLength"], <add> "9241" : ["US", "GradientEchoTrainLength"], <add> "9250" : ["CS", "ArterialSpinLabelingContrast"], <add> "9251" : ["SQ", "MRArterialSpinLabelingSequence"], <add> "9252" : ["LO", "ASLTechniqueDescription"], <add> "9253" : ["US", "ASLSlabNumber"], <add> "9254" : ["FD ", "ASLSlabThickness"], <add> "9255" : ["FD ", "ASLSlabOrientation"], <add> "9256" : ["FD ", "ASLMidSlabPosition"], <add> "9257" : ["CS", "ASLContext"], <add> "9258" : ["UL", "ASLPulseTrainDuration"], <add> "9259" : ["CS", "ASLCrusherFlag"], <add> "925A" : ["FD", "ASLCrusherFlow"], <add> "925B" : ["LO", "ASLCrusherDescription"], <add> "925C" : ["CS", "ASLBolusCutoffFlag"], <add> "925D" : ["SQ", "ASLBolusCutoffTimingSequence"], <add> "925E" : ["LO", "ASLBolusCutoffTechnique"], <add> "925F" : ["UL", "ASLBolusCutoffDelayTime"], <add> "9260" : ["SQ", "ASLSlabSequence"], <add> "9295" : ["FD", "ChemicalShiftMinimumIntegrationLimitInppm"], <add> "9296" : ["FD", "ChemicalShiftMaximumIntegrationLimitInppm"], <add> "9301" : ["SQ", "CTAcquisitionTypeSequence"], <add> "9302" : ["CS", "AcquisitionType"], <add> "9303" : ["FD", "TubeAngle"], <add> "9304" : ["SQ", "CTAcquisitionDetailsSequence"], <add> "9305" : ["FD", "RevolutionTime"], <add> "9306" : ["FD", "SingleCollimationWidth"], <add> "9307" : ["FD", "TotalCollimationWidth"], <add> "9308" : ["SQ", "CTTableDynamicsSequence"], <add> "9309" : ["FD", "TableSpeed"], <add> "9310" : ["FD", "TableFeedPerRotation"], <add> "9311" : ["FD", "SpiralPitchFactor"], <add> "9312" : ["SQ", "CTGeometrySequence"], <add> "9313" : ["FD", "DataCollectionCenterPatient"], <add> "9314" : ["SQ", "CTReconstructionSequence"], <add> "9315" : ["CS", "ReconstructionAlgorithm"], <add> "9316" : ["CS", "ConvolutionKernelGroup"], <add> "9317" : ["FD", "ReconstructionFieldOfView"], <add> "9318" : ["FD", "ReconstructionTargetCenterPatient"], <add> "9319" : ["FD", "ReconstructionAngle"], <add> "9320" : ["SH", "ImageFilter"], <add> "9321" : ["SQ", "CTExposureSequence"], <add> "9322" : ["FD", "ReconstructionPixelSpacing"], <add> "9323" : ["CS", "ExposureModulationType"], <add> "9324" : ["FD", "EstimatedDoseSaving"], <add> "9325" : ["SQ", "CTXRayDetailsSequence"], <add> "9326" : ["SQ", "CTPositionSequence"], <add> "9327" : ["FD", "TablePosition"], <add> "9328" : ["FD", "ExposureTimeInms"], <add> "9329" : ["SQ", "CTImageFrameTypeSequence"], <add> "9330" : ["FD", "XRayTubeCurrentInmA"], <add> "9332" : ["FD", "ExposureInmAs"], <add> "9333" : ["CS", "ConstantVolumeFlag"], <add> "9334" : ["CS", "FluoroscopyFlag"], <add> "9335" : ["FD", "DistanceSourceToDataCollectionCenter"], <add> "9337" : ["US", "ContrastBolusAgentNumber"], <add> "9338" : ["SQ", "ContrastBolusIngredientCodeSequence"], <add> "9340" : ["SQ", "ContrastAdministrationProfileSequence"], <add> "9341" : ["SQ", "ContrastBolusUsageSequence"], <add> "9342" : ["CS", "ContrastBolusAgentAdministered"], <add> "9343" : ["CS", "ContrastBolusAgentDetected"], <add> "9344" : ["CS", "ContrastBolusAgentPhase"], <add> "9345" : ["FD", "CTDIvol"], <add> "9346" : ["SQ", "CTDIPhantomTypeCodeSequence"], <add> "9351" : ["FL", "CalciumScoringMassFactorPatient"], <add> "9352" : ["FL", "CalciumScoringMassFactorDevice"], <add> "9353" : ["FL", "EnergyWeightingFactor"], <add> "9360" : ["SQ", "CTAdditionalXRaySourceSequence"], <add> "9401" : ["SQ", "ProjectionPixelCalibrationSequence"], <add> "9402" : ["FL", "DistanceSourceToIsocenter"], <add> "9403" : ["FL", "DistanceObjectToTableTop"], <add> "9404" : ["FL", "ObjectPixelSpacingInCenterOfBeam"], <add> "9405" : ["SQ", "PositionerPositionSequence"], <add> "9406" : ["SQ", "TablePositionSequence"], <add> "9407" : ["SQ", "CollimatorShapeSequence"], <add> "9410" : ["CS", "PlanesInAcquisition"], <add> "9412" : ["SQ", "XAXRFFrameCharacteristicsSequence"], <add> "9417" : ["SQ", "FrameAcquisitionSequence"], <add> "9420" : ["CS", "XRayReceptorType"], <add> "9423" : ["LO", "AcquisitionProtocolName"], <add> "9424" : ["LT", "AcquisitionProtocolDescription"], <add> "9425" : ["CS", "ContrastBolusIngredientOpaque"], <add> "9426" : ["FL", "DistanceReceptorPlaneToDetectorHousing"], <add> "9427" : ["CS", "IntensifierActiveShape"], <add> "9428" : ["FL", "IntensifierActiveDimensions"], <add> "9429" : ["FL", "PhysicalDetectorSize"], <add> "9430" : ["FL", "PositionOfIsocenterProjection"], <add> "9432" : ["SQ", "FieldOfViewSequence"], <add> "9433" : ["LO", "FieldOfViewDescription"], <add> "9434" : ["SQ", "ExposureControlSensingRegionsSequence"], <add> "9435" : ["CS", "ExposureControlSensingRegionShape"], <add> "9436" : ["SS", "ExposureControlSensingRegionLeftVerticalEdge"], <add> "9437" : ["SS", "ExposureControlSensingRegionRightVerticalEdge"], <add> "9438" : ["SS", "ExposureControlSensingRegionUpperHorizontalEdge"], <add> "9439" : ["SS", "ExposureControlSensingRegionLowerHorizontalEdge"], <add> "9440" : ["SS", "CenterOfCircularExposureControlSensingRegion"], <add> "9441" : ["US", "RadiusOfCircularExposureControlSensingRegion"], <add> "9442" : ["SS", "VerticesOfThePolygonalExposureControlSensingRegion"], <add> "9447" : ["FL", "ColumnAngulationPatient"], <add> "9449" : ["FL", "BeamAngle"], <add> "9451" : ["SQ", "FrameDetectorParametersSequence"], <add> "9452" : ["FL", "CalculatedAnatomyThickness"], <add> "9455" : ["SQ", "CalibrationSequence"], <add> "9456" : ["SQ", "ObjectThicknessSequence"], <add> "9457" : ["CS", "PlaneIdentification"], <add> "9461" : ["FL", "FieldOfViewDimensionsInFloat"], <add> "9462" : ["SQ", "IsocenterReferenceSystemSequence"], <add> "9463" : ["FL", "PositionerIsocenterPrimaryAngle"], <add> "9464" : ["FL", "PositionerIsocenterSecondaryAngle"], <add> "9465" : ["FL", "PositionerIsocenterDetectorRotationAngle"], <add> "9466" : ["FL", "TableXPositionToIsocenter"], <add> "9467" : ["FL", "TableYPositionToIsocenter"], <add> "9468" : ["FL", "TableZPositionToIsocenter"], <add> "9469" : ["FL", "TableHorizontalRotationAngle"], <add> "9470" : ["FL", "TableHeadTiltAngle"], <add> "9471" : ["FL", "TableCradleTiltAngle"], <add> "9472" : ["SQ", "FrameDisplayShutterSequence"], <add> "9473" : ["FL", "AcquiredImageAreaDoseProduct"], <add> "9474" : ["CS", "CArmPositionerTabletopRelationship"], <add> "9476" : ["SQ", "XRayGeometrySequence"], <add> "9477" : ["SQ", "IrradiationEventIdentificationSequence"], <add> "9504" : ["SQ", "XRay3DFrameTypeSequence"], <add> "9506" : ["SQ", "ContributingSourcesSequence"], <add> "9507" : ["SQ", "XRay3DAcquisitionSequence"], <add> "9508" : ["FL", "PrimaryPositionerScanArc"], <add> "9509" : ["FL", "SecondaryPositionerScanArc"], <add> "9510" : ["FL ", "PrimaryPositionerScanStartAngle"], <add> "9511" : ["FL", "SecondaryPositionerScanStartAngle"], <add> "9514" : ["FL", "PrimaryPositionerIncrement"], <add> "9515" : ["FL", "SecondaryPositionerIncrement"], <add> "9516" : ["DT", "StartAcquisitionDateTime"], <add> "9517" : ["DT", "EndAcquisitionDateTime"], <add> "9524" : ["LO", "ApplicationName"], <add> "9525" : ["LO", "ApplicationVersion"], <add> "9526" : ["LO", "ApplicationManufacturer"], <add> "9527" : ["CS", "AlgorithmType"], <add> "9528" : ["LO", "AlgorithmDescription"], <add> "9530" : ["SQ", "XRay3DReconstructionSequence"], <add> "9531" : ["LO", "ReconstructionDescription"], <add> "9538" : ["SQ", "PerProjectionAcquisitionSequence"], <add> "9601" : ["SQ", "DiffusionBMatrixSequence"], <add> "9602" : ["FD", "DiffusionBValueXX"], <add> "9603" : ["FD", "DiffusionBValueXY"], <add> "9604" : ["FD", "DiffusionBValueXZ"], <add> "9605" : ["FD", "DiffusionBValueYY"], <add> "9606" : ["FD", "DiffusionBValueYZ"], <add> "9607" : ["FD", "DiffusionBValueZZ"], <add> "9701" : ["DT", "DecayCorrectionDateTime"], <add> "9715" : ["FD", "StartDensityThreshold"], <add> "9716" : ["FD", "StartRelativeDensityDifferenceThreshold"], <add> "9717" : ["FD", "StartCardiacTriggerCountThreshold"], <add> "9718" : ["FD", "StartRespiratoryTriggerCountThreshold"], <add> "9719" : ["FD", "TerminationCountsThreshold"], <add> "9720" : ["FD", "TerminationDensityThreshold"], <add> "9721" : ["FD", "TerminationRelativeDensityThreshold"], <add> "9722" : ["FD", "TerminationTimeThreshold"], <add> "9723" : ["FD", "TerminationCardiacTriggerCountThreshold"], <add> "9724" : ["FD", "TerminationRespiratoryTriggerCountThreshold"], <add> "9725" : ["CS", "DetectorGeometry"], <add> "9726" : ["FD", "TransverseDetectorSeparation"], <add> "9727" : ["FD", "AxialDetectorDimension"], <add> "9729" : ["US", "RadiopharmaceuticalAgentNumber"], <add> "9732" : ["SQ", "PETFrameAcquisitionSequence"], <add> "9733" : ["SQ", "PETDetectorMotionDetailsSequence"], <add> "9734" : ["SQ", "PETTableDynamicsSequence"], <add> "9735" : ["SQ", "PETPositionSequence"], <add> "9736" : ["SQ", "PETFrameCorrectionFactorsSequence"], <add> "9737" : ["SQ", "RadiopharmaceuticalUsageSequence"], <add> "9738" : ["CS", "AttenuationCorrectionSource"], <add> "9739" : ["US", "NumberOfIterations"], <add> "9740" : ["US", "NumberOfSubsets"], <add> "9749" : ["SQ", "PETReconstructionSequence"], <add> "9751" : ["SQ", "PETFrameTypeSequence"], <add> "9755" : ["CS", "TimeOfFlightInformationUsed"], <add> "9756" : ["CS", "ReconstructionType"], <add> "9758" : ["CS", "DecayCorrected"], <add> "9759" : ["CS", "AttenuationCorrected"], <add> "9760" : ["CS", "ScatterCorrected"], <add> "9761" : ["CS", "DeadTimeCorrected"], <add> "9762" : ["CS", "GantryMotionCorrected"], <add> "9763" : ["CS", "PatientMotionCorrected"], <add> "9764" : ["CS", "CountLossNormalizationCorrected"], <add> "9765" : ["CS", "RandomsCorrected"], <add> "9766" : ["CS", "NonUniformRadialSamplingCorrected"], <add> "9767" : ["CS", "SensitivityCalibrated"], <add> "9768" : ["CS", "DetectorNormalizationCorrection"], <add> "9769" : ["CS", "IterativeReconstructionMethod"], <add> "9770" : ["CS", "AttenuationCorrectionTemporalRelationship"], <add> "9771" : ["SQ", "PatientPhysiologicalStateSequence"], <add> "9772" : ["SQ", "PatientPhysiologicalStateCodeSequence"], <add> "9801" : ["FD", "DepthsOfFocus"], <add> "9803" : ["SQ", "ExcludedIntervalsSequence"], <add> "9804" : ["DT", "ExclusionStartDatetime"], <add> "9805" : ["FD", "ExclusionDuration"], <add> "9806" : ["SQ", "USImageDescriptionSequence"], <add> "9807" : ["SQ", "ImageDataTypeSequence"], <add> "9808" : ["CS", "DataType"], <add> "9809" : ["SQ", "TransducerScanPatternCodeSequence"], <add> "980B" : ["CS", "AliasedDataType"], <add> "980C" : ["CS", "PositionMeasuringDeviceUsed"], <add> "980D" : ["SQ", "TransducerGeometryCodeSequence"], <add> "980E" : ["SQ", "TransducerBeamSteeringCodeSequence"], <add> "980F" : ["SQ", "TransducerApplicationCodeSequence"], <add> "A001" : ["SQ", "ContributingEquipmentSequence"], <add> "A002" : ["DT", "ContributionDateTime"], <add> "A003" : ["ST", "ContributionDescription"] <add> }, <add> "0020" : { <add> "000D" : ["UI", "StudyInstanceUID"], <add> "000E" : ["UI", "SeriesInstanceUID"], <add> "0010" : ["SH", "StudyID"], <add> "0011" : ["IS", "SeriesNumber"], <add> "0012" : ["IS", "AcquisitionNumber"], <add> "0013" : ["IS", "InstanceNumber"], <add> "0014" : ["IS", "IsotopeNumber"], <add> "0015" : ["IS", "PhaseNumber"], <add> "0016" : ["IS", "IntervalNumber"], <add> "0017" : ["IS", "TimeSlotNumber"], <add> "0018" : ["IS", "AngleNumber"], <add> "0019" : ["IS", "ItemNumber"], <add> "0020" : ["CS", "PatientOrientation"], <add> "0022" : ["IS", "OverlayNumber"], <add> "0024" : ["IS", "CurveNumber"], <add> "0026" : ["IS", "LUTNumber"], <add> "0030" : ["DS", "ImagePosition"], <add> "0032" : ["DS", "ImagePositionPatient"], <add> "0035" : ["DS", "ImageOrientation"], <add> "0037" : ["DS", "ImageOrientationPatient"], <add> "0050" : ["DS", "Location"], <add> "0052" : ["UI", "FrameOfReferenceUID"], <add> "0060" : ["CS", "Laterality"], <add> "0062" : ["CS", "ImageLaterality"], <add> "0070" : ["LO", "ImageGeometryType"], <add> "0080" : ["CS", "MaskingImage"], <add> "00AA" : ["IS", "ReportNumber"], <add> "0100" : ["IS", "TemporalPositionIdentifier"], <add> "0105" : ["IS", "NumberOfTemporalPositions"], <add> "0110" : ["DS", "TemporalResolution"], <add> "0200" : ["UI", "SynchronizationFrameOfReferenceUID"], <add> "0242" : ["UI", "SOPInstanceUIDOfConcatenationSource"], <add> "1000" : ["IS", "SeriesInStudy"], <add> "1001" : ["IS", "AcquisitionsInSeries"], <add> "1002" : ["IS", "ImagesInAcquisition"], <add> "1003" : ["IS", "ImagesInSeries"], <add> "1004" : ["IS", "AcquisitionsInStudy"], <add> "1005" : ["IS", "ImagesInStudy"], <add> "1020" : ["LO", "Reference"], <add> "1040" : ["LO", "PositionReferenceIndicator"], <add> "1041" : ["DS", "SliceLocation"], <add> "1070" : ["IS", "OtherStudyNumbers"], <add> "1200" : ["IS", "NumberOfPatientRelatedStudies"], <add> "1202" : ["IS", "NumberOfPatientRelatedSeries"], <add> "1204" : ["IS", "NumberOfPatientRelatedInstances"], <add> "1206" : ["IS", "NumberOfStudyRelatedSeries"], <add> "1208" : ["IS", "NumberOfStudyRelatedInstances"], <add> "1209" : ["IS", "NumberOfSeriesRelatedInstances"], <add> "3401" : ["CS", "ModifyingDeviceID"], <add> "3402" : ["CS", "ModifiedImageID"], <add> "3403" : ["DA", "ModifiedImageDate"], <add> "3404" : ["LO", "ModifyingDeviceManufacturer"], <add> "3405" : ["TM", "ModifiedImageTime"], <add> "3406" : ["LO", "ModifiedImageDescription"], <add> "4000" : ["LT", "ImageComments"], <add> "5000" : ["AT", "OriginalImageIdentification"], <add> "5002" : ["LO", "OriginalImageIdentificationNomenclature"], <add> "9056" : ["SH", "StackID"], <add> "9057" : ["UL", "InStackPositionNumber"], <add> "9071" : ["SQ", "FrameAnatomySequence"], <add> "9072" : ["CS", "FrameLaterality"], <add> "9111" : ["SQ", "FrameContentSequence"], <add> "9113" : ["SQ", "PlanePositionSequence"], <add> "9116" : ["SQ", "PlaneOrientationSequence"], <add> "9128" : ["UL", "TemporalPositionIndex"], <add> "9153" : ["FD", "NominalCardiacTriggerDelayTime"], <add> "9154" : ["FL", "NominalCardiacTriggerTimePriorToRPeak"], <add> "9155" : ["FL", "ActualCardiacTriggerTimePriorToRPeak"], <add> "9156" : ["US", "FrameAcquisitionNumber"], <add> "9157" : ["UL", "DimensionIndexValues"], <add> "9158" : ["LT", "FrameComments"], <add> "9161" : ["UI", "ConcatenationUID"], <add> "9162" : ["US", "InConcatenationNumber"], <add> "9163" : ["US", "InConcatenationTotalNumber"], <add> "9164" : ["UI", "DimensionOrganizationUID"], <add> "9165" : ["AT", "DimensionIndexPointer"], <add> "9167" : ["AT", "FunctionalGroupPointer"], <add> "9213" : ["LO", "DimensionIndexPrivateCreator"], <add> "9221" : ["SQ", "DimensionOrganizationSequence"], <add> "9222" : ["SQ", "DimensionIndexSequence"], <add> "9228" : ["UL", "ConcatenationFrameOffsetNumber"], <add> "9238" : ["LO", "FunctionalGroupPrivateCreator"], <add> "9241" : ["FL", "NominalPercentageOfCardiacPhase"], <add> "9245" : ["FL", "NominalPercentageOfRespiratoryPhase"], <add> "9246" : ["FL", "StartingRespiratoryAmplitude"], <add> "9247" : ["CS", "StartingRespiratoryPhase"], <add> "9248" : ["FL", "EndingRespiratoryAmplitude"], <add> "9249" : ["CS", "EndingRespiratoryPhase"], <add> "9250" : ["CS", "RespiratoryTriggerType"], <add> "9251" : ["FD", "RRIntervalTimeNominal"], <add> "9252" : ["FD", "ActualCardiacTriggerDelayTime"], <add> "9253" : ["SQ", "RespiratorySynchronizationSequence"], <add> "9254" : ["FD", "RespiratoryIntervalTime"], <add> "9255" : ["FD", "NominalRespiratoryTriggerDelayTime"], <add> "9256" : ["FD", "RespiratoryTriggerDelayThreshold"], <add> "9257" : ["FD", "ActualRespiratoryTriggerDelayTime"], <add> "9301" : ["FD", "ImagePositionVolume"], <add> "9302" : ["FD", "ImageOrientationVolume"], <add> "9307" : ["CS", "UltrasoundAcquisitionGeometry"], <add> "9308" : ["FD", "ApexPosition"], <add> "9309" : ["FD", "VolumeToTransducerMappingMatrix"], <add> "930A" : ["FD", "VolumeToTableMappingMatrix"], <add> "930C" : ["CS", "PatientFrameOfReferenceSource"], <add> "930D" : ["FD", "TemporalPositionTimeOffset"], <add> "930E" : ["SQ", "PlanePositionVolumeSequence"], <add> "930F" : ["SQ", "PlaneOrientationVolumeSequence"], <add> "9310" : ["SQ", "TemporalPositionSequence"], <add> "9311" : ["CS", "DimensionOrganizationType"], <add> "9312" : ["UI", "VolumeFrameOfReferenceUID"], <add> "9313" : ["UI", "TableFrameOfReferenceUID"], <add> "9421" : ["LO", "DimensionDescriptionLabel"], <add> "9450" : ["SQ", "PatientOrientationInFrameSequence"], <add> "9453" : ["LO", "FrameLabel"], <add> "9518" : ["US", "AcquisitionIndex"], <add> "9529" : ["SQ", "ContributingSOPInstancesReferenceSequence"], <add> "9536" : ["US", "ReconstructionIndex"] <add> }, <add> "0022" : { <add> "0001" : ["US", "LightPathFilterPassThroughWavelength"], <add> "0002" : ["US", "LightPathFilterPassBand"], <add> "0003" : ["US", "ImagePathFilterPassThroughWavelength"], <add> "0004" : ["US", "ImagePathFilterPassBand"], <add> "0005" : ["CS", "PatientEyeMovementCommanded"], <add> "0006" : ["SQ", "PatientEyeMovementCommandCodeSequence"], <add> "0007" : ["FL", "SphericalLensPower"], <add> "0008" : ["FL", "CylinderLensPower"], <add> "0009" : ["FL", "CylinderAxis"], <add> "000A" : ["FL", "EmmetropicMagnification"], <add> "000B" : ["FL", "IntraOcularPressure"], <add> "000C" : ["FL", "HorizontalFieldOfView"], <add> "000D" : ["CS", "PupilDilated"], <add> "000E" : ["FL", "DegreeOfDilation"], <add> "0010" : ["FL", "StereoBaselineAngle"], <add> "0011" : ["FL", "StereoBaselineDisplacement"], <add> "0012" : ["FL", "StereoHorizontalPixelOffset"], <add> "0013" : ["FL", "StereoVerticalPixelOffset"], <add> "0014" : ["FL", "StereoRotation"], <add> "0015" : ["SQ", "AcquisitionDeviceTypeCodeSequence"], <add> "0016" : ["SQ", "IlluminationTypeCodeSequence"], <add> "0017" : ["SQ", "LightPathFilterTypeStackCodeSequence"], <add> "0018" : ["SQ", "ImagePathFilterTypeStackCodeSequence"], <add> "0019" : ["SQ", "LensesCodeSequence"], <add> "001A" : ["SQ", "ChannelDescriptionCodeSequence"], <add> "001B" : ["SQ", "RefractiveStateSequence"], <add> "001C" : ["SQ", "MydriaticAgentCodeSequence"], <add> "001D" : ["SQ", "RelativeImagePositionCodeSequence"], <add> "001E" : ["FL", "CameraAngleOfView"], <add> "0020" : ["SQ", "StereoPairsSequence"], <add> "0021" : ["SQ", "LeftImageSequence"], <add> "0022" : ["SQ", "RightImageSequence"], <add> "0030" : ["FL", "AxialLengthOfTheEye"], <add> "0031" : ["SQ", "OphthalmicFrameLocationSequence"], <add> "0032" : ["FL", "ReferenceCoordinates"], <add> "0035" : ["FL", "DepthSpatialResolution"], <add> "0036" : ["FL", "MaximumDepthDistortion"], <add> "0037" : ["FL", "AlongScanSpatialResolution"], <add> "0038" : ["FL", "MaximumAlongScanDistortion"], <add> "0039" : ["CS", "OphthalmicImageOrientation"], <add> "0041" : ["FL", "DepthOfTransverseImage"], <add> "0042" : ["SQ", "MydriaticAgentConcentrationUnitsSequence"], <add> "0048" : ["FL", "AcrossScanSpatialResolution"], <add> "0049" : ["FL", "MaximumAcrossScanDistortion"], <add> "004E" : ["DS", "MydriaticAgentConcentration"], <add> "0055" : ["FL", "IlluminationWaveLength"], <add> "0056" : ["FL", "IlluminationPower"], <add> "0057" : ["FL", "IlluminationBandwidth"], <add> "0058" : ["SQ", "MydriaticAgentSequence"], <add> "1007" : ["SQ", "OphthalmicAxialMeasurementsRightEyeSequence"], <add> "1008" : ["SQ", "OphthalmicAxialMeasurementsLeftEyeSequence"], <add> "1010" : ["CS", "OphthalmicAxialLengthMeasurementsType"], <add> "1019" : ["FL", "OphthalmicAxialLength"], <add> "1024" : ["SQ", "LensStatusCodeSequence"], <add> "1025" : ["SQ", "VitreousStatusCodeSequence"], <add> "1028" : ["SQ", "IOLFormulaCodeSequence"], <add> "1029" : ["LO", "IOLFormulaDetail"], <add> "1033" : ["FL", "KeratometerIndex"], <add> "1035" : ["SQ", "SourceOfOphthalmicAxialLengthCodeSequence"], <add> "1037" : ["FL", "TargetRefraction"], <add> "1039" : ["CS", "RefractiveProcedureOccurred"], <add> "1040" : ["SQ", "RefractiveSurgeryTypeCodeSequence"], <add> "1044" : ["SQ", "OphthalmicUltrasoundAxialMeasurementsTypeCodeSequence"], <add> "1050" : ["SQ", "OphthalmicAxialLengthMeasurementsSequence"], <add> "1053" : ["FL", "IOLPower"], <add> "1054" : ["FL", "PredictedRefractiveError"], <add> "1059" : ["FL", "OphthalmicAxialLengthVelocity"], <add> "1065" : ["LO", "LensStatusDescription"], <add> "1066" : ["LO", "VitreousStatusDescription"], <add> "1090" : ["SQ", "IOLPowerSequence"], <add> "1092" : ["SQ", "LensConstantSequence"], <add> "1093" : ["LO", "IOLManufacturer"], <add> "1094" : ["LO", "LensConstantDescription"], <add> "1096" : ["SQ", "KeratometryMeasurementTypeCodeSequence"], <add> "1100" : ["SQ", "ReferencedOphthalmicAxialMeasurementsSequence"], <add> "1101" : ["SQ", "OphthalmicAxialLengthMeasurementsSegmentNameCodeSequence"], <add> "1103" : ["SQ", "RefractiveErrorBeforeRefractiveSurgeryCodeSequence"], <add> "1121" : ["FL", "IOLPowerForExactEmmetropia"], <add> "1122" : ["FL", "IOLPowerForExactTargetRefraction"], <add> "1125" : ["SQ", "AnteriorChamberDepthDefinitionCodeSequence"], <add> "1130" : ["FL", "LensThickness"], <add> "1131" : ["FL", "AnteriorChamberDepth"], <add> "1132" : ["SQ", "SourceOfLensThicknessDataCodeSequence"], <add> "1133" : ["SQ", "SourceOfAnteriorChamberDepthDataCodeSequence"], <add> "1135" : ["SQ", "SourceOfRefractiveErrorDataCodeSequence"], <add> "1140" : ["CS", "OphthalmicAxialLengthMeasurementModified"], <add> "1150" : ["SQ", "OphthalmicAxialLengthDataSourceCodeSequence"], <add> "1153" : ["SQ", "OphthalmicAxialLengthAcquisitionMethodCodeSequence"], <add> "1155" : ["FL", "SignalToNoiseRatio"], <add> "1159" : ["LO", "OphthalmicAxialLengthDataSourceDescription"], <add> "1210" : ["SQ", "OphthalmicAxialLengthMeasurementsTotalLengthSequence"], <add> "1211" : ["SQ", "OphthalmicAxialLengthMeasurementsSegmentalLengthSequence"], <add> "1212" : ["SQ", "OphthalmicAxialLengthMeasurementsLengthSummationSequence"], <add> "1220" : ["SQ", "UltrasoundOphthalmicAxialLengthMeasurementsSequence"], <add> "1225" : ["SQ", "OpticalOphthalmicAxialLengthMeasurementsSequence"], <add> "1230" : ["SQ", "UltrasoundSelectedOphthalmicAxialLengthSequence"], <add> "1250" : ["SQ", "OphthalmicAxialLengthSelectionMethodCodeSequence"], <add> "1255" : ["SQ", "OpticalSelectedOphthalmicAxialLengthSequence"], <add> "1257" : ["SQ", "SelectedSegmentalOphthalmicAxialLengthSequence"], <add> "1260" : ["SQ", "SelectedTotalOphthalmicAxialLengthSequence"], <add> "1262" : ["SQ", "OphthalmicAxialLengthQualityMetricSequence"], <add> "1273" : ["LO", "OphthalmicAxialLengthQualityMetricTypeDescription"], <add> "1300" : ["SQ", "IntraocularLensCalculationsRightEyeSequence"], <add> "1310" : ["SQ", "IntraocularLensCalculationsLeftEyeSequence"], <add> "1330" : ["SQ", "ReferencedOphthalmicAxialLengthMeasurementQCImageSequence"] <add> }, <add> "0024" : { <add> "0010" : ["FL", "VisualFieldHorizontalExtent"], <add> "0011" : ["FL", "VisualFieldVerticalExtent"], <add> "0012" : ["CS", "VisualFieldShape"], <add> "0016" : ["SQ", "ScreeningTestModeCodeSequence"], <add> "0018" : ["FL", "MaximumStimulusLuminance"], <add> "0020" : ["FL", "BackgroundLuminance"], <add> "0021" : ["SQ", "StimulusColorCodeSequence"], <add> "0024" : ["SQ", "BackgroundIlluminationColorCodeSequence"], <add> "0025" : ["FL", "StimulusArea"], <add> "0028" : ["FL", "StimulusPresentationTime"], <add> "0032" : ["SQ", "FixationSequence"], <add> "0033" : ["SQ", "FixationMonitoringCodeSequence"], <add> "0034" : ["SQ", "VisualFieldCatchTrialSequence"], <add> "0035" : ["US", "FixationCheckedQuantity"], <add> "0036" : ["US", "PatientNotProperlyFixatedQuantity"], <add> "0037" : ["CS", "PresentedVisualStimuliDataFlag"], <add> "0038" : ["US", "NumberOfVisualStimuli"], <add> "0039" : ["CS", "ExcessiveFixationLossesDataFlag"], <add> "0040" : ["CS", "ExcessiveFixationLosses"], <add> "0042" : ["US", "StimuliRetestingQuantity"], <add> "0044" : ["LT", "CommentsOnPatientPerformanceOfVisualField"], <add> "0045" : ["CS", "FalseNegativesEstimateFlag"], <add> "0046" : ["FL", "FalseNegativesEstimate"], <add> "0048" : ["US", "NegativeCatchTrialsQuantity"], <add> "0050" : ["US", "FalseNegativesQuantity"], <add> "0051" : ["CS", "ExcessiveFalseNegativesDataFlag"], <add> "0052" : ["CS", "ExcessiveFalseNegatives"], <add> "0053" : ["CS", "FalsePositivesEstimateFlag"], <add> "0054" : ["FL", "FalsePositivesEstimate"], <add> "0055" : ["CS", "CatchTrialsDataFlag"], <add> "0056" : ["US", "PositiveCatchTrialsQuantity"], <add> "0057" : ["CS", "TestPointNormalsDataFlag"], <add> "0058" : ["SQ", "TestPointNormalsSequence"], <add> "0059" : ["CS", "GlobalDeviationProbabilityNormalsFlag"], <add> "0060" : ["US", "FalsePositivesQuantity"], <add> "0061" : ["CS", "ExcessiveFalsePositivesDataFlag"], <add> "0062" : ["CS", "ExcessiveFalsePositives"], <add> "0063" : ["CS", "VisualFieldTestNormalsFlag"], <add> "0064" : ["SQ", "ResultsNormalsSequence"], <add> "0065" : ["SQ", "AgeCorrectedSensitivityDeviationAlgorithmSequence"], <add> "0066" : ["FL", "GlobalDeviationFromNormal"], <add> "0067" : ["SQ", "GeneralizedDefectSensitivityDeviationAlgorithmSequence"], <add> "0068" : ["FL", "LocalizedDeviationfromNormal"], <add> "0069" : ["LO", "PatientReliabilityIndicator"], <add> "0070" : ["FL", "VisualFieldMeanSensitivity"], <add> "0071" : ["FL", "GlobalDeviationProbability"], <add> "0072" : ["CS", "LocalDeviationProbabilityNormalsFlag"], <add> "0073" : ["FL", "LocalizedDeviationProbability"], <add> "0074" : ["CS", "ShortTermFluctuationCalculated"], <add> "0075" : ["FL", "ShortTermFluctuation"], <add> "0076" : ["CS", "ShortTermFluctuationProbabilityCalculated"], <add> "0077" : ["FL", "ShortTermFluctuationProbability"], <add> "0078" : ["CS", "CorrectedLocalizedDeviationFromNormalCalculated"], <add> "0079" : ["FL", "CorrectedLocalizedDeviationFromNormal"], <add> "0080" : ["CS", "CorrectedLocalizedDeviationFromNormalProbabilityCalculated"], <add> "0081" : ["FL", "CorrectedLocalizedDeviationFromNormalProbability"], <add> "0083" : ["SQ", "GlobalDeviationProbabilitySequence"], <add> "0085" : ["SQ", "LocalizedDeviationProbabilitySequence"], <add> "0086" : ["CS", "FovealSensitivityMeasured"], <add> "0087" : ["FL", "FovealSensitivity"], <add> "0088" : ["FL", "VisualFieldTestDuration"], <add> "0089" : ["SQ", "VisualFieldTestPointSequence"], <add> "0090" : ["FL", "VisualFieldTestPointXCoordinate"], <add> "0091" : ["FL", "VisualFieldTestPointYCoordinate"], <add> "0092" : ["FL", "AgeCorrectedSensitivityDeviationValue"], <add> "0093" : ["CS", "StimulusResults"], <add> "0094" : ["FL", "SensitivityValue"], <add> "0095" : ["CS", "RetestStimulusSeen"], <add> "0096" : ["FL", "RetestSensitivityValue"], <add> "0097" : ["SQ", "VisualFieldTestPointNormalsSequence"], <add> "0098" : ["FL", "QuantifiedDefect"], <add> "0100" : ["FL", "AgeCorrectedSensitivityDeviationProbabilityValue"], <add> "0102" : ["CS", "GeneralizedDefectCorrectedSensitivityDeviationFlag "], <add> "0103" : ["FL", "GeneralizedDefectCorrectedSensitivityDeviationValue "], <add> "0104" : ["FL", "GeneralizedDefectCorrectedSensitivityDeviationProbabilityValue"], <add> "0105" : ["FL ", "MinimumSensitivityValue"], <add> "0106" : ["CS", "BlindSpotLocalized"], <add> "0107" : ["FL", "BlindSpotXCoordinate"], <add> "0108" : ["FL", "BlindSpotYCoordinate "], <add> "0110" : ["SQ", "VisualAcuityMeasurementSequence"], <add> "0112" : ["SQ", "RefractiveParametersUsedOnPatientSequence"], <add> "0113" : ["CS", "MeasurementLaterality"], <add> "0114" : ["SQ", "OphthalmicPatientClinicalInformationLeftEyeSequence"], <add> "0115" : ["SQ", "OphthalmicPatientClinicalInformationRightEyeSequence"], <add> "0117" : ["CS", "FovealPointNormativeDataFlag"], <add> "0118" : ["FL", "FovealPointProbabilityValue"], <add> "0120" : ["CS", "ScreeningBaselineMeasured"], <add> "0122" : ["SQ", "ScreeningBaselineMeasuredSequence"], <add> "0124" : ["CS", "ScreeningBaselineType"], <add> "0126" : ["FL", "ScreeningBaselineValue"], <add> "0202" : ["LO", "AlgorithmSource"], <add> "0306" : ["LO", "DataSetName"], <add> "0307" : ["LO", "DataSetVersion"], <add> "0308" : ["LO", "DataSetSource"], <add> "0309" : ["LO", "DataSetDescription"], <add> "0317" : ["SQ", "VisualFieldTestReliabilityGlobalIndexSequence"], <add> "0320" : ["SQ", "VisualFieldGlobalResultsIndexSequence"], <add> "0325" : ["SQ", "DataObservationSequence"], <add> "0338" : ["CS", "IndexNormalsFlag"], <add> "0341" : ["FL", "IndexProbability"], <add> "0344" : ["SQ", "IndexProbabilitySequence"] <add> }, <add> "0028" : { <add> "0002" : ["US", "SamplesPerPixel"], <add> "0003" : ["US", "SamplesPerPixelUsed"], <add> "0004" : ["CS", "PhotometricInterpretation"], <add> "0005" : ["US", "ImageDimensions"], <add> "0006" : ["US", "PlanarConfiguration"], <add> "0008" : ["IS", "NumberOfFrames"], <add> "0009" : ["AT", "FrameIncrementPointer"], <add> "000A" : ["AT", "FrameDimensionPointer"], <add> "0010" : ["US", "Rows"], <add> "0011" : ["US", "Columns"], <add> "0012" : ["US", "Planes"], <add> "0014" : ["US", "UltrasoundColorDataPresent"], <add> "0030" : ["DS", "PixelSpacing"], <add> "0031" : ["DS", "ZoomFactor"], <add> "0032" : ["DS", "ZoomCenter"], <add> "0034" : ["IS", "PixelAspectRatio"], <add> "0040" : ["CS", "ImageFormat"], <add> "0050" : ["LO", "ManipulatedImage"], <add> "0051" : ["CS", "CorrectedImage"], <add> "005F" : ["LO", "CompressionRecognitionCode"], <add> "0060" : ["CS", "CompressionCode"], <add> "0061" : ["SH", "CompressionOriginator"], <add> "0062" : ["LO", "CompressionLabel"], <add> "0063" : ["SH", "CompressionDescription"], <add> "0065" : ["CS", "CompressionSequence"], <add> "0066" : ["AT", "CompressionStepPointers"], <add> "0068" : ["US", "RepeatInterval"], <add> "0069" : ["US", "BitsGrouped"], <add> "0070" : ["US", "PerimeterTable"], <add> "0071" : ["SS", "PerimeterValue"], <add> "0080" : ["US", "PredictorRows"], <add> "0081" : ["US", "PredictorColumns"], <add> "0082" : ["US", "PredictorConstants"], <add> "0090" : ["CS", "BlockedPixels"], <add> "0091" : ["US", "BlockRows"], <add> "0092" : ["US", "BlockColumns"], <add> "0093" : ["US", "RowOverlap"], <add> "0094" : ["US", "ColumnOverlap"], <add> "0100" : ["US", "BitsAllocated"], <add> "0101" : ["US", "BitsStored"], <add> "0102" : ["US", "HighBit"], <add> "0103" : ["US", "PixelRepresentation"], <add> "0104" : ["SS", "SmallestValidPixelValue"], <add> "0105" : ["SS", "LargestValidPixelValue"], <add> "0106" : ["SS", "SmallestImagePixelValue"], <add> "0107" : ["SS", "LargestImagePixelValue"], <add> "0108" : ["SS", "SmallestPixelValueInSeries"], <add> "0109" : ["SS", "LargestPixelValueInSeries"], <add> "0110" : ["SS", "SmallestImagePixelValueInPlane"], <add> "0111" : ["SS", "LargestImagePixelValueInPlane"], <add> "0120" : ["SS", "PixelPaddingValue"], <add> "0121" : ["SS", "PixelPaddingRangeLimit"], <add> "0200" : ["US", "ImageLocation"], <add> "0300" : ["CS", "QualityControlImage"], <add> "0301" : ["CS", "BurnedInAnnotation"], <add> "0302" : ["CS", "RecognizableVisualFeatures"], <add> "0303" : ["CS", "LongitudinalTemporalInformationModified"], <add> "0400" : ["LO", "TransformLabel"], <add> "0401" : ["LO", "TransformVersionNumber"], <add> "0402" : ["US", "NumberOfTransformSteps"], <add> "0403" : ["LO", "SequenceOfCompressedData"], <add> "0404" : ["AT", "DetailsOfCoefficients"], <add> "0700" : ["LO", "DCTLabel"], <add> "0701" : ["CS", "DataBlockDescription"], <add> "0702" : ["AT", "DataBlock"], <add> "0710" : ["US", "NormalizationFactorFormat"], <add> "0720" : ["US", "ZonalMapNumberFormat"], <add> "0721" : ["AT", "ZonalMapLocation"], <add> "0722" : ["US", "ZonalMapFormat"], <add> "0730" : ["US", "AdaptiveMapFormat"], <add> "0740" : ["US", "CodeNumberFormat"], <add> "0A02" : ["CS", "PixelSpacingCalibrationType"], <add> "0A04" : ["LO", "PixelSpacingCalibrationDescription"], <add> "1040" : ["CS", "PixelIntensityRelationship"], <add> "1041" : ["SS", "PixelIntensityRelationshipSign"], <add> "1050" : ["DS", "WindowCenter"], <add> "1051" : ["DS", "WindowWidth"], <add> "1052" : ["DS", "RescaleIntercept"], <add> "1053" : ["DS", "RescaleSlope"], <add> "1054" : ["LO", "RescaleType"], <add> "1055" : ["LO", "WindowCenterWidthExplanation"], <add> "1056" : ["CS", "VOILUTFunction"], <add> "1080" : ["CS", "GrayScale"], <add> "1090" : ["CS", "RecommendedViewingMode"], <add> "1100" : ["SS", "GrayLookupTableDescriptor"], <add> "1101" : ["SS", "RedPaletteColorLookupTableDescriptor"], <add> "1102" : ["SS", "GreenPaletteColorLookupTableDescriptor"], <add> "1103" : ["SS", "BluePaletteColorLookupTableDescriptor"], <add> "1104" : ["US", "AlphaPaletteColorLookupTableDescriptor"], <add> "1111" : ["SS", "LargeRedPaletteColorLookupTableDescriptor"], <add> "1112" : ["SS", "LargeGreenPaletteColorLookupTableDescriptor"], <add> "1113" : ["SS", "LargeBluePaletteColorLookupTableDescriptor"], <add> "1199" : ["UI", "PaletteColorLookupTableUID"], <add> "1200" : ["OW", "GrayLookupTableData"], <add> "1201" : ["OW", "RedPaletteColorLookupTableData"], <add> "1202" : ["OW", "GreenPaletteColorLookupTableData"], <add> "1203" : ["OW", "BluePaletteColorLookupTableData"], <add> "1204" : ["OW", "AlphaPaletteColorLookupTableData"], <add> "1211" : ["OW", "LargeRedPaletteColorLookupTableData"], <add> "1212" : ["OW", "LargeGreenPaletteColorLookupTableData"], <add> "1213" : ["OW", "LargeBluePaletteColorLookupTableData"], <add> "1214" : ["UI", "LargePaletteColorLookupTableUID"], <add> "1221" : ["OW", "SegmentedRedPaletteColorLookupTableData"], <add> "1222" : ["OW", "SegmentedGreenPaletteColorLookupTableData"], <add> "1223" : ["OW", "SegmentedBluePaletteColorLookupTableData"], <add> "1300" : ["CS", "BreastImplantPresent"], <add> "1350" : ["CS", "PartialView"], <add> "1351" : ["ST", "PartialViewDescription"], <add> "1352" : ["SQ", "PartialViewCodeSequence"], <add> "135A" : ["CS", "SpatialLocationsPreserved"], <add> "1401" : ["SQ", "DataFrameAssignmentSequence"], <add> "1402" : ["CS", "DataPathAssignment"], <add> "1403" : ["US", "BitsMappedToColorLookupTable"], <add> "1404" : ["SQ", "BlendingLUT1Sequence"], <add> "1405" : ["CS", "BlendingLUT1TransferFunction"], <add> "1406" : ["FD", "BlendingWeightConstant"], <add> "1407" : ["US", "BlendingLookupTableDescriptor"], <add> "1408" : ["OW", "BlendingLookupTableData"], <add> "140B" : ["SQ", "EnhancedPaletteColorLookupTableSequence"], <add> "140C" : ["SQ", "BlendingLUT2Sequence"], <add> "140D" : ["CS", "BlendingLUT2TransferFunction"], <add> "140E" : ["CS", "DataPathID"], <add> "140F" : ["CS", "RGBLUTTransferFunction"], <add> "1410" : ["CS", "AlphaLUTTransferFunction"], <add> "2000" : ["OB", "ICCProfile"], <add> "2110" : ["CS", "LossyImageCompression"], <add> "2112" : ["DS", "LossyImageCompressionRatio"], <add> "2114" : ["CS", "LossyImageCompressionMethod"], <add> "3000" : ["SQ", "ModalityLUTSequence"], <add> "3002" : ["SS", "LUTDescriptor"], <add> "3003" : ["LO", "LUTExplanation"], <add> "3004" : ["LO", "ModalityLUTType"], <add> "3006" : ["OW", "LUTData"], <add> "3010" : ["SQ", "VOILUTSequence"], <add> "3110" : ["SQ", "SoftcopyVOILUTSequence"], <add> "4000" : ["LT", "ImagePresentationComments"], <add> "5000" : ["SQ", "BiPlaneAcquisitionSequence"], <add> "6010" : ["US", "RepresentativeFrameNumber"], <add> "6020" : ["US", "FrameNumbersOfInterest"], <add> "6022" : ["LO", "FrameOfInterestDescription"], <add> "6023" : ["CS", "FrameOfInterestType"], <add> "6030" : ["US", "MaskPointers"], <add> "6040" : ["US", "RWavePointer"], <add> "6100" : ["SQ", "MaskSubtractionSequence"], <add> "6101" : ["CS", "MaskOperation"], <add> "6102" : ["US", "ApplicableFrameRange"], <add> "6110" : ["US", "MaskFrameNumbers"], <add> "6112" : ["US", "ContrastFrameAveraging"], <add> "6114" : ["FL", "MaskSubPixelShift"], <add> "6120" : ["SS", "TIDOffset"], <add> "6190" : ["ST", "MaskOperationExplanation"], <add> "7FE0" : ["UT", "PixelDataProviderURL"], <add> "9001" : ["UL", "DataPointRows"], <add> "9002" : ["UL", "DataPointColumns"], <add> "9003" : ["CS", "SignalDomainColumns"], <add> "9099" : ["US", "LargestMonochromePixelValue"], <add> "9108" : ["CS", "DataRepresentation"], <add> "9110" : ["SQ", "PixelMeasuresSequence"], <add> "9132" : ["SQ", "FrameVOILUTSequence"], <add> "9145" : ["SQ", "PixelValueTransformationSequence"], <add> "9235" : ["CS", "SignalDomainRows"], <add> "9411" : ["FL", "DisplayFilterPercentage"], <add> "9415" : ["SQ", "FramePixelShiftSequence"], <add> "9416" : ["US", "SubtractionItemID"], <add> "9422" : ["SQ", "PixelIntensityRelationshipLUTSequence"], <add> "9443" : ["SQ", "FramePixelDataPropertiesSequence"], <add> "9444" : ["CS", "GeometricalProperties"], <add> "9445" : ["FL", "GeometricMaximumDistortion"], <add> "9446" : ["CS", "ImageProcessingApplied"], <add> "9454" : ["CS", "MaskSelectionMode"], <add> "9474" : ["CS", "LUTFunction"], <add> "9478" : ["FL", "MaskVisibilityPercentage"], <add> "9501" : ["SQ", "PixelShiftSequence"], <add> "9502" : ["SQ", "RegionPixelShiftSequence"], <add> "9503" : ["SS", "VerticesOfTheRegion"], <add> "9505" : ["SQ", "MultiFramePresentationSequence"], <add> "9506" : ["US", "PixelShiftFrameRange"], <add> "9507" : ["US", "LUTFrameRange"], <add> "9520" : ["DS", "ImageToEquipmentMappingMatrix"], <add> "9537" : ["CS", "EquipmentCoordinateSystemIdentification"] <add> }, <add> "0032" : { <add> "000A" : ["CS", "StudyStatusID"], <add> "000C" : ["CS", "StudyPriorityID"], <add> "0012" : ["LO", "StudyIDIssuer"], <add> "0032" : ["DA", "StudyVerifiedDate"], <add> "0033" : ["TM", "StudyVerifiedTime"], <add> "0034" : ["DA", "StudyReadDate"], <add> "0035" : ["TM", "StudyReadTime"], <add> "1000" : ["DA", "ScheduledStudyStartDate"], <add> "1001" : ["TM", "ScheduledStudyStartTime"], <add> "1010" : ["DA", "ScheduledStudyStopDate"], <add> "1011" : ["TM", "ScheduledStudyStopTime"], <add> "1020" : ["LO", "ScheduledStudyLocation"], <add> "1021" : ["AE", "ScheduledStudyLocationAETitle"], <add> "1030" : ["LO", "ReasonForStudy"], <add> "1031" : ["SQ", "RequestingPhysicianIdentificationSequence"], <add> "1032" : ["PN", "RequestingPhysician"], <add> "1033" : ["LO", "RequestingService"], <add> "1034" : ["SQ", "RequestingServiceCodeSequence"], <add> "1040" : ["DA", "StudyArrivalDate"], <add> "1041" : ["TM", "StudyArrivalTime"], <add> "1050" : ["DA", "StudyCompletionDate"], <add> "1051" : ["TM", "StudyCompletionTime"], <add> "1055" : ["CS", "StudyComponentStatusID"], <add> "1060" : ["LO", "RequestedProcedureDescription"], <add> "1064" : ["SQ", "RequestedProcedureCodeSequence"], <add> "1070" : ["LO", "RequestedContrastAgent"], <add> "4000" : ["LT", "StudyComments"] <add> }, <add> "0038" : { <add> "0004" : ["SQ", "ReferencedPatientAliasSequence"], <add> "0008" : ["CS", "VisitStatusID"], <add> "0010" : ["LO", "AdmissionID"], <add> "0011" : ["LO", "IssuerOfAdmissionID"], <add> "0014" : ["SQ", "IssuerOfAdmissionIDSequence"], <add> "0016" : ["LO", "RouteOfAdmissions"], <add> "001A" : ["DA", "ScheduledAdmissionDate"], <add> "001B" : ["TM", "ScheduledAdmissionTime"], <add> "001C" : ["DA", "ScheduledDischargeDate"], <add> "001D" : ["TM", "ScheduledDischargeTime"], <add> "001E" : ["LO", "ScheduledPatientInstitutionResidence"], <add> "0020" : ["DA", "AdmittingDate"], <add> "0021" : ["TM", "AdmittingTime"], <add> "0030" : ["DA", "DischargeDate"], <add> "0032" : ["TM", "DischargeTime"], <add> "0040" : ["LO", "DischargeDiagnosisDescription"], <add> "0044" : ["SQ", "DischargeDiagnosisCodeSequence"], <add> "0050" : ["LO", "SpecialNeeds"], <add> "0060" : ["LO", "ServiceEpisodeID"], <add> "0061" : ["LO", "IssuerOfServiceEpisodeID"], <add> "0062" : ["LO", "ServiceEpisodeDescription"], <add> "0064" : ["SQ", "IssuerOfServiceEpisodeIDSequence"], <add> "0100" : ["SQ", "PertinentDocumentsSequence"], <add> "0300" : ["LO", "CurrentPatientLocation"], <add> "0400" : ["LO", "PatientInstitutionResidence"], <add> "0500" : ["LO", "PatientState"], <add> "0502" : ["SQ", "PatientClinicalTrialParticipationSequence"], <add> "4000" : ["LT", "VisitComments"] <add> }, <add> "003A" : { <add> "0004" : ["CS", "WaveformOriginality"], <add> "0005" : ["US", "NumberOfWaveformChannels"], <add> "0010" : ["UL", "NumberOfWaveformSamples"], <add> "001A" : ["DS", "SamplingFrequency"], <add> "0020" : ["SH", "MultiplexGroupLabel"], <add> "0200" : ["SQ", "ChannelDefinitionSequence"], <add> "0202" : ["IS", "WaveformChannelNumber"], <add> "0203" : ["SH", "ChannelLabel"], <add> "0205" : ["CS", "ChannelStatus"], <add> "0208" : ["SQ", "ChannelSourceSequence"], <add> "0209" : ["SQ", "ChannelSourceModifiersSequence"], <add> "020A" : ["SQ", "SourceWaveformSequence"], <add> "020C" : ["LO", "ChannelDerivationDescription"], <add> "0210" : ["DS", "ChannelSensitivity"], <add> "0211" : ["SQ", "ChannelSensitivityUnitsSequence"], <add> "0212" : ["DS", "ChannelSensitivityCorrectionFactor"], <add> "0213" : ["DS", "ChannelBaseline"], <add> "0214" : ["DS", "ChannelTimeSkew"], <add> "0215" : ["DS", "ChannelSampleSkew"], <add> "0218" : ["DS", "ChannelOffset"], <add> "021A" : ["US", "WaveformBitsStored"], <add> "0220" : ["DS", "FilterLowFrequency"], <add> "0221" : ["DS", "FilterHighFrequency"], <add> "0222" : ["DS", "NotchFilterFrequency"], <add> "0223" : ["DS", "NotchFilterBandwidth"], <add> "0230" : ["FL", "WaveformDataDisplayScale"], <add> "0231" : ["US", "WaveformDisplayBackgroundCIELabValue"], <add> "0240" : ["SQ", "WaveformPresentationGroupSequence"], <add> "0241" : ["US", "PresentationGroupNumber"], <add> "0242" : ["SQ", "ChannelDisplaySequence"], <add> "0244" : ["US", "ChannelRecommendedDisplayCIELabValue"], <add> "0245" : ["FL", "ChannelPosition"], <add> "0246" : ["CS", "DisplayShadingFlag"], <add> "0247" : ["FL", "FractionalChannelDisplayScale"], <add> "0248" : ["FL", "AbsoluteChannelDisplayScale"], <add> "0300" : ["SQ", "MultiplexedAudioChannelsDescriptionCodeSequence"], <add> "0301" : ["IS", "ChannelIdentificationCode"], <add> "0302" : ["CS", "ChannelMode"] <add> }, <add> "0040" : { <add> "0001" : ["AE", "ScheduledStationAETitle"], <add> "0002" : ["DA", "ScheduledProcedureStepStartDate"], <add> "0003" : ["TM", "ScheduledProcedureStepStartTime"], <add> "0004" : ["DA", "ScheduledProcedureStepEndDate"], <add> "0005" : ["TM", "ScheduledProcedureStepEndTime"], <add> "0006" : ["PN", "ScheduledPerformingPhysicianName"], <add> "0007" : ["LO", "ScheduledProcedureStepDescription"], <add> "0008" : ["SQ", "ScheduledProtocolCodeSequence"], <add> "0009" : ["SH", "ScheduledProcedureStepID"], <add> "000A" : ["SQ", "StageCodeSequence"], <add> "000B" : ["SQ", "ScheduledPerformingPhysicianIdentificationSequence"], <add> "0010" : ["SH", "ScheduledStationName"], <add> "0011" : ["SH", "ScheduledProcedureStepLocation"], <add> "0012" : ["LO", "PreMedication"], <add> "0020" : ["CS", "ScheduledProcedureStepStatus"], <add> "0026" : ["SQ", "OrderPlacerIdentifierSequence"], <add> "0027" : ["SQ", "OrderFillerIdentifierSequence"], <add> "0031" : ["UT", "LocalNamespaceEntityID"], <add> "0032" : ["UT", "UniversalEntityID"], <add> "0033" : ["CS", "UniversalEntityIDType"], <add> "0035" : ["CS", "IdentifierTypeCode"], <add> "0036" : ["SQ", "AssigningFacilitySequence"], <add> "0039" : ["SQ", "AssigningJurisdictionCodeSequence"], <add> "003A" : ["SQ", "AssigningAgencyOrDepartmentCodeSequence"], <add> "0100" : ["SQ", "ScheduledProcedureStepSequence"], <add> "0220" : ["SQ", "ReferencedNonImageCompositeSOPInstanceSequence"], <add> "0241" : ["AE", "PerformedStationAETitle"], <add> "0242" : ["SH", "PerformedStationName"], <add> "0243" : ["SH", "PerformedLocation"], <add> "0244" : ["DA", "PerformedProcedureStepStartDate"], <add> "0245" : ["TM", "PerformedProcedureStepStartTime"], <add> "0250" : ["DA", "PerformedProcedureStepEndDate"], <add> "0251" : ["TM", "PerformedProcedureStepEndTime"], <add> "0252" : ["CS", "PerformedProcedureStepStatus"], <add> "0253" : ["SH", "PerformedProcedureStepID"], <add> "0254" : ["LO", "PerformedProcedureStepDescription"], <add> "0255" : ["LO", "PerformedProcedureTypeDescription"], <add> "0260" : ["SQ", "PerformedProtocolCodeSequence"], <add> "0261" : ["CS", "PerformedProtocolType"], <add> "0270" : ["SQ", "ScheduledStepAttributesSequence"], <add> "0275" : ["SQ", "RequestAttributesSequence"], <add> "0280" : ["ST", "CommentsOnThePerformedProcedureStep"], <add> "0281" : ["SQ", "PerformedProcedureStepDiscontinuationReasonCodeSequence"], <add> "0293" : ["SQ", "QuantitySequence"], <add> "0294" : ["DS", "Quantity"], <add> "0295" : ["SQ", "MeasuringUnitsSequence"], <add> "0296" : ["SQ", "BillingItemSequence"], <add> "0300" : ["US", "TotalTimeOfFluoroscopy"], <add> "0301" : ["US", "TotalNumberOfExposures"], <add> "0302" : ["US", "EntranceDose"], <add> "0303" : ["US", "ExposedArea"], <add> "0306" : ["DS", "DistanceSourceToEntrance"], <add> "0307" : ["DS", "DistanceSourceToSupport"], <add> "030E" : ["SQ", "ExposureDoseSequence"], <add> "0310" : ["ST", "CommentsOnRadiationDose"], <add> "0312" : ["DS", "XRayOutput"], <add> "0314" : ["DS", "HalfValueLayer"], <add> "0316" : ["DS", "OrganDose"], <add> "0318" : ["CS", "OrganExposed"], <add> "0320" : ["SQ", "BillingProcedureStepSequence"], <add> "0321" : ["SQ", "FilmConsumptionSequence"], <add> "0324" : ["SQ", "BillingSuppliesAndDevicesSequence"], <add> "0330" : ["SQ", "ReferencedProcedureStepSequence"], <add> "0340" : ["SQ", "PerformedSeriesSequence"], <add> "0400" : ["LT", "CommentsOnTheScheduledProcedureStep"], <add> "0440" : ["SQ", "ProtocolContextSequence"], <add> "0441" : ["SQ", "ContentItemModifierSequence"], <add> "0500" : ["SQ", "ScheduledSpecimenSequence"], <add> "050A" : ["LO", "SpecimenAccessionNumber"], <add> "0512" : ["LO", "ContainerIdentifier"], <add> "0513" : ["SQ", "IssuerOfTheContainerIdentifierSequence"], <add> "0515" : ["SQ", "AlternateContainerIdentifierSequence"], <add> "0518" : ["SQ", "ContainerTypeCodeSequence"], <add> "051A" : ["LO", "ContainerDescription"], <add> "0520" : ["SQ", "ContainerComponentSequence"], <add> "0550" : ["SQ", "SpecimenSequence"], <add> "0551" : ["LO", "SpecimenIdentifier"], <add> "0552" : ["SQ", "SpecimenDescriptionSequenceTrial"], <add> "0553" : ["ST", "SpecimenDescriptionTrial"], <add> "0554" : ["UI", "SpecimenUID"], <add> "0555" : ["SQ", "AcquisitionContextSequence"], <add> "0556" : ["ST", "AcquisitionContextDescription"], <add> "059A" : ["SQ", "SpecimenTypeCodeSequence"], <add> "0560" : ["SQ", "SpecimenDescriptionSequence"], <add> "0562" : ["SQ", "IssuerOfTheSpecimenIdentifierSequence"], <add> "0600" : ["LO", "SpecimenShortDescription"], <add> "0602" : ["UT", "SpecimenDetailedDescription"], <add> "0610" : ["SQ", "SpecimenPreparationSequence"], <add> "0612" : ["SQ", "SpecimenPreparationStepContentItemSequence"], <add> "0620" : ["SQ", "SpecimenLocalizationContentItemSequence"], <add> "06FA" : ["LO", "SlideIdentifier"], <add> "071A" : ["SQ", "ImageCenterPointCoordinatesSequence"], <add> "072A" : ["DS", "XOffsetInSlideCoordinateSystem"], <add> "073A" : ["DS", "YOffsetInSlideCoordinateSystem"], <add> "074A" : ["DS", "ZOffsetInSlideCoordinateSystem"], <add> "08D8" : ["SQ", "PixelSpacingSequence"], <add> "08DA" : ["SQ", "CoordinateSystemAxisCodeSequence"], <add> "08EA" : ["SQ", "MeasurementUnitsCodeSequence"], <add> "09F8" : ["SQ", "VitalStainCodeSequenceTrial"], <add> "1001" : ["SH", "RequestedProcedureID"], <add> "1002" : ["LO", "ReasonForTheRequestedProcedure"], <add> "1003" : ["SH", "RequestedProcedurePriority"], <add> "1004" : ["LO", "PatientTransportArrangements"], <add> "1005" : ["LO", "RequestedProcedureLocation"], <add> "1006" : ["SH", "PlacerOrderNumberProcedure"], <add> "1007" : ["SH", "FillerOrderNumberProcedure"], <add> "1008" : ["LO", "ConfidentialityCode"], <add> "1009" : ["SH", "ReportingPriority"], <add> "100A" : ["SQ", "ReasonForRequestedProcedureCodeSequence"], <add> "1010" : ["PN", "NamesOfIntendedRecipientsOfResults"], <add> "1011" : ["SQ", "IntendedRecipientsOfResultsIdentificationSequence"], <add> "1012" : ["SQ", "ReasonForPerformedProcedureCodeSequence"], <add> "1060" : ["LO", "RequestedProcedureDescriptionTrial"], <add> "1101" : ["SQ", "PersonIdentificationCodeSequence"], <add> "1102" : ["ST", "PersonAddress"], <add> "1103" : ["LO", "PersonTelephoneNumbers"], <add> "1400" : ["LT", "RequestedProcedureComments"], <add> "2001" : ["LO", "ReasonForTheImagingServiceRequest"], <add> "2004" : ["DA", "IssueDateOfImagingServiceRequest"], <add> "2005" : ["TM", "IssueTimeOfImagingServiceRequest"], <add> "2006" : ["SH", "PlacerOrderNumberImagingServiceRequestRetired"], <add> "2007" : ["SH", "FillerOrderNumberImagingServiceRequestRetired"], <add> "2008" : ["PN", "OrderEnteredBy"], <add> "2009" : ["SH", "OrderEntererLocation"], <add> "2010" : ["SH", "OrderCallbackPhoneNumber"], <add> "2016" : ["LO", "PlacerOrderNumberImagingServiceRequest"], <add> "2017" : ["LO", "FillerOrderNumberImagingServiceRequest"], <add> "2400" : ["LT", "ImagingServiceRequestComments"], <add> "3001" : ["LO", "ConfidentialityConstraintOnPatientDataDescription"], <add> "4001" : ["CS", "GeneralPurposeScheduledProcedureStepStatus"], <add> "4002" : ["CS", "GeneralPurposePerformedProcedureStepStatus"], <add> "4003" : ["CS", "GeneralPurposeScheduledProcedureStepPriority"], <add> "4004" : ["SQ", "ScheduledProcessingApplicationsCodeSequence"], <add> "4005" : ["DT", "ScheduledProcedureStepStartDateTime"], <add> "4006" : ["CS", "MultipleCopiesFlag"], <add> "4007" : ["SQ", "PerformedProcessingApplicationsCodeSequence"], <add> "4009" : ["SQ", "HumanPerformerCodeSequence"], <add> "4010" : ["DT", "ScheduledProcedureStepModificationDateTime"], <add> "4011" : ["DT", "ExpectedCompletionDateTime"], <add> "4015" : ["SQ", "ResultingGeneralPurposePerformedProcedureStepsSequence"], <add> "4016" : ["SQ", "ReferencedGeneralPurposeScheduledProcedureStepSequence"], <add> "4018" : ["SQ", "ScheduledWorkitemCodeSequence"], <add> "4019" : ["SQ", "PerformedWorkitemCodeSequence"], <add> "4020" : ["CS", "InputAvailabilityFlag"], <add> "4021" : ["SQ", "InputInformationSequence"], <add> "4022" : ["SQ", "RelevantInformationSequence"], <add> "4023" : ["UI", "ReferencedGeneralPurposeScheduledProcedureStepTransactionUID"], <add> "4025" : ["SQ", "ScheduledStationNameCodeSequence"], <add> "4026" : ["SQ", "ScheduledStationClassCodeSequence"], <add> "4027" : ["SQ", "ScheduledStationGeographicLocationCodeSequence"], <add> "4028" : ["SQ", "PerformedStationNameCodeSequence"], <add> "4029" : ["SQ", "PerformedStationClassCodeSequence"], <add> "4030" : ["SQ", "PerformedStationGeographicLocationCodeSequence"], <add> "4031" : ["SQ", "RequestedSubsequentWorkitemCodeSequence"], <add> "4032" : ["SQ", "NonDICOMOutputCodeSequence"], <add> "4033" : ["SQ", "OutputInformationSequence"], <add> "4034" : ["SQ", "ScheduledHumanPerformersSequence"], <add> "4035" : ["SQ", "ActualHumanPerformersSequence"], <add> "4036" : ["LO", "HumanPerformerOrganization"], <add> "4037" : ["PN", "HumanPerformerName"], <add> "4040" : ["CS", "RawDataHandling"], <add> "4041" : ["CS", "InputReadinessState"], <add> "4050" : ["DT", "PerformedProcedureStepStartDateTime"], <add> "4051" : ["DT", "PerformedProcedureStepEndDateTime"], <add> "4052" : ["DT", "ProcedureStepCancellationDateTime"], <add> "8302" : ["DS", "EntranceDoseInmGy"], <add> "9094" : ["SQ", "ReferencedImageRealWorldValueMappingSequence"], <add> "9096" : ["SQ", "RealWorldValueMappingSequence"], <add> "9098" : ["SQ", "PixelValueMappingCodeSequence"], <add> "9210" : ["SH", "LUTLabel"], <add> "9211" : ["SS", "RealWorldValueLastValueMapped"], <add> "9212" : ["FD", "RealWorldValueLUTData"], <add> "9216" : ["SS", "RealWorldValueFirstValueMapped"], <add> "9224" : ["FD", "RealWorldValueIntercept"], <add> "9225" : ["FD", "RealWorldValueSlope"], <add> "A007" : ["CS", "FindingsFlagTrial"], <add> "A010" : ["CS", "RelationshipType"], <add> "A020" : ["SQ", "FindingsSequenceTrial"], <add> "A021" : ["UI", "FindingsGroupUIDTrial"], <add> "A022" : ["UI", "ReferencedFindingsGroupUIDTrial"], <add> "A023" : ["DA", "FindingsGroupRecordingDateTrial"], <add> "A024" : ["TM", "FindingsGroupRecordingTimeTrial"], <add> "A026" : ["SQ", "FindingsSourceCategoryCodeSequenceTrial"], <add> "A027" : ["LO", "VerifyingOrganization"], <add> "A028" : ["SQ", "DocumentingOrganizationIdentifierCodeSequenceTrial"], <add> "A030" : ["DT", "VerificationDateTime"], <add> "A032" : ["DT", "ObservationDateTime"], <add> "A040" : ["CS", "ValueType"], <add> "A043" : ["SQ", "ConceptNameCodeSequence"], <add> "A047" : ["LO", "MeasurementPrecisionDescriptionTrial"], <add> "A050" : ["CS", "ContinuityOfContent"], <add> "A057" : ["CS", "UrgencyOrPriorityAlertsTrial"], <add> "A060" : ["LO", "SequencingIndicatorTrial"], <add> "A066" : ["SQ", "DocumentIdentifierCodeSequenceTrial"], <add> "A067" : ["PN", "DocumentAuthorTrial"], <add> "A068" : ["SQ", "DocumentAuthorIdentifierCodeSequenceTrial"], <add> "A070" : ["SQ", "IdentifierCodeSequenceTrial"], <add> "A073" : ["SQ", "VerifyingObserverSequence"], <add> "A074" : ["OB", "ObjectBinaryIdentifierTrial"], <add> "A075" : ["PN", "VerifyingObserverName"], <add> "A076" : ["SQ", "DocumentingObserverIdentifierCodeSequenceTrial"], <add> "A078" : ["SQ", "AuthorObserverSequence"], <add> "A07A" : ["SQ", "ParticipantSequence"], <add> "A07C" : ["SQ", "CustodialOrganizationSequence"], <add> "A080" : ["CS", "ParticipationType"], <add> "A082" : ["DT", "ParticipationDateTime"], <add> "A084" : ["CS", "ObserverType"], <add> "A085" : ["SQ", "ProcedureIdentifierCodeSequenceTrial"], <add> "A088" : ["SQ", "VerifyingObserverIdentificationCodeSequence"], <add> "A089" : ["OB", "ObjectDirectoryBinaryIdentifierTrial"], <add> "A090" : ["SQ", "EquivalentCDADocumentSequence"], <add> "A0B0" : ["US", "ReferencedWaveformChannels"], <add> "A110" : ["DA", "DateOfDocumentOrVerbalTransactionTrial"], <add> "A112" : ["TM", "TimeOfDocumentCreationOrVerbalTransactionTrial"], <add> "A120" : ["DT", "DateTime"], <add> "A121" : ["DA", "Date"], <add> "A122" : ["TM", "Time"], <add> "A123" : ["PN", "PersonName"], <add> "A124" : ["UI", "UID"], <add> "A125" : ["CS", "ReportStatusIDTrial"], <add> "A130" : ["CS", "TemporalRangeType"], <add> "A132" : ["UL", "ReferencedSamplePositions"], <add> "A136" : ["US", "ReferencedFrameNumbers"], <add> "A138" : ["DS", "ReferencedTimeOffsets"], <add> "A13A" : ["DT", "ReferencedDateTime"], <add> "A160" : ["UT", "TextValue"], <add> "A167" : ["SQ", "ObservationCategoryCodeSequenceTrial"], <add> "A168" : ["SQ", "ConceptCodeSequence"], <add> "A16A" : ["ST", "BibliographicCitationTrial"], <add> "A170" : ["SQ", "PurposeOfReferenceCodeSequence"], <add> "A171" : ["UI", "ObservationUIDTrial"], <add> "A172" : ["UI", "ReferencedObservationUIDTrial"], <add> "A173" : ["CS", "ReferencedObservationClassTrial"], <add> "A174" : ["CS", "ReferencedObjectObservationClassTrial"], <add> "A180" : ["US", "AnnotationGroupNumber"], <add> "A192" : ["DA", "ObservationDateTrial"], <add> "A193" : ["TM", "ObservationTimeTrial"], <add> "A194" : ["CS", "MeasurementAutomationTrial"], <add> "A195" : ["SQ", "ModifierCodeSequence"], <add> "A224" : ["ST", "IdentificationDescriptionTrial"], <add> "A290" : ["CS", "CoordinatesSetGeometricTypeTrial"], <add> "A296" : ["SQ", "AlgorithmCodeSequenceTrial"], <add> "A297" : ["ST", "AlgorithmDescriptionTrial"], <add> "A29A" : ["SL", "PixelCoordinatesSetTrial"], <add> "A300" : ["SQ", "MeasuredValueSequence"], <add> "A301" : ["SQ", "NumericValueQualifierCodeSequence"], <add> "A307" : ["PN", "CurrentObserverTrial"], <add> "A30A" : ["DS", "NumericValue"], <add> "A313" : ["SQ", "ReferencedAccessionSequenceTrial"], <add> "A33A" : ["ST", "ReportStatusCommentTrial"], <add> "A340" : ["SQ", "ProcedureContextSequenceTrial"], <add> "A352" : ["PN", "VerbalSourceTrial"], <add> "A353" : ["ST", "AddressTrial"], <add> "A354" : ["LO", "TelephoneNumberTrial"], <add> "A358" : ["SQ", "VerbalSourceIdentifierCodeSequenceTrial"], <add> "A360" : ["SQ", "PredecessorDocumentsSequence"], <add> "A370" : ["SQ", "ReferencedRequestSequence"], <add> "A372" : ["SQ", "PerformedProcedureCodeSequence"], <add> "A375" : ["SQ", "CurrentRequestedProcedureEvidenceSequence"], <add> "A380" : ["SQ", "ReportDetailSequenceTrial"], <add> "A385" : ["SQ", "PertinentOtherEvidenceSequence"], <add> "A390" : ["SQ", "HL7StructuredDocumentReferenceSequence"], <add> "A402" : ["UI", "ObservationSubjectUIDTrial"], <add> "A403" : ["CS", "ObservationSubjectClassTrial"], <add> "A404" : ["SQ", "ObservationSubjectTypeCodeSequenceTrial"], <add> "A491" : ["CS", "CompletionFlag"], <add> "A492" : ["LO", "CompletionFlagDescription"], <add> "A493" : ["CS", "VerificationFlag"], <add> "A494" : ["CS", "ArchiveRequested"], <add> "A496" : ["CS", "PreliminaryFlag"], <add> "A504" : ["SQ", "ContentTemplateSequence"], <add> "A525" : ["SQ", "IdenticalDocumentsSequence"], <add> "A600" : ["CS", "ObservationSubjectContextFlagTrial"], <add> "A601" : ["CS", "ObserverContextFlagTrial"], <add> "A603" : ["CS", "ProcedureContextFlagTrial"], <add> "A730" : ["SQ", "ContentSequence"], <add> "A731" : ["SQ", "RelationshipSequenceTrial"], <add> "A732" : ["SQ", "RelationshipTypeCodeSequenceTrial"], <add> "A744" : ["SQ", "LanguageCodeSequenceTrial"], <add> "A992" : ["ST", "UniformResourceLocatorTrial"], <add> "B020" : ["SQ", "WaveformAnnotationSequence"], <add> "DB00" : ["CS", "TemplateIdentifier"], <add> "DB06" : ["DT", "TemplateVersion"], <add> "DB07" : ["DT", "TemplateLocalVersion"], <add> "DB0B" : ["CS", "TemplateExtensionFlag"], <add> "DB0C" : ["UI", "TemplateExtensionOrganizationUID"], <add> "DB0D" : ["UI", "TemplateExtensionCreatorUID"], <add> "DB73" : ["UL", "ReferencedContentItemIdentifier"], <add> "E001" : ["ST", "HL7InstanceIdentifier"], <add> "E004" : ["DT", "HL7DocumentEffectiveTime"], <add> "E006" : ["SQ", "HL7DocumentTypeCodeSequence"], <add> "E008" : ["SQ", "DocumentClassCodeSequence"], <add> "E010" : ["UT", "RetrieveURI"], <add> "E011" : ["UI", "RetrieveLocationUID"], <add> "E020" : ["CS", "TypeOfInstances"], <add> "E021" : ["SQ", "DICOMRetrievalSequence"], <add> "E022" : ["SQ", "DICOMMediaRetrievalSequence"], <add> "E023" : ["SQ", "WADORetrievalSequence"], <add> "E024" : ["SQ", "XDSRetrievalSequence"], <add> "E030" : ["UI", "RepositoryUniqueID"], <add> "E031" : ["UI", "HomeCommunityID"] <add> }, <add> "0042" : { <add> "0010" : ["ST", "DocumentTitle"], <add> "0011" : ["OB", "EncapsulatedDocument"], <add> "0012" : ["LO", "MIMETypeOfEncapsulatedDocument"], <add> "0013" : ["SQ", "SourceInstanceSequence"], <add> "0014" : ["LO", "ListOfMIMETypes"] <add> }, <add> "0044" : { <add> "0001" : ["ST", "ProductPackageIdentifier"], <add> "0002" : ["CS", "SubstanceAdministrationApproval"], <add> "0003" : ["LT", "ApprovalStatusFurtherDescription"], <add> "0004" : ["DT", "ApprovalStatusDateTime"], <add> "0007" : ["SQ", "ProductTypeCodeSequence"], <add> "0008" : ["LO", "ProductName"], <add> "0009" : ["LT", "ProductDescription"], <add> "000A" : ["LO", "ProductLotIdentifier"], <add> "000B" : ["DT", "ProductExpirationDateTime"], <add> "0010" : ["DT", "SubstanceAdministrationDateTime"], <add> "0011" : ["LO", "SubstanceAdministrationNotes"], <add> "0012" : ["LO", "SubstanceAdministrationDeviceID"], <add> "0013" : ["SQ", "ProductParameterSequence"], <add> "0019" : ["SQ", "SubstanceAdministrationParameterSequence"] <add> }, <add> "0046" : { <add> "0012" : ["LO", "LensDescription"], <add> "0014" : ["SQ", "RightLensSequence"], <add> "0015" : ["SQ", "LeftLensSequence"], <add> "0016" : ["SQ", "UnspecifiedLateralityLensSequence"], <add> "0018" : ["SQ", "CylinderSequence"], <add> "0028" : ["SQ", "PrismSequence"], <add> "0030" : ["FD", "HorizontalPrismPower"], <add> "0032" : ["CS", "HorizontalPrismBase"], <add> "0034" : ["FD", "VerticalPrismPower"], <add> "0036" : ["CS", "VerticalPrismBase"], <add> "0038" : ["CS", "LensSegmentType"], <add> "0040" : ["FD", "OpticalTransmittance"], <add> "0042" : ["FD", "ChannelWidth"], <add> "0044" : ["FD", "PupilSize"], <add> "0046" : ["FD", "CornealSize"], <add> "0050" : ["SQ", "AutorefractionRightEyeSequence"], <add> "0052" : ["SQ", "AutorefractionLeftEyeSequence"], <add> "0060" : ["FD", "DistancePupillaryDistance"], <add> "0062" : ["FD", "NearPupillaryDistance"], <add> "0063" : ["FD", "IntermediatePupillaryDistance"], <add> "0064" : ["FD", "OtherPupillaryDistance"], <add> "0070" : ["SQ", "KeratometryRightEyeSequence"], <add> "0071" : ["SQ", "KeratometryLeftEyeSequence"], <add> "0074" : ["SQ", "SteepKeratometricAxisSequence"], <add> "0075" : ["FD", "RadiusOfCurvature"], <add> "0076" : ["FD", "KeratometricPower"], <add> "0077" : ["FD", "KeratometricAxis"], <add> "0080" : ["SQ", "FlatKeratometricAxisSequence"], <add> "0092" : ["CS", "BackgroundColor"], <add> "0094" : ["CS", "Optotype"], <add> "0095" : ["CS", "OptotypePresentation"], <add> "0097" : ["SQ", "SubjectiveRefractionRightEyeSequence"], <add> "0098" : ["SQ", "SubjectiveRefractionLeftEyeSequence"], <add> "0100" : ["SQ", "AddNearSequence"], <add> "0101" : ["SQ", "AddIntermediateSequence"], <add> "0102" : ["SQ", "AddOtherSequence"], <add> "0104" : ["FD", "AddPower"], <add> "0106" : ["FD", "ViewingDistance"], <add> "0121" : ["SQ", "VisualAcuityTypeCodeSequence"], <add> "0122" : ["SQ", "VisualAcuityRightEyeSequence"], <add> "0123" : ["SQ", "VisualAcuityLeftEyeSequence"], <add> "0124" : ["SQ", "VisualAcuityBothEyesOpenSequence"], <add> "0125" : ["CS", "ViewingDistanceType"], <add> "0135" : ["SS", "VisualAcuityModifiers"], <add> "0137" : ["FD", "DecimalVisualAcuity"], <add> "0139" : ["LO", "OptotypeDetailedDefinition"], <add> "0145" : ["SQ", "ReferencedRefractiveMeasurementsSequence"], <add> "0146" : ["FD", "SpherePower"], <add> "0147" : ["FD", "CylinderPower"] <add> }, <add> "0048" : { <add> "0001" : ["FL", "ImagedVolumeWidth"], <add> "0002" : ["FL", "ImagedVolumeHeight"], <add> "0003" : ["FL", "ImagedVolumeDepth"], <add> "0006" : ["UL", "TotalPixelMatrixColumns"], <add> "0007" : ["UL", "TotalPixelMatrixRows"], <add> "0008" : ["SQ", "TotalPixelMatrixOriginSequence"], <add> "0010" : ["CS", "SpecimenLabelInImage"], <add> "0011" : ["CS", "FocusMethod"], <add> "0012" : ["CS", "ExtendedDepthOfField"], <add> "0013" : ["US", "NumberOfFocalPlanes"], <add> "0014" : ["FL", "DistanceBetweenFocalPlanes"], <add> "0015" : ["US", "RecommendedAbsentPixelCIELabValue"], <add> "0100" : ["SQ", "IlluminatorTypeCodeSequence"], <add> "0102" : ["DS", "ImageOrientationSlide"], <add> "0105" : ["SQ", "OpticalPathSequence"], <add> "0106" : ["SH", "OpticalPathIdentifier"], <add> "0107" : ["ST", "OpticalPathDescription"], <add> "0108" : ["SQ", "IlluminationColorCodeSequence"], <add> "0110" : ["SQ", "SpecimenReferenceSequence"], <add> "0111" : ["DS", "CondenserLensPower"], <add> "0112" : ["DS", "ObjectiveLensPower"], <add> "0113" : ["DS", "ObjectiveLensNumericalAperture"], <add> "0120" : ["SQ", "PaletteColorLookupTableSequence"], <add> "0200" : ["SQ", "ReferencedImageNavigationSequence"], <add> "0201" : ["US", "TopLeftHandCornerOfLocalizerArea"], <add> "0202" : ["US", "BottomRightHandCornerOfLocalizerArea"], <add> "0207" : ["SQ", "OpticalPathIdentificationSequence"], <add> "021A" : ["SQ", "PlanePositionSlideSequence"], <add> "021E" : ["SL", "RowPositionInTotalImagePixelMatrix"], <add> "021F" : ["SL", "ColumnPositionInTotalImagePixelMatrix"], <add> "0301" : ["CS", "PixelOriginInterpretation"] <add> }, <add> "0050" : { <add> "0004" : ["CS", "CalibrationImage"], <add> "0010" : ["SQ", "DeviceSequence"], <add> "0012" : ["SQ", "ContainerComponentTypeCodeSequence"], <add> "0013" : ["FD", "ContainerComponentThickness"], <add> "0014" : ["DS", "DeviceLength"], <add> "0015" : ["FD", "ContainerComponentWidth"], <add> "0016" : ["DS", "DeviceDiameter"], <add> "0017" : ["CS", "DeviceDiameterUnits"], <add> "0018" : ["DS", "DeviceVolume"], <add> "0019" : ["DS", "InterMarkerDistance"], <add> "001A" : ["CS", "ContainerComponentMaterial"], <add> "001B" : ["LO", "ContainerComponentID"], <add> "001C" : ["FD", "ContainerComponentLength"], <add> "001D" : ["FD", "ContainerComponentDiameter"], <add> "001E" : ["LO", "ContainerComponentDescription"], <add> "0020" : ["LO", "DeviceDescription"] <add> }, <add> "0052" : { <add> "0001" : ["FL", "ContrastBolusIngredientPercentByVolume"], <add> "0002" : ["FD", "OCTFocalDistance"], <add> "0003" : ["FD", "BeamSpotSize"], <add> "0004" : ["FD", "EffectiveRefractiveIndex"], <add> "0006" : ["CS", "OCTAcquisitionDomain"], <add> "0007" : ["FD", "OCTOpticalCenterWavelength"], <add> "0008" : ["FD", "AxialResolution"], <add> "0009" : ["FD", "RangingDepth"], <add> "0011" : ["FD", "ALineRate"], <add> "0012" : ["US", "ALinesPerFrame"], <add> "0013" : ["FD", "CatheterRotationalRate"], <add> "0014" : ["FD", "ALinePixelSpacing"], <add> "0016" : ["SQ", "ModeOfPercutaneousAccessSequence"], <add> "0025" : ["SQ", "IntravascularOCTFrameTypeSequence"], <add> "0026" : ["CS", "OCTZOffsetApplied"], <add> "0027" : ["SQ", "IntravascularFrameContentSequence"], <add> "0028" : ["FD", "IntravascularLongitudinalDistance"], <add> "0029" : ["SQ", "IntravascularOCTFrameContentSequence"], <add> "0030" : ["SS", "OCTZOffsetCorrection"], <add> "0031" : ["CS", "CatheterDirectionOfRotation"], <add> "0033" : ["FD", "SeamLineLocation"], <add> "0034" : ["FD", "FirstALineLocation"], <add> "0036" : ["US", "SeamLineIndex"], <add> "0038" : ["US", "NumberOfPaddedAlines"], <add> "0039" : ["CS", "InterpolationType"], <add> "003A" : ["CS", "RefractiveIndexApplied"] <add> }, <add> "0054" : { <add> "0010" : ["US", "EnergyWindowVector"], <add> "0011" : ["US", "NumberOfEnergyWindows"], <add> "0012" : ["SQ", "EnergyWindowInformationSequence"], <add> "0013" : ["SQ", "EnergyWindowRangeSequence"], <add> "0014" : ["DS", "EnergyWindowLowerLimit"], <add> "0015" : ["DS", "EnergyWindowUpperLimit"], <add> "0016" : ["SQ", "RadiopharmaceuticalInformationSequence"], <add> "0017" : ["IS", "ResidualSyringeCounts"], <add> "0018" : ["SH", "EnergyWindowName"], <add> "0020" : ["US", "DetectorVector"], <add> "0021" : ["US", "NumberOfDetectors"], <add> "0022" : ["SQ", "DetectorInformationSequence"], <add> "0030" : ["US", "PhaseVector"], <add> "0031" : ["US", "NumberOfPhases"], <add> "0032" : ["SQ", "PhaseInformationSequence"], <add> "0033" : ["US", "NumberOfFramesInPhase"], <add> "0036" : ["IS", "PhaseDelay"], <add> "0038" : ["IS", "PauseBetweenFrames"], <add> "0039" : ["CS", "PhaseDescription"], <add> "0050" : ["US", "RotationVector"], <add> "0051" : ["US", "NumberOfRotations"], <add> "0052" : ["SQ", "RotationInformationSequence"], <add> "0053" : ["US", "NumberOfFramesInRotation"], <add> "0060" : ["US", "RRIntervalVector"], <add> "0061" : ["US", "NumberOfRRIntervals"], <add> "0062" : ["SQ", "GatedInformationSequence"], <add> "0063" : ["SQ", "DataInformationSequence"], <add> "0070" : ["US", "TimeSlotVector"], <add> "0071" : ["US", "NumberOfTimeSlots"], <add> "0072" : ["SQ", "TimeSlotInformationSequence"], <add> "0073" : ["DS", "TimeSlotTime"], <add> "0080" : ["US", "SliceVector"], <add> "0081" : ["US", "NumberOfSlices"], <add> "0090" : ["US", "AngularViewVector"], <add> "0100" : ["US", "TimeSliceVector"], <add> "0101" : ["US", "NumberOfTimeSlices"], <add> "0200" : ["DS", "StartAngle"], <add> "0202" : ["CS", "TypeOfDetectorMotion"], <add> "0210" : ["IS", "TriggerVector"], <add> "0211" : ["US", "NumberOfTriggersInPhase"], <add> "0220" : ["SQ", "ViewCodeSequence"], <add> "0222" : ["SQ", "ViewModifierCodeSequence"], <add> "0300" : ["SQ", "RadionuclideCodeSequence"], <add> "0302" : ["SQ", "AdministrationRouteCodeSequence"], <add> "0304" : ["SQ", "RadiopharmaceuticalCodeSequence"], <add> "0306" : ["SQ", "CalibrationDataSequence"], <add> "0308" : ["US", "EnergyWindowNumber"], <add> "0400" : ["SH", "ImageID"], <add> "0410" : ["SQ", "PatientOrientationCodeSequence"], <add> "0412" : ["SQ", "PatientOrientationModifierCodeSequence"], <add> "0414" : ["SQ", "PatientGantryRelationshipCodeSequence"], <add> "0500" : ["CS", "SliceProgressionDirection"], <add> "1000" : ["CS", "SeriesType"], <add> "1001" : ["CS", "Units"], <add> "1002" : ["CS", "CountsSource"], <add> "1004" : ["CS", "ReprojectionMethod"], <add> "1006" : ["CS", "SUVType"], <add> "1100" : ["CS", "RandomsCorrectionMethod"], <add> "1101" : ["LO", "AttenuationCorrectionMethod"], <add> "1102" : ["CS", "DecayCorrection"], <add> "1103" : ["LO", "ReconstructionMethod"], <add> "1104" : ["LO", "DetectorLinesOfResponseUsed"], <add> "1105" : ["LO", "ScatterCorrectionMethod"], <add> "1200" : ["DS", "AxialAcceptance"], <add> "1201" : ["IS", "AxialMash"], <add> "1202" : ["IS", "TransverseMash"], <add> "1203" : ["DS", "DetectorElementSize"], <add> "1210" : ["DS", "CoincidenceWindowWidth"], <add> "1220" : ["CS", "SecondaryCountsType"], <add> "1300" : ["DS", "FrameReferenceTime"], <add> "1310" : ["IS", "PrimaryPromptsCountsAccumulated"], <add> "1311" : ["IS", "SecondaryCountsAccumulated"], <add> "1320" : ["DS", "SliceSensitivityFactor"], <add> "1321" : ["DS", "DecayFactor"], <add> "1322" : ["DS", "DoseCalibrationFactor"], <add> "1323" : ["DS", "ScatterFractionFactor"], <add> "1324" : ["DS", "DeadTimeFactor"], <add> "1330" : ["US", "ImageIndex"], <add> "1400" : ["CS", "CountsIncluded"], <add> "1401" : ["CS", "DeadTimeCorrectionFlag"] <add> }, <add> "0060" : { <add> "3000" : ["SQ", "HistogramSequence"], <add> "3002" : ["US", "HistogramNumberOfBins"], <add> "3004" : ["SS", "HistogramFirstBinValue"], <add> "3006" : ["SS", "HistogramLastBinValue"], <add> "3008" : ["US", "HistogramBinWidth"], <add> "3010" : ["LO", "HistogramExplanation"], <add> "3020" : ["UL", "HistogramData"] <add> }, <add> "0062" : { <add> "0001" : ["CS", "SegmentationType"], <add> "0002" : ["SQ", "SegmentSequence"], <add> "0003" : ["SQ", "SegmentedPropertyCategoryCodeSequence"], <add> "0004" : ["US", "SegmentNumber"], <add> "0005" : ["LO", "SegmentLabel"], <add> "0006" : ["ST", "SegmentDescription"], <add> "0008" : ["CS", "SegmentAlgorithmType"], <add> "0009" : ["LO", "SegmentAlgorithmName"], <add> "000A" : ["SQ", "SegmentIdentificationSequence"], <add> "000B" : ["US", "ReferencedSegmentNumber"], <add> "000C" : ["US", "RecommendedDisplayGrayscaleValue"], <add> "000D" : ["US", "RecommendedDisplayCIELabValue"], <add> "000E" : ["US", "MaximumFractionalValue"], <add> "000F" : ["SQ", "SegmentedPropertyTypeCodeSequence"], <add> "0010" : ["CS", "SegmentationFractionalType"] <add> }, <add> "0064" : { <add> "0002" : ["SQ", "DeformableRegistrationSequence"], <add> "0003" : ["UI", "SourceFrameOfReferenceUID"], <add> "0005" : ["SQ", "DeformableRegistrationGridSequence"], <add> "0007" : ["UL", "GridDimensions"], <add> "0008" : ["FD", "GridResolution"], <add> "0009" : ["OF", "VectorGridData"], <add> "000F" : ["SQ", "PreDeformationMatrixRegistrationSequence"], <add> "0010" : ["SQ", "PostDeformationMatrixRegistrationSequence"] <add> }, <add> "0066" : { <add> "0001" : ["UL", "NumberOfSurfaces"], <add> "0002" : ["SQ", "SurfaceSequence"], <add> "0003" : ["UL", "SurfaceNumber"], <add> "0004" : ["LT", "SurfaceComments"], <add> "0009" : ["CS", "SurfaceProcessing"], <add> "000A" : ["FL", "SurfaceProcessingRatio"], <add> "000B" : ["LO", "SurfaceProcessingDescription"], <add> "000C" : ["FL", "RecommendedPresentationOpacity"], <add> "000D" : ["CS", "RecommendedPresentationType"], <add> "000E" : ["CS", "FiniteVolume"], <add> "0010" : ["CS", "Manifold"], <add> "0011" : ["SQ", "SurfacePointsSequence"], <add> "0012" : ["SQ", "SurfacePointsNormalsSequence"], <add> "0013" : ["SQ", "SurfaceMeshPrimitivesSequence"], <add> "0015" : ["UL", "NumberOfSurfacePoints"], <add> "0016" : ["OF", "PointCoordinatesData"], <add> "0017" : ["FL", "PointPositionAccuracy"], <add> "0018" : ["FL", "MeanPointDistance"], <add> "0019" : ["FL", "MaximumPointDistance"], <add> "001A" : ["FL", "PointsBoundingBoxCoordinates"], <add> "001B" : ["FL", "AxisOfRotation"], <add> "001C" : ["FL", "CenterOfRotation"], <add> "001E" : ["UL", "NumberOfVectors"], <add> "001F" : ["US", "VectorDimensionality"], <add> "0020" : ["FL", "VectorAccuracy"], <add> "0021" : ["OF", "VectorCoordinateData"], <add> "0023" : ["OW", "TrianglePointIndexList"], <add> "0024" : ["OW", "EdgePointIndexList"], <add> "0025" : ["OW", "VertexPointIndexList"], <add> "0026" : ["SQ", "TriangleStripSequence"], <add> "0027" : ["SQ", "TriangleFanSequence"], <add> "0028" : ["SQ", "LineSequence"], <add> "0029" : ["OW", "PrimitivePointIndexList"], <add> "002A" : ["UL", "SurfaceCount"], <add> "002B" : ["SQ", "ReferencedSurfaceSequence"], <add> "002C" : ["UL", "ReferencedSurfaceNumber"], <add> "002D" : ["SQ", "SegmentSurfaceGenerationAlgorithmIdentificationSequence"], <add> "002E" : ["SQ", "SegmentSurfaceSourceInstanceSequence"], <add> "002F" : ["SQ", "AlgorithmFamilyCodeSequence"], <add> "0030" : ["SQ", "AlgorithmNameCodeSequence"], <add> "0031" : ["LO", "AlgorithmVersion"], <add> "0032" : ["LT", "AlgorithmParameters"], <add> "0034" : ["SQ", "FacetSequence"], <add> "0035" : ["SQ", "SurfaceProcessingAlgorithmIdentificationSequence"], <add> "0036" : ["LO", "AlgorithmName"] <add> }, <add> "0068" : { <add> "6210" : ["LO", "ImplantSize"], <add> "6221" : ["LO", "ImplantTemplateVersion"], <add> "6222" : ["SQ", "ReplacedImplantTemplateSequence"], <add> "6223" : ["CS", "ImplantType"], <add> "6224" : ["SQ", "DerivationImplantTemplateSequence"], <add> "6225" : ["SQ", "OriginalImplantTemplateSequence"], <add> "6226" : ["DT", "EffectiveDateTime"], <add> "6230" : ["SQ", "ImplantTargetAnatomySequence"], <add> "6260" : ["SQ", "InformationFromManufacturerSequence"], <add> "6265" : ["SQ", "NotificationFromManufacturerSequence"], <add> "6270" : ["DT", "InformationIssueDateTime"], <add> "6280" : ["ST", "InformationSummary"], <add> "62A0" : ["SQ", "ImplantRegulatoryDisapprovalCodeSequence"], <add> "62A5" : ["FD", "OverallTemplateSpatialTolerance"], <add> "62C0" : ["SQ", "HPGLDocumentSequence"], <add> "62D0" : ["US", "HPGLDocumentID"], <add> "62D5" : ["LO", "HPGLDocumentLabel"], <add> "62E0" : ["SQ", "ViewOrientationCodeSequence"], <add> "62F0" : ["FD", "ViewOrientationModifier"], <add> "62F2" : ["FD", "HPGLDocumentScaling"], <add> "6300" : ["OB", "HPGLDocument"], <add> "6310" : ["US", "HPGLContourPenNumber"], <add> "6320" : ["SQ", "HPGLPenSequence"], <add> "6330" : ["US", "HPGLPenNumber"], <add> "6340" : ["LO", "HPGLPenLabel"], <add> "6345" : ["ST", "HPGLPenDescription"], <add> "6346" : ["FD", "RecommendedRotationPoint"], <add> "6347" : ["FD", "BoundingRectangle"], <add> "6350" : ["US", "ImplantTemplate3DModelSurfaceNumber"], <add> "6360" : ["SQ", "SurfaceModelDescriptionSequence"], <add> "6380" : ["LO", "SurfaceModelLabel"], <add> "6390" : ["FD", "SurfaceModelScalingFactor"], <add> "63A0" : ["SQ", "MaterialsCodeSequence"], <add> "63A4" : ["SQ", "CoatingMaterialsCodeSequence"], <add> "63A8" : ["SQ", "ImplantTypeCodeSequence"], <add> "63AC" : ["SQ", "FixationMethodCodeSequence"], <add> "63B0" : ["SQ", "MatingFeatureSetsSequence"], <add> "63C0" : ["US", "MatingFeatureSetID"], <add> "63D0" : ["LO", "MatingFeatureSetLabel"], <add> "63E0" : ["SQ", "MatingFeatureSequence"], <add> "63F0" : ["US", "MatingFeatureID"], <add> "6400" : ["SQ", "MatingFeatureDegreeOfFreedomSequence"], <add> "6410" : ["US", "DegreeOfFreedomID"], <add> "6420" : ["CS", "DegreeOfFreedomType"], <add> "6430" : ["SQ", "TwoDMatingFeatureCoordinatesSequence"], <add> "6440" : ["US", "ReferencedHPGLDocumentID"], <add> "6450" : ["FD", "TwoDMatingPoint"], <add> "6460" : ["FD", "TwoDMatingAxes"], <add> "6470" : ["SQ", "TwoDDegreeOfFreedomSequence"], <add> "6490" : ["FD", "ThreeDDegreeOfFreedomAxis"], <add> "64A0" : ["FD", "RangeOfFreedom"], <add> "64C0" : ["FD", "ThreeDMatingPoint"], <add> "64D0" : ["FD", "ThreeDMatingAxes"], <add> "64F0" : ["FD", "TwoDDegreeOfFreedomAxis"], <add> "6500" : ["SQ", "PlanningLandmarkPointSequence"], <add> "6510" : ["SQ", "PlanningLandmarkLineSequence"], <add> "6520" : ["SQ", "PlanningLandmarkPlaneSequence"], <add> "6530" : ["US", "PlanningLandmarkID"], <add> "6540" : ["LO", "PlanningLandmarkDescription"], <add> "6545" : ["SQ", "PlanningLandmarkIdentificationCodeSequence"], <add> "6550" : ["SQ", "TwoDPointCoordinatesSequence"], <add> "6560" : ["FD", "TwoDPointCoordinates"], <add> "6590" : ["FD", "ThreeDPointCoordinates"], <add> "65A0" : ["SQ", "TwoDLineCoordinatesSequence"], <add> "65B0" : ["FD", "TwoDLineCoordinates"], <add> "65D0" : ["FD", "ThreeDLineCoordinates"], <add> "65E0" : ["SQ", "TwoDPlaneCoordinatesSequence"], <add> "65F0" : ["FD", "TwoDPlaneIntersection"], <add> "6610" : ["FD", "ThreeDPlaneOrigin"], <add> "6620" : ["FD", "ThreeDPlaneNormal"] <add> }, <add> "0070" : { <add> "0001" : ["SQ", "GraphicAnnotationSequence"], <add> "0002" : ["CS", "GraphicLayer"], <add> "0003" : ["CS", "BoundingBoxAnnotationUnits"], <add> "0004" : ["CS", "AnchorPointAnnotationUnits"], <add> "0005" : ["CS", "GraphicAnnotationUnits"], <add> "0006" : ["ST", "UnformattedTextValue"], <add> "0008" : ["SQ", "TextObjectSequence"], <add> "0009" : ["SQ", "GraphicObjectSequence"], <add> "0010" : ["FL", "BoundingBoxTopLeftHandCorner"], <add> "0011" : ["FL", "BoundingBoxBottomRightHandCorner"], <add> "0012" : ["CS", "BoundingBoxTextHorizontalJustification"], <add> "0014" : ["FL", "AnchorPoint"], <add> "0015" : ["CS", "AnchorPointVisibility"], <add> "0020" : ["US", "GraphicDimensions"], <add> "0021" : ["US", "NumberOfGraphicPoints"], <add> "0022" : ["FL", "GraphicData"], <add> "0023" : ["CS", "GraphicType"], <add> "0024" : ["CS", "GraphicFilled"], <add> "0040" : ["IS", "ImageRotationRetired"], <add> "0041" : ["CS", "ImageHorizontalFlip"], <add> "0042" : ["US", "ImageRotation"], <add> "0050" : ["US", "DisplayedAreaTopLeftHandCornerTrial"], <add> "0051" : ["US", "DisplayedAreaBottomRightHandCornerTrial"], <add> "0052" : ["SL", "DisplayedAreaTopLeftHandCorner"], <add> "0053" : ["SL", "DisplayedAreaBottomRightHandCorner"], <add> "005A" : ["SQ", "DisplayedAreaSelectionSequence"], <add> "0060" : ["SQ", "GraphicLayerSequence"], <add> "0062" : ["IS", "GraphicLayerOrder"], <add> "0066" : ["US", "GraphicLayerRecommendedDisplayGrayscaleValue"], <add> "0067" : ["US", "GraphicLayerRecommendedDisplayRGBValue"], <add> "0068" : ["LO", "GraphicLayerDescription"], <add> "0080" : ["CS", "ContentLabel"], <add> "0081" : ["LO", "ContentDescription"], <add> "0082" : ["DA", "PresentationCreationDate"], <add> "0083" : ["TM", "PresentationCreationTime"], <add> "0084" : ["PN", "ContentCreatorName"], <add> "0086" : ["SQ", "ContentCreatorIdentificationCodeSequence"], <add> "0087" : ["SQ", "AlternateContentDescriptionSequence"], <add> "0100" : ["CS", "PresentationSizeMode"], <add> "0101" : ["DS", "PresentationPixelSpacing"], <add> "0102" : ["IS", "PresentationPixelAspectRatio"], <add> "0103" : ["FL", "PresentationPixelMagnificationRatio"], <add> "0207" : ["LO", "GraphicGroupLabel"], <add> "0208" : ["ST", "GraphicGroupDescription"], <add> "0209" : ["SQ", "CompoundGraphicSequence"], <add> "0226" : ["UL", "CompoundGraphicInstanceID"], <add> "0227" : ["LO", "FontName"], <add> "0228" : ["CS", "FontNameType"], <add> "0229" : ["LO", "CSSFontName"], <add> "0230" : ["FD", "RotationAngle"], <add> "0231" : ["SQ", "TextStyleSequence"], <add> "0232" : ["SQ", "LineStyleSequence"], <add> "0233" : ["SQ", "FillStyleSequence"], <add> "0234" : ["SQ", "GraphicGroupSequence"], <add> "0241" : ["US", "TextColorCIELabValue"], <add> "0242" : ["CS", "HorizontalAlignment"], <add> "0243" : ["CS", "VerticalAlignment"], <add> "0244" : ["CS", "ShadowStyle"], <add> "0245" : ["FL", "ShadowOffsetX"], <add> "0246" : ["FL", "ShadowOffsetY"], <add> "0247" : ["US", "ShadowColorCIELabValue"], <add> "0248" : ["CS", "Underlined"], <add> "0249" : ["CS", "Bold"], <add> "0250" : ["CS", "Italic"], <add> "0251" : ["US", "PatternOnColorCIELabValue"], <add> "0252" : ["US", "PatternOffColorCIELabValue"], <add> "0253" : ["FL", "LineThickness"], <add> "0254" : ["CS", "LineDashingStyle"], <add> "0255" : ["UL", "LinePattern"], <add> "0256" : ["OB", "FillPattern"], <add> "0257" : ["CS", "FillMode"], <add> "0258" : ["FL", "ShadowOpacity"], <add> "0261" : ["FL", "GapLength"], <add> "0262" : ["FL", "DiameterOfVisibility"], <add> "0273" : ["FL", "RotationPoint"], <add> "0274" : ["CS", "TickAlignment"], <add> "0278" : ["CS", "ShowTickLabel"], <add> "0279" : ["CS", "TickLabelAlignment"], <add> "0282" : ["CS", "CompoundGraphicUnits"], <add> "0284" : ["FL", "PatternOnOpacity"], <add> "0285" : ["FL", "PatternOffOpacity"], <add> "0287" : ["SQ", "MajorTicksSequence"], <add> "0288" : ["FL", "TickPosition"], <add> "0289" : ["SH", "TickLabel"], <add> "0294" : ["CS", "CompoundGraphicType"], <add> "0295" : ["UL", "GraphicGroupID"], <add> "0306" : ["CS", "ShapeType"], <add> "0308" : ["SQ", "RegistrationSequence"], <add> "0309" : ["SQ", "MatrixRegistrationSequence"], <add> "030A" : ["SQ", "MatrixSequence"], <add> "030C" : ["CS", "FrameOfReferenceTransformationMatrixType"], <add> "030D" : ["SQ", "RegistrationTypeCodeSequence"], <add> "030F" : ["ST", "FiducialDescription"], <add> "0310" : ["SH", "FiducialIdentifier"], <add> "0311" : ["SQ", "FiducialIdentifierCodeSequence"], <add> "0312" : ["FD", "ContourUncertaintyRadius"], <add> "0314" : ["SQ", "UsedFiducialsSequence"], <add> "0318" : ["SQ", "GraphicCoordinatesDataSequence"], <add> "031A" : ["UI", "FiducialUID"], <add> "031C" : ["SQ", "FiducialSetSequence"], <add> "031E" : ["SQ", "FiducialSequence"], <add> "0401" : ["US", "GraphicLayerRecommendedDisplayCIELabValue"], <add> "0402" : ["SQ", "BlendingSequence"], <add> "0403" : ["FL", "RelativeOpacity"], <add> "0404" : ["SQ", "ReferencedSpatialRegistrationSequence"], <add> "0405" : ["CS", "BlendingPosition"] <add> }, <add> "0072" : { <add> "0002" : ["SH", "HangingProtocolName"], <add> "0004" : ["LO", "HangingProtocolDescription"], <add> "0006" : ["CS", "HangingProtocolLevel"], <add> "0008" : ["LO", "HangingProtocolCreator"], <add> "000A" : ["DT", "HangingProtocolCreationDateTime"], <add> "000C" : ["SQ", "HangingProtocolDefinitionSequence"], <add> "000E" : ["SQ", "HangingProtocolUserIdentificationCodeSequence"], <add> "0010" : ["LO", "HangingProtocolUserGroupName"], <add> "0012" : ["SQ", "SourceHangingProtocolSequence"], <add> "0014" : ["US", "NumberOfPriorsReferenced"], <add> "0020" : ["SQ", "ImageSetsSequence"], <add> "0022" : ["SQ", "ImageSetSelectorSequence"], <add> "0024" : ["CS", "ImageSetSelectorUsageFlag"], <add> "0026" : ["AT", "SelectorAttribute"], <add> "0028" : ["US", "SelectorValueNumber"], <add> "0030" : ["SQ", "TimeBasedImageSetsSequence"], <add> "0032" : ["US", "ImageSetNumber"], <add> "0034" : ["CS", "ImageSetSelectorCategory"], <add> "0038" : ["US", "RelativeTime"], <add> "003A" : ["CS", "RelativeTimeUnits"], <add> "003C" : ["SS", "AbstractPriorValue"], <add> "003E" : ["SQ", "AbstractPriorCodeSequence"], <add> "0040" : ["LO", "ImageSetLabel"], <add> "0050" : ["CS", "SelectorAttributeVR"], <add> "0052" : ["AT", "SelectorSequencePointer"], <add> "0054" : ["LO", "SelectorSequencePointerPrivateCreator"], <add> "0056" : ["LO", "SelectorAttributePrivateCreator"], <add> "0060" : ["AT", "SelectorATValue"], <add> "0062" : ["CS", "SelectorCSValue"], <add> "0064" : ["IS", "SelectorISValue"], <add> "0066" : ["LO", "SelectorLOValue"], <add> "0068" : ["LT", "SelectorLTValue"], <add> "006A" : ["PN", "SelectorPNValue"], <add> "006C" : ["SH", "SelectorSHValue"], <add> "006E" : ["ST", "SelectorSTValue"], <add> "0070" : ["UT", "SelectorUTValue"], <add> "0072" : ["DS", "SelectorDSValue"], <add> "0074" : ["FD", "SelectorFDValue"], <add> "0076" : ["FL", "SelectorFLValue"], <add> "0078" : ["UL", "SelectorULValue"], <add> "007A" : ["US", "SelectorUSValue"], <add> "007C" : ["SL", "SelectorSLValue"], <add> "007E" : ["SS", "SelectorSSValue"], <add> "0080" : ["SQ", "SelectorCodeSequenceValue"], <add> "0100" : ["US", "NumberOfScreens"], <add> "0102" : ["SQ", "NominalScreenDefinitionSequence"], <add> "0104" : ["US", "NumberOfVerticalPixels"], <add> "0106" : ["US", "NumberOfHorizontalPixels"], <add> "0108" : ["FD", "DisplayEnvironmentSpatialPosition"], <add> "010A" : ["US", "ScreenMinimumGrayscaleBitDepth"], <add> "010C" : ["US", "ScreenMinimumColorBitDepth"], <add> "010E" : ["US", "ApplicationMaximumRepaintTime"], <add> "0200" : ["SQ", "DisplaySetsSequence"], <add> "0202" : ["US", "DisplaySetNumber"], <add> "0203" : ["LO", "DisplaySetLabel"], <add> "0204" : ["US", "DisplaySetPresentationGroup"], <add> "0206" : ["LO", "DisplaySetPresentationGroupDescription"], <add> "0208" : ["CS", "PartialDataDisplayHandling"], <add> "0210" : ["SQ", "SynchronizedScrollingSequence"], <add> "0212" : ["US", "DisplaySetScrollingGroup"], <add> "0214" : ["SQ", "NavigationIndicatorSequence"], <add> "0216" : ["US", "NavigationDisplaySet"], <add> "0218" : ["US", "ReferenceDisplaySets"], <add> "0300" : ["SQ", "ImageBoxesSequence"], <add> "0302" : ["US", "ImageBoxNumber"], <add> "0304" : ["CS", "ImageBoxLayoutType"], <add> "0306" : ["US", "ImageBoxTileHorizontalDimension"], <add> "0308" : ["US", "ImageBoxTileVerticalDimension"], <add> "0310" : ["CS", "ImageBoxScrollDirection"], <add> "0312" : ["CS", "ImageBoxSmallScrollType"], <add> "0314" : ["US", "ImageBoxSmallScrollAmount"], <add> "0316" : ["CS", "ImageBoxLargeScrollType"], <add> "0318" : ["US", "ImageBoxLargeScrollAmount"], <add> "0320" : ["US", "ImageBoxOverlapPriority"], <add> "0330" : ["FD", "CineRelativeToRealTime"], <add> "0400" : ["SQ", "FilterOperationsSequence"], <add> "0402" : ["CS", "FilterByCategory"], <add> "0404" : ["CS", "FilterByAttributePresence"], <add> "0406" : ["CS", "FilterByOperator"], <add> "0420" : ["US", "StructuredDisplayBackgroundCIELabValue"], <add> "0421" : ["US", "EmptyImageBoxCIELabValue"], <add> "0422" : ["SQ", "StructuredDisplayImageBoxSequence"], <add> "0424" : ["SQ", "StructuredDisplayTextBoxSequence"], <add> "0427" : ["SQ", "ReferencedFirstFrameSequence"], <add> "0430" : ["SQ", "ImageBoxSynchronizationSequence"], <add> "0432" : ["US", "SynchronizedImageBoxList"], <add> "0434" : ["CS", "TypeOfSynchronization"], <add> "0500" : ["CS", "BlendingOperationType"], <add> "0510" : ["CS", "ReformattingOperationType"], <add> "0512" : ["FD", "ReformattingThickness"], <add> "0514" : ["FD", "ReformattingInterval"], <add> "0516" : ["CS", "ReformattingOperationInitialViewDirection"], <add> "0520" : ["CS", "ThreeDRenderingType"], <add> "0600" : ["SQ", "SortingOperationsSequence"], <add> "0602" : ["CS", "SortByCategory"], <add> "0604" : ["CS", "SortingDirection"], <add> "0700" : ["CS", "DisplaySetPatientOrientation"], <add> "0702" : ["CS", "VOIType"], <add> "0704" : ["CS", "PseudoColorType"], <add> "0705" : ["SQ", "PseudoColorPaletteInstanceReferenceSequence"], <add> "0706" : ["CS", "ShowGrayscaleInverted"], <add> "0710" : ["CS", "ShowImageTrueSizeFlag"], <add> "0712" : ["CS", "ShowGraphicAnnotationFlag"], <add> "0714" : ["CS", "ShowPatientDemographicsFlag"], <add> "0716" : ["CS", "ShowAcquisitionTechniquesFlag"], <add> "0717" : ["CS", "DisplaySetHorizontalJustification"], <add> "0718" : ["CS", "DisplaySetVerticalJustification"] <add> }, <add> "0074" : { <add> "0120" : ["FD", "ContinuationStartMeterset"], <add> "0121" : ["FD", "ContinuationEndMeterset"], <add> "1000" : ["CS", "ProcedureStepState"], <add> "1002" : ["SQ", "ProcedureStepProgressInformationSequence"], <add> "1004" : ["DS", "ProcedureStepProgress"], <add> "1006" : ["ST", "ProcedureStepProgressDescription"], <add> "1008" : ["SQ", "ProcedureStepCommunicationsURISequence"], <add> "100A" : ["ST", "ContactURI"], <add> "100C" : ["LO", "ContactDisplayName"], <add> "100E" : ["SQ", "ProcedureStepDiscontinuationReasonCodeSequence"], <add> "1020" : ["SQ", "BeamTaskSequence"], <add> "1022" : ["CS", "BeamTaskType"], <add> "1024" : ["IS", "BeamOrderIndexTrial"], <add> "1026" : ["FD", "TableTopVerticalAdjustedPosition"], <add> "1027" : ["FD", "TableTopLongitudinalAdjustedPosition"], <add> "1028" : ["FD", "TableTopLateralAdjustedPosition"], <add> "102A" : ["FD", "PatientSupportAdjustedAngle"], <add> "102B" : ["FD", "TableTopEccentricAdjustedAngle"], <add> "102C" : ["FD", "TableTopPitchAdjustedAngle"], <add> "102D" : ["FD", "TableTopRollAdjustedAngle"], <add> "1030" : ["SQ", "DeliveryVerificationImageSequence"], <add> "1032" : ["CS", "VerificationImageTiming"], <add> "1034" : ["CS", "DoubleExposureFlag"], <add> "1036" : ["CS", "DoubleExposureOrdering"], <add> "1038" : ["DS", "DoubleExposureMetersetTrial"], <add> "103A" : ["DS", "DoubleExposureFieldDeltaTrial"], <add> "1040" : ["SQ", "RelatedReferenceRTImageSequence"], <add> "1042" : ["SQ", "GeneralMachineVerificationSequence"], <add> "1044" : ["SQ", "ConventionalMachineVerificationSequence"], <add> "1046" : ["SQ", "IonMachineVerificationSequence"], <add> "1048" : ["SQ", "FailedAttributesSequence"], <add> "104A" : ["SQ", "OverriddenAttributesSequence"], <add> "104C" : ["SQ", "ConventionalControlPointVerificationSequence"], <add> "104E" : ["SQ", "IonControlPointVerificationSequence"], <add> "1050" : ["SQ", "AttributeOccurrenceSequence"], <add> "1052" : ["AT", "AttributeOccurrencePointer"], <add> "1054" : ["UL", "AttributeItemSelector"], <add> "1056" : ["LO", "AttributeOccurrencePrivateCreator"], <add> "1057" : ["IS", "SelectorSequencePointerItems"], <add> "1200" : ["CS", "ScheduledProcedureStepPriority"], <add> "1202" : ["LO", "WorklistLabel"], <add> "1204" : ["LO", "ProcedureStepLabel"], <add> "1210" : ["SQ", "ScheduledProcessingParametersSequence"], <add> "1212" : ["SQ", "PerformedProcessingParametersSequence"], <add> "1216" : ["SQ", "UnifiedProcedureStepPerformedProcedureSequence"], <add> "1220" : ["SQ", "RelatedProcedureStepSequence"], <add> "1222" : ["LO", "ProcedureStepRelationshipType"], <add> "1224" : ["SQ", "ReplacedProcedureStepSequence"], <add> "1230" : ["LO", "DeletionLock"], <add> "1234" : ["AE", "ReceivingAE"], <add> "1236" : ["AE", "RequestingAE"], <add> "1238" : ["LT", "ReasonForCancellation"], <add> "1242" : ["CS", "SCPStatus"], <add> "1244" : ["CS", "SubscriptionListStatus"], <add> "1246" : ["CS", "UnifiedProcedureStepListStatus"], <add> "1324" : ["UL", "BeamOrderIndex"], <add> "1338" : ["FD", "DoubleExposureMeterset"], <add> "133A" : ["FD", "DoubleExposureFieldDelta"] <add> }, <add> "0076" : { <add> "0001" : ["LO", "ImplantAssemblyTemplateName"], <add> "0003" : ["LO", "ImplantAssemblyTemplateIssuer"], <add> "0006" : ["LO", "ImplantAssemblyTemplateVersion"], <add> "0008" : ["SQ", "ReplacedImplantAssemblyTemplateSequence"], <add> "000A" : ["CS", "ImplantAssemblyTemplateType"], <add> "000C" : ["SQ", "OriginalImplantAssemblyTemplateSequence"], <add> "000E" : ["SQ", "DerivationImplantAssemblyTemplateSequence"], <add> "0010" : ["SQ", "ImplantAssemblyTemplateTargetAnatomySequence"], <add> "0020" : ["SQ", "ProcedureTypeCodeSequence"], <add> "0030" : ["LO", "SurgicalTechnique"], <add> "0032" : ["SQ", "ComponentTypesSequence"], <add> "0034" : ["CS", "ComponentTypeCodeSequence"], <add> "0036" : ["CS", "ExclusiveComponentType"], <add> "0038" : ["CS", "MandatoryComponentType"], <add> "0040" : ["SQ", "ComponentSequence"], <add> "0055" : ["US", "ComponentID"], <add> "0060" : ["SQ", "ComponentAssemblySequence"], <add> "0070" : ["US", "Component1ReferencedID"], <add> "0080" : ["US", "Component1ReferencedMatingFeatureSetID"], <add> "0090" : ["US", "Component1ReferencedMatingFeatureID"], <add> "00A0" : ["US", "Component2ReferencedID"], <add> "00B0" : ["US", "Component2ReferencedMatingFeatureSetID"], <add> "00C0" : ["US", "Component2ReferencedMatingFeatureID"] <add> }, <add> "0078" : { <add> "0001" : ["LO", "ImplantTemplateGroupName"], <add> "0010" : ["ST", "ImplantTemplateGroupDescription"], <add> "0020" : ["LO", "ImplantTemplateGroupIssuer"], <add> "0024" : ["LO", "ImplantTemplateGroupVersion"], <add> "0026" : ["SQ", "ReplacedImplantTemplateGroupSequence"], <add> "0028" : ["SQ", "ImplantTemplateGroupTargetAnatomySequence"], <add> "002A" : ["SQ", "ImplantTemplateGroupMembersSequence"], <add> "002E" : ["US", "ImplantTemplateGroupMemberID"], <add> "0050" : ["FD", "ThreeDImplantTemplateGroupMemberMatchingPoint"], <add> "0060" : ["FD", "ThreeDImplantTemplateGroupMemberMatchingAxes"], <add> "0070" : ["SQ", "ImplantTemplateGroupMemberMatching2DCoordinatesSequence"], <add> "0090" : ["FD", "TwoDImplantTemplateGroupMemberMatchingPoint"], <add> "00A0" : ["FD", "TwoDImplantTemplateGroupMemberMatchingAxes"], <add> "00B0" : ["SQ", "ImplantTemplateGroupVariationDimensionSequence"], <add> "00B2" : ["LO", "ImplantTemplateGroupVariationDimensionName"], <add> "00B4" : ["SQ", "ImplantTemplateGroupVariationDimensionRankSequence"], <add> "00B6" : ["US", "ReferencedImplantTemplateGroupMemberID"], <add> "00B8" : ["US", "ImplantTemplateGroupVariationDimensionRank"] <add> }, <add> "0088" : { <add> "0130" : ["SH", "StorageMediaFileSetID"], <add> "0140" : ["UI", "StorageMediaFileSetUID"], <add> "0200" : ["SQ", "IconImageSequence"], <add> "0904" : ["LO", "TopicTitle"], <add> "0906" : ["ST", "TopicSubject"], <add> "0910" : ["LO", "TopicAuthor"], <add> "0912" : ["LO", "TopicKeywords"] <add> }, <add> "0100" : { <add> "0410" : ["CS", "SOPInstanceStatus"], <add> "0420" : ["DT", "SOPAuthorizationDateTime"], <add> "0424" : ["LT", "SOPAuthorizationComment"], <add> "0426" : ["LO", "AuthorizationEquipmentCertificationNumber"] <add> }, <add> "0400" : { <add> "0005" : ["US", "MACIDNumber"], <add> "0010" : ["UI", "MACCalculationTransferSyntaxUID"], <add> "0015" : ["CS", "MACAlgorithm"], <add> "0020" : ["AT", "DataElementsSigned"], <add> "0100" : ["UI", "DigitalSignatureUID"], <add> "0105" : ["DT", "DigitalSignatureDateTime"], <add> "0110" : ["CS", "CertificateType"], <add> "0115" : ["OB", "CertificateOfSigner"], <add> "0120" : ["OB", "Signature"], <add> "0305" : ["CS", "CertifiedTimestampType"], <add> "0310" : ["OB", "CertifiedTimestamp"], <add> "0401" : ["SQ", "DigitalSignaturePurposeCodeSequence"], <add> "0402" : ["SQ", "ReferencedDigitalSignatureSequence"], <add> "0403" : ["SQ", "ReferencedSOPInstanceMACSequence"], <add> "0404" : ["OB", "MAC"], <add> "0500" : ["SQ", "EncryptedAttributesSequence"], <add> "0510" : ["UI", "EncryptedContentTransferSyntaxUID"], <add> "0520" : ["OB", "EncryptedContent"], <add> "0550" : ["SQ", "ModifiedAttributesSequence"], <add> "0561" : ["SQ", "OriginalAttributesSequence"], <add> "0562" : ["DT", "AttributeModificationDateTime"], <add> "0563" : ["LO", "ModifyingSystem"], <add> "0564" : ["LO", "SourceOfPreviousValues"], <add> "0565" : ["CS", "ReasonForTheAttributeModification"] <add> }, <add> "2000" : { <add> "0010" : ["IS", "NumberOfCopies"], <add> "001E" : ["SQ", "PrinterConfigurationSequence"], <add> "0020" : ["CS", "PrintPriority"], <add> "0030" : ["CS", "MediumType"], <add> "0040" : ["CS", "FilmDestination"], <add> "0050" : ["LO", "FilmSessionLabel"], <add> "0060" : ["IS", "MemoryAllocation"], <add> "0061" : ["IS", "MaximumMemoryAllocation"], <add> "0062" : ["CS", "ColorImagePrintingFlag"], <add> "0063" : ["CS", "CollationFlag"], <add> "0065" : ["CS", "AnnotationFlag"], <add> "0067" : ["CS", "ImageOverlayFlag"], <add> "0069" : ["CS", "PresentationLUTFlag"], <add> "006A" : ["CS", "ImageBoxPresentationLUTFlag"], <add> "00A0" : ["US", "MemoryBitDepth"], <add> "00A1" : ["US", "PrintingBitDepth"], <add> "00A2" : ["SQ", "MediaInstalledSequence"], <add> "00A4" : ["SQ", "OtherMediaAvailableSequence"], <add> "00A8" : ["SQ", "SupportedImageDisplayFormatsSequence"], <add> "0500" : ["SQ", "ReferencedFilmBoxSequence"], <add> "0510" : ["SQ", "ReferencedStoredPrintSequence"] <add> }, <add> "2010" : { <add> "0010" : ["ST", "ImageDisplayFormat"], <add> "0030" : ["CS", "AnnotationDisplayFormatID"], <add> "0040" : ["CS", "FilmOrientation"], <add> "0050" : ["CS", "FilmSizeID"], <add> "0052" : ["CS", "PrinterResolutionID"], <add> "0054" : ["CS", "DefaultPrinterResolutionID"], <add> "0060" : ["CS", "MagnificationType"], <add> "0080" : ["CS", "SmoothingType"], <add> "00A6" : ["CS", "DefaultMagnificationType"], <add> "00A7" : ["CS", "OtherMagnificationTypesAvailable"], <add> "00A8" : ["CS", "DefaultSmoothingType"], <add> "00A9" : ["CS", "OtherSmoothingTypesAvailable"], <add> "0100" : ["CS", "BorderDensity"], <add> "0110" : ["CS", "EmptyImageDensity"], <add> "0120" : ["US", "MinDensity"], <add> "0130" : ["US", "MaxDensity"], <add> "0140" : ["CS", "Trim"], <add> "0150" : ["ST", "ConfigurationInformation"], <add> "0152" : ["LT", "ConfigurationInformationDescription"], <add> "0154" : ["IS", "MaximumCollatedFilms"], <add> "015E" : ["US", "Illumination"], <add> "0160" : ["US", "ReflectedAmbientLight"], <add> "0376" : ["DS", "PrinterPixelSpacing"], <add> "0500" : ["SQ", "ReferencedFilmSessionSequence"], <add> "0510" : ["SQ", "ReferencedImageBoxSequence"], <add> "0520" : ["SQ", "ReferencedBasicAnnotationBoxSequence"] <add> }, <add> "2020" : { <add> "0010" : ["US", "ImageBoxPosition"], <add> "0020" : ["CS", "Polarity"], <add> "0030" : ["DS", "RequestedImageSize"], <add> "0040" : ["CS", "RequestedDecimateCropBehavior"], <add> "0050" : ["CS", "RequestedResolutionID"], <add> "00A0" : ["CS", "RequestedImageSizeFlag"], <add> "00A2" : ["CS", "DecimateCropResult"], <add> "0110" : ["SQ", "BasicGrayscaleImageSequence"], <add> "0111" : ["SQ", "BasicColorImageSequence"], <add> "0130" : ["SQ", "ReferencedImageOverlayBoxSequence"], <add> "0140" : ["SQ", "ReferencedVOILUTBoxSequence"] <add> }, <add> "2030" : { <add> "0010" : ["US", "AnnotationPosition"], <add> "0020" : ["LO", "TextString"] <add> }, <add> "2040" : { <add> "0010" : ["SQ", "ReferencedOverlayPlaneSequence"], <add> "0011" : ["US", "ReferencedOverlayPlaneGroups"], <add> "0020" : ["SQ", "OverlayPixelDataSequence"], <add> "0060" : ["CS", "OverlayMagnificationType"], <add> "0070" : ["CS", "OverlaySmoothingType"], <add> "0072" : ["CS", "OverlayOrImageMagnification"], <add> "0074" : ["US", "MagnifyToNumberOfColumns"], <add> "0080" : ["CS", "OverlayForegroundDensity"], <add> "0082" : ["CS", "OverlayBackgroundDensity"], <add> "0090" : ["CS", "OverlayMode"], <add> "0100" : ["CS", "ThresholdDensity"], <add> "0500" : ["SQ", "ReferencedImageBoxSequenceRetired"] <add> }, <add> "2050" : { <add> "0010" : ["SQ", "PresentationLUTSequence"], <add> "0020" : ["CS", "PresentationLUTShape"], <add> "0500" : ["SQ", "ReferencedPresentationLUTSequence"] <add> }, <add> "2100" : { <add> "0010" : ["SH", "PrintJobID"], <add> "0020" : ["CS", "ExecutionStatus"], <add> "0030" : ["CS", "ExecutionStatusInfo"], <add> "0040" : ["DA", "CreationDate"], <add> "0050" : ["TM", "CreationTime"], <add> "0070" : ["AE", "Originator"], <add> "0140" : ["AE", "DestinationAE"], <add> "0160" : ["SH", "OwnerID"], <add> "0170" : ["IS", "NumberOfFilms"], <add> "0500" : ["SQ", "ReferencedPrintJobSequencePullStoredPrint"] <add> }, <add> "2110" : { <add> "0010" : ["CS", "PrinterStatus"], <add> "0020" : ["CS", "PrinterStatusInfo"], <add> "0030" : ["LO", "PrinterName"], <add> "0099" : ["SH", "PrintQueueID"] <add> }, <add> "2120" : { <add> "0010" : ["CS", "QueueStatus"], <add> "0050" : ["SQ", "PrintJobDescriptionSequence"], <add> "0070" : ["SQ", "ReferencedPrintJobSequence"] <add> }, <add> "2130" : { <add> "0010" : ["SQ", "PrintManagementCapabilitiesSequence"], <add> "0015" : ["SQ", "PrinterCharacteristicsSequence"], <add> "0030" : ["SQ", "FilmBoxContentSequence"], <add> "0040" : ["SQ", "ImageBoxContentSequence"], <add> "0050" : ["SQ", "AnnotationContentSequence"], <add> "0060" : ["SQ", "ImageOverlayBoxContentSequence"], <add> "0080" : ["SQ", "PresentationLUTContentSequence"], <add> "00A0" : ["SQ", "ProposedStudySequence"], <add> "00C0" : ["SQ", "OriginalImageSequence"] <add> }, <add> "2200" : { <add> "0001" : ["CS", "LabelUsingInformationExtractedFromInstances"], <add> "0002" : ["UT", "LabelText"], <add> "0003" : ["CS", "LabelStyleSelection"], <add> "0004" : ["LT", "MediaDisposition"], <add> "0005" : ["LT", "BarcodeValue"], <add> "0006" : ["CS", "BarcodeSymbology"], <add> "0007" : ["CS", "AllowMediaSplitting"], <add> "0008" : ["CS", "IncludeNonDICOMObjects"], <add> "0009" : ["CS", "IncludeDisplayApplication"], <add> "000A" : ["CS", "PreserveCompositeInstancesAfterMediaCreation"], <add> "000B" : ["US", "TotalNumberOfPiecesOfMediaCreated"], <add> "000C" : ["LO", "RequestedMediaApplicationProfile"], <add> "000D" : ["SQ", "ReferencedStorageMediaSequence"], <add> "000E" : ["AT", "FailureAttributes"], <add> "000F" : ["CS", "AllowLossyCompression"], <add> "0020" : ["CS", "RequestPriority"] <add> }, <add> "3002" : { <add> "0002" : ["SH", "RTImageLabel"], <add> "0003" : ["LO", "RTImageName"], <add> "0004" : ["ST", "RTImageDescription"], <add> "000A" : ["CS", "ReportedValuesOrigin"], <add> "000C" : ["CS", "RTImagePlane"], <add> "000D" : ["DS", "XRayImageReceptorTranslation"], <add> "000E" : ["DS", "XRayImageReceptorAngle"], <add> "0010" : ["DS", "RTImageOrientation"], <add> "0011" : ["DS", "ImagePlanePixelSpacing"], <add> "0012" : ["DS", "RTImagePosition"], <add> "0020" : ["SH", "RadiationMachineName"], <add> "0022" : ["DS", "RadiationMachineSAD"], <add> "0024" : ["DS", "RadiationMachineSSD"], <add> "0026" : ["DS", "RTImageSID"], <add> "0028" : ["DS", "SourceToReferenceObjectDistance"], <add> "0029" : ["IS", "FractionNumber"], <add> "0030" : ["SQ", "ExposureSequence"], <add> "0032" : ["DS", "MetersetExposure"], <add> "0034" : ["DS", "DiaphragmPosition"], <add> "0040" : ["SQ", "FluenceMapSequence"], <add> "0041" : ["CS", "FluenceDataSource"], <add> "0042" : ["DS", "FluenceDataScale"], <add> "0050" : ["SQ", "PrimaryFluenceModeSequence"], <add> "0051" : ["CS", "FluenceMode"], <add> "0052" : ["SH", "FluenceModeID"] <add> }, <add> "3004" : { <add> "0001" : ["CS", "DVHType"], <add> "0002" : ["CS", "DoseUnits"], <add> "0004" : ["CS", "DoseType"], <add> "0006" : ["LO", "DoseComment"], <add> "0008" : ["DS", "NormalizationPoint"], <add> "000A" : ["CS", "DoseSummationType"], <add> "000C" : ["DS", "GridFrameOffsetVector"], <add> "000E" : ["DS", "DoseGridScaling"], <add> "0010" : ["SQ", "RTDoseROISequence"], <add> "0012" : ["DS", "DoseValue"], <add> "0014" : ["CS", "TissueHeterogeneityCorrection"], <add> "0040" : ["DS", "DVHNormalizationPoint"], <add> "0042" : ["DS", "DVHNormalizationDoseValue"], <add> "0050" : ["SQ", "DVHSequence"], <add> "0052" : ["DS", "DVHDoseScaling"], <add> "0054" : ["CS", "DVHVolumeUnits"], <add> "0056" : ["IS", "DVHNumberOfBins"], <add> "0058" : ["DS", "DVHData"], <add> "0060" : ["SQ", "DVHReferencedROISequence"], <add> "0062" : ["CS", "DVHROIContributionType"], <add> "0070" : ["DS", "DVHMinimumDose"], <add> "0072" : ["DS", "DVHMaximumDose"], <add> "0074" : ["DS", "DVHMeanDose"] <add> }, <add> "3006" : { <add> "0002" : ["SH", "StructureSetLabel"], <add> "0004" : ["LO", "StructureSetName"], <add> "0006" : ["ST", "StructureSetDescription"], <add> "0008" : ["DA", "StructureSetDate"], <add> "0009" : ["TM", "StructureSetTime"], <add> "0010" : ["SQ", "ReferencedFrameOfReferenceSequence"], <add> "0012" : ["SQ", "RTReferencedStudySequence"], <add> "0014" : ["SQ", "RTReferencedSeriesSequence"], <add> "0016" : ["SQ", "ContourImageSequence"], <add> "0020" : ["SQ", "StructureSetROISequence"], <add> "0022" : ["IS", "ROINumber"], <add> "0024" : ["UI", "ReferencedFrameOfReferenceUID"], <add> "0026" : ["LO", "ROIName"], <add> "0028" : ["ST", "ROIDescription"], <add> "002A" : ["IS", "ROIDisplayColor"], <add> "002C" : ["DS", "ROIVolume"], <add> "0030" : ["SQ", "RTRelatedROISequence"], <add> "0033" : ["CS", "RTROIRelationship"], <add> "0036" : ["CS", "ROIGenerationAlgorithm"], <add> "0038" : ["LO", "ROIGenerationDescription"], <add> "0039" : ["SQ", "ROIContourSequence"], <add> "0040" : ["SQ", "ContourSequence"], <add> "0042" : ["CS", "ContourGeometricType"], <add> "0044" : ["DS", "ContourSlabThickness"], <add> "0045" : ["DS", "ContourOffsetVector"], <add> "0046" : ["IS", "NumberOfContourPoints"], <add> "0048" : ["IS", "ContourNumber"], <add> "0049" : ["IS", "AttachedContours"], <add> "0050" : ["DS", "ContourData"], <add> "0080" : ["SQ", "RTROIObservationsSequence"], <add> "0082" : ["IS", "ObservationNumber"], <add> "0084" : ["IS", "ReferencedROINumber"], <add> "0085" : ["SH", "ROIObservationLabel"], <add> "0086" : ["SQ", "RTROIIdentificationCodeSequence"], <add> "0088" : ["ST", "ROIObservationDescription"], <add> "00A0" : ["SQ", "RelatedRTROIObservationsSequence"], <add> "00A4" : ["CS", "RTROIInterpretedType"], <add> "00A6" : ["PN", "ROIInterpreter"], <add> "00B0" : ["SQ", "ROIPhysicalPropertiesSequence"], <add> "00B2" : ["CS", "ROIPhysicalProperty"], <add> "00B4" : ["DS", "ROIPhysicalPropertyValue"], <add> "00B6" : ["SQ", "ROIElementalCompositionSequence"], <add> "00B7" : ["US", "ROIElementalCompositionAtomicNumber"], <add> "00B8" : ["FL", "ROIElementalCompositionAtomicMassFraction"], <add> "00C0" : ["SQ", "FrameOfReferenceRelationshipSequence"], <add> "00C2" : ["UI", "RelatedFrameOfReferenceUID"], <add> "00C4" : ["CS", "FrameOfReferenceTransformationType"], <add> "00C6" : ["DS", "FrameOfReferenceTransformationMatrix"], <add> "00C8" : ["LO", "FrameOfReferenceTransformationComment"] <add> }, <add> "3008" : { <add> "0010" : ["SQ", "MeasuredDoseReferenceSequence"], <add> "0012" : ["ST", "MeasuredDoseDescription"], <add> "0014" : ["CS", "MeasuredDoseType"], <add> "0016" : ["DS", "MeasuredDoseValue"], <add> "0020" : ["SQ", "TreatmentSessionBeamSequence"], <add> "0021" : ["SQ", "TreatmentSessionIonBeamSequence"], <add> "0022" : ["IS", "CurrentFractionNumber"], <add> "0024" : ["DA", "TreatmentControlPointDate"], <add> "0025" : ["TM", "TreatmentControlPointTime"], <add> "002A" : ["CS", "TreatmentTerminationStatus"], <add> "002B" : ["SH", "TreatmentTerminationCode"], <add> "002C" : ["CS", "TreatmentVerificationStatus"], <add> "0030" : ["SQ", "ReferencedTreatmentRecordSequence"], <add> "0032" : ["DS", "SpecifiedPrimaryMeterset"], <add> "0033" : ["DS", "SpecifiedSecondaryMeterset"], <add> "0036" : ["DS", "DeliveredPrimaryMeterset"], <add> "0037" : ["DS", "DeliveredSecondaryMeterset"], <add> "003A" : ["DS", "SpecifiedTreatmentTime"], <add> "003B" : ["DS", "DeliveredTreatmentTime"], <add> "0040" : ["SQ", "ControlPointDeliverySequence"], <add> "0041" : ["SQ", "IonControlPointDeliverySequence"], <add> "0042" : ["DS", "SpecifiedMeterset"], <add> "0044" : ["DS", "DeliveredMeterset"], <add> "0045" : ["FL", "MetersetRateSet"], <add> "0046" : ["FL", "MetersetRateDelivered"], <add> "0047" : ["FL", "ScanSpotMetersetsDelivered"], <add> "0048" : ["DS", "DoseRateDelivered"], <add> "0050" : ["SQ", "TreatmentSummaryCalculatedDoseReferenceSequence"], <add> "0052" : ["DS", "CumulativeDoseToDoseReference"], <add> "0054" : ["DA", "FirstTreatmentDate"], <add> "0056" : ["DA", "MostRecentTreatmentDate"], <add> "005A" : ["IS", "NumberOfFractionsDelivered"], <add> "0060" : ["SQ", "OverrideSequence"], <add> "0061" : ["AT", "ParameterSequencePointer"], <add> "0062" : ["AT", "OverrideParameterPointer"], <add> "0063" : ["IS", "ParameterItemIndex"], <add> "0064" : ["IS", "MeasuredDoseReferenceNumber"], <add> "0065" : ["AT", "ParameterPointer"], <add> "0066" : ["ST", "OverrideReason"], <add> "0068" : ["SQ", "CorrectedParameterSequence"], <add> "006A" : ["FL", "CorrectionValue"], <add> "0070" : ["SQ", "CalculatedDoseReferenceSequence"], <add> "0072" : ["IS", "CalculatedDoseReferenceNumber"], <add> "0074" : ["ST", "CalculatedDoseReferenceDescription"], <add> "0076" : ["DS", "CalculatedDoseReferenceDoseValue"], <add> "0078" : ["DS", "StartMeterset"], <add> "007A" : ["DS", "EndMeterset"], <add> "0080" : ["SQ", "ReferencedMeasuredDoseReferenceSequence"], <add> "0082" : ["IS", "ReferencedMeasuredDoseReferenceNumber"], <add> "0090" : ["SQ", "ReferencedCalculatedDoseReferenceSequence"], <add> "0092" : ["IS", "ReferencedCalculatedDoseReferenceNumber"], <add> "00A0" : ["SQ", "BeamLimitingDeviceLeafPairsSequence"], <add> "00B0" : ["SQ", "RecordedWedgeSequence"], <add> "00C0" : ["SQ", "RecordedCompensatorSequence"], <add> "00D0" : ["SQ", "RecordedBlockSequence"], <add> "00E0" : ["SQ", "TreatmentSummaryMeasuredDoseReferenceSequence"], <add> "00F0" : ["SQ", "RecordedSnoutSequence"], <add> "00F2" : ["SQ", "RecordedRangeShifterSequence"], <add> "00F4" : ["SQ", "RecordedLateralSpreadingDeviceSequence"], <add> "00F6" : ["SQ", "RecordedRangeModulatorSequence"], <add> "0100" : ["SQ", "RecordedSourceSequence"], <add> "0105" : ["LO", "SourceSerialNumber"], <add> "0110" : ["SQ", "TreatmentSessionApplicationSetupSequence"], <add> "0116" : ["CS", "ApplicationSetupCheck"], <add> "0120" : ["SQ", "RecordedBrachyAccessoryDeviceSequence"], <add> "0122" : ["IS", "ReferencedBrachyAccessoryDeviceNumber"], <add> "0130" : ["SQ", "RecordedChannelSequence"], <add> "0132" : ["DS", "SpecifiedChannelTotalTime"], <add> "0134" : ["DS", "DeliveredChannelTotalTime"], <add> "0136" : ["IS", "SpecifiedNumberOfPulses"], <add> "0138" : ["IS", "DeliveredNumberOfPulses"], <add> "013A" : ["DS", "SpecifiedPulseRepetitionInterval"], <add> "013C" : ["DS", "DeliveredPulseRepetitionInterval"], <add> "0140" : ["SQ", "RecordedSourceApplicatorSequence"], <add> "0142" : ["IS", "ReferencedSourceApplicatorNumber"], <add> "0150" : ["SQ", "RecordedChannelShieldSequence"], <add> "0152" : ["IS", "ReferencedChannelShieldNumber"], <add> "0160" : ["SQ", "BrachyControlPointDeliveredSequence"], <add> "0162" : ["DA", "SafePositionExitDate"], <add> "0164" : ["TM", "SafePositionExitTime"], <add> "0166" : ["DA", "SafePositionReturnDate"], <add> "0168" : ["TM", "SafePositionReturnTime"], <add> "0200" : ["CS", "CurrentTreatmentStatus"], <add> "0202" : ["ST", "TreatmentStatusComment"], <add> "0220" : ["SQ", "FractionGroupSummarySequence"], <add> "0223" : ["IS", "ReferencedFractionNumber"], <add> "0224" : ["CS", "FractionGroupType"], <add> "0230" : ["CS", "BeamStopperPosition"], <add> "0240" : ["SQ", "FractionStatusSummarySequence"], <add> "0250" : ["DA", "TreatmentDate"], <add> "0251" : ["TM", "TreatmentTime"] <add> }, <add> "300A" : { <add> "0002" : ["SH", "RTPlanLabel"], <add> "0003" : ["LO", "RTPlanName"], <add> "0004" : ["ST", "RTPlanDescription"], <add> "0006" : ["DA", "RTPlanDate"], <add> "0007" : ["TM", "RTPlanTime"], <add> "0009" : ["LO", "TreatmentProtocols"], <add> "000A" : ["CS", "PlanIntent"], <add> "000B" : ["LO", "TreatmentSites"], <add> "000C" : ["CS", "RTPlanGeometry"], <add> "000E" : ["ST", "PrescriptionDescription"], <add> "0010" : ["SQ", "DoseReferenceSequence"], <add> "0012" : ["IS", "DoseReferenceNumber"], <add> "0013" : ["UI", "DoseReferenceUID"], <add> "0014" : ["CS", "DoseReferenceStructureType"], <add> "0015" : ["CS", "NominalBeamEnergyUnit"], <add> "0016" : ["LO", "DoseReferenceDescription"], <add> "0018" : ["DS", "DoseReferencePointCoordinates"], <add> "001A" : ["DS", "NominalPriorDose"], <add> "0020" : ["CS", "DoseReferenceType"], <add> "0021" : ["DS", "ConstraintWeight"], <add> "0022" : ["DS", "DeliveryWarningDose"], <add> "0023" : ["DS", "DeliveryMaximumDose"], <add> "0025" : ["DS", "TargetMinimumDose"], <add> "0026" : ["DS", "TargetPrescriptionDose"], <add> "0027" : ["DS", "TargetMaximumDose"], <add> "0028" : ["DS", "TargetUnderdoseVolumeFraction"], <add> "002A" : ["DS", "OrganAtRiskFullVolumeDose"], <add> "002B" : ["DS", "OrganAtRiskLimitDose"], <add> "002C" : ["DS", "OrganAtRiskMaximumDose"], <add> "002D" : ["DS", "OrganAtRiskOverdoseVolumeFraction"], <add> "0040" : ["SQ", "ToleranceTableSequence"], <add> "0042" : ["IS", "ToleranceTableNumber"], <add> "0043" : ["SH", "ToleranceTableLabel"], <add> "0044" : ["DS", "GantryAngleTolerance"], <add> "0046" : ["DS", "BeamLimitingDeviceAngleTolerance"], <add> "0048" : ["SQ", "BeamLimitingDeviceToleranceSequence"], <add> "004A" : ["DS", "BeamLimitingDevicePositionTolerance"], <add> "004B" : ["FL", "SnoutPositionTolerance"], <add> "004C" : ["DS", "PatientSupportAngleTolerance"], <add> "004E" : ["DS", "TableTopEccentricAngleTolerance"], <add> "004F" : ["FL", "TableTopPitchAngleTolerance"], <add> "0050" : ["FL", "TableTopRollAngleTolerance"], <add> "0051" : ["DS", "TableTopVerticalPositionTolerance"], <add> "0052" : ["DS", "TableTopLongitudinalPositionTolerance"], <add> "0053" : ["DS", "TableTopLateralPositionTolerance"], <add> "0055" : ["CS", "RTPlanRelationship"], <add> "0070" : ["SQ", "FractionGroupSequence"], <add> "0071" : ["IS", "FractionGroupNumber"], <add> "0072" : ["LO", "FractionGroupDescription"], <add> "0078" : ["IS", "NumberOfFractionsPlanned"], <add> "0079" : ["IS", "NumberOfFractionPatternDigitsPerDay"], <add> "007A" : ["IS", "RepeatFractionCycleLength"], <add> "007B" : ["LT", "FractionPattern"], <add> "0080" : ["IS", "NumberOfBeams"], <add> "0082" : ["DS", "BeamDoseSpecificationPoint"], <add> "0084" : ["DS", "BeamDose"], <add> "0086" : ["DS", "BeamMeterset"], <add> "0088" : ["FL", "BeamDosePointDepth"], <add> "0089" : ["FL", "BeamDosePointEquivalentDepth"], <add> "008A" : ["FL", "BeamDosePointSSD"], <add> "00A0" : ["IS", "NumberOfBrachyApplicationSetups"], <add> "00A2" : ["DS", "BrachyApplicationSetupDoseSpecificationPoint"], <add> "00A4" : ["DS", "BrachyApplicationSetupDose"], <add> "00B0" : ["SQ", "BeamSequence"], <add> "00B2" : ["SH", "TreatmentMachineName"], <add> "00B3" : ["CS", "PrimaryDosimeterUnit"], <add> "00B4" : ["DS", "SourceAxisDistance"], <add> "00B6" : ["SQ", "BeamLimitingDeviceSequence"], <add> "00B8" : ["CS", "RTBeamLimitingDeviceType"], <add> "00BA" : ["DS", "SourceToBeamLimitingDeviceDistance"], <add> "00BB" : ["FL", "IsocenterToBeamLimitingDeviceDistance"], <add> "00BC" : ["IS", "NumberOfLeafJawPairs"], <add> "00BE" : ["DS", "LeafPositionBoundaries"], <add> "00C0" : ["IS", "BeamNumber"], <add> "00C2" : ["LO", "BeamName"], <add> "00C3" : ["ST", "BeamDescription"], <add> "00C4" : ["CS", "BeamType"], <add> "00C6" : ["CS", "RadiationType"], <add> "00C7" : ["CS", "HighDoseTechniqueType"], <add> "00C8" : ["IS", "ReferenceImageNumber"], <add> "00CA" : ["SQ", "PlannedVerificationImageSequence"], <add> "00CC" : ["LO", "ImagingDeviceSpecificAcquisitionParameters"], <add> "00CE" : ["CS", "TreatmentDeliveryType"], <add> "00D0" : ["IS", "NumberOfWedges"], <add> "00D1" : ["SQ", "WedgeSequence"], <add> "00D2" : ["IS", "WedgeNumber"], <add> "00D3" : ["CS", "WedgeType"], <add> "00D4" : ["SH", "WedgeID"], <add> "00D5" : ["IS", "WedgeAngle"], <add> "00D6" : ["DS", "WedgeFactor"], <add> "00D7" : ["FL", "TotalWedgeTrayWaterEquivalentThickness"], <add> "00D8" : ["DS", "WedgeOrientation"], <add> "00D9" : ["FL", "IsocenterToWedgeTrayDistance"], <add> "00DA" : ["DS", "SourceToWedgeTrayDistance"], <add> "00DB" : ["FL", "WedgeThinEdgePosition"], <add> "00DC" : ["SH", "BolusID"], <add> "00DD" : ["ST", "BolusDescription"], <add> "00E0" : ["IS", "NumberOfCompensators"], <add> "00E1" : ["SH", "MaterialID"], <add> "00E2" : ["DS", "TotalCompensatorTrayFactor"], <add> "00E3" : ["SQ", "CompensatorSequence"], <add> "00E4" : ["IS", "CompensatorNumber"], <add> "00E5" : ["SH", "CompensatorID"], <add> "00E6" : ["DS", "SourceToCompensatorTrayDistance"], <add> "00E7" : ["IS", "CompensatorRows"], <add> "00E8" : ["IS", "CompensatorColumns"], <add> "00E9" : ["DS", "CompensatorPixelSpacing"], <add> "00EA" : ["DS", "CompensatorPosition"], <add> "00EB" : ["DS", "CompensatorTransmissionData"], <add> "00EC" : ["DS", "CompensatorThicknessData"], <add> "00ED" : ["IS", "NumberOfBoli"], <add> "00EE" : ["CS", "CompensatorType"], <add> "00F0" : ["IS", "NumberOfBlocks"], <add> "00F2" : ["DS", "TotalBlockTrayFactor"], <add> "00F3" : ["FL", "TotalBlockTrayWaterEquivalentThickness"], <add> "00F4" : ["SQ", "BlockSequence"], <add> "00F5" : ["SH", "BlockTrayID"], <add> "00F6" : ["DS", "SourceToBlockTrayDistance"], <add> "00F7" : ["FL", "IsocenterToBlockTrayDistance"], <add> "00F8" : ["CS", "BlockType"], <add> "00F9" : ["LO", "AccessoryCode"], <add> "00FA" : ["CS", "BlockDivergence"], <add> "00FB" : ["CS", "BlockMountingPosition"], <add> "00FC" : ["IS", "BlockNumber"], <add> "00FE" : ["LO", "BlockName"], <add> "0100" : ["DS", "BlockThickness"], <add> "0102" : ["DS", "BlockTransmission"], <add> "0104" : ["IS", "BlockNumberOfPoints"], <add> "0106" : ["DS", "BlockData"], <add> "0107" : ["SQ", "ApplicatorSequence"], <add> "0108" : ["SH", "ApplicatorID"], <add> "0109" : ["CS", "ApplicatorType"], <add> "010A" : ["LO", "ApplicatorDescription"], <add> "010C" : ["DS", "CumulativeDoseReferenceCoefficient"], <add> "010E" : ["DS", "FinalCumulativeMetersetWeight"], <add> "0110" : ["IS", "NumberOfControlPoints"], <add> "0111" : ["SQ", "ControlPointSequence"], <add> "0112" : ["IS", "ControlPointIndex"], <add> "0114" : ["DS", "NominalBeamEnergy"], <add> "0115" : ["DS", "DoseRateSet"], <add> "0116" : ["SQ", "WedgePositionSequence"], <add> "0118" : ["CS", "WedgePosition"], <add> "011A" : ["SQ", "BeamLimitingDevicePositionSequence"], <add> "011C" : ["DS", "LeafJawPositions"], <add> "011E" : ["DS", "GantryAngle"], <add> "011F" : ["CS", "GantryRotationDirection"], <add> "0120" : ["DS", "BeamLimitingDeviceAngle"], <add> "0121" : ["CS", "BeamLimitingDeviceRotationDirection"], <add> "0122" : ["DS", "PatientSupportAngle"], <add> "0123" : ["CS", "PatientSupportRotationDirection"], <add> "0124" : ["DS", "TableTopEccentricAxisDistance"], <add> "0125" : ["DS", "TableTopEccentricAngle"], <add> "0126" : ["CS", "TableTopEccentricRotationDirection"], <add> "0128" : ["DS", "TableTopVerticalPosition"], <add> "0129" : ["DS", "TableTopLongitudinalPosition"], <add> "012A" : ["DS", "TableTopLateralPosition"], <add> "012C" : ["DS", "IsocenterPosition"], <add> "012E" : ["DS", "SurfaceEntryPoint"], <add> "0130" : ["DS", "SourceToSurfaceDistance"], <add> "0134" : ["DS", "CumulativeMetersetWeight"], <add> "0140" : ["FL", "TableTopPitchAngle"], <add> "0142" : ["CS", "TableTopPitchRotationDirection"], <add> "0144" : ["FL", "TableTopRollAngle"], <add> "0146" : ["CS", "TableTopRollRotationDirection"], <add> "0148" : ["FL", "HeadFixationAngle"], <add> "014A" : ["FL", "GantryPitchAngle"], <add> "014C" : ["CS", "GantryPitchRotationDirection"], <add> "014E" : ["FL", "GantryPitchAngleTolerance"], <add> "0180" : ["SQ", "PatientSetupSequence"], <add> "0182" : ["IS", "PatientSetupNumber"], <add> "0183" : ["LO", "PatientSetupLabel"], <add> "0184" : ["LO", "PatientAdditionalPosition"], <add> "0190" : ["SQ", "FixationDeviceSequence"], <add> "0192" : ["CS", "FixationDeviceType"], <add> "0194" : ["SH", "FixationDeviceLabel"], <add> "0196" : ["ST", "FixationDeviceDescription"], <add> "0198" : ["SH", "FixationDevicePosition"], <add> "0199" : ["FL", "FixationDevicePitchAngle"], <add> "019A" : ["FL", "FixationDeviceRollAngle"], <add> "01A0" : ["SQ", "ShieldingDeviceSequence"], <add> "01A2" : ["CS", "ShieldingDeviceType"], <add> "01A4" : ["SH", "ShieldingDeviceLabel"], <add> "01A6" : ["ST", "ShieldingDeviceDescription"], <add> "01A8" : ["SH", "ShieldingDevicePosition"], <add> "01B0" : ["CS", "SetupTechnique"], <add> "01B2" : ["ST", "SetupTechniqueDescription"], <add> "01B4" : ["SQ", "SetupDeviceSequence"], <add> "01B6" : ["CS", "SetupDeviceType"], <add> "01B8" : ["SH", "SetupDeviceLabel"], <add> "01BA" : ["ST", "SetupDeviceDescription"], <add> "01BC" : ["DS", "SetupDeviceParameter"], <add> "01D0" : ["ST", "SetupReferenceDescription"], <add> "01D2" : ["DS", "TableTopVerticalSetupDisplacement"], <add> "01D4" : ["DS", "TableTopLongitudinalSetupDisplacement"], <add> "01D6" : ["DS", "TableTopLateralSetupDisplacement"], <add> "0200" : ["CS", "BrachyTreatmentTechnique"], <add> "0202" : ["CS", "BrachyTreatmentType"], <add> "0206" : ["SQ", "TreatmentMachineSequence"], <add> "0210" : ["SQ", "SourceSequence"], <add> "0212" : ["IS", "SourceNumber"], <add> "0214" : ["CS", "SourceType"], <add> "0216" : ["LO", "SourceManufacturer"], <add> "0218" : ["DS", "ActiveSourceDiameter"], <add> "021A" : ["DS", "ActiveSourceLength"], <add> "0222" : ["DS", "SourceEncapsulationNominalThickness"], <add> "0224" : ["DS", "SourceEncapsulationNominalTransmission"], <add> "0226" : ["LO", "SourceIsotopeName"], <add> "0228" : ["DS", "SourceIsotopeHalfLife"], <add> "0229" : ["CS", "SourceStrengthUnits"], <add> "022A" : ["DS", "ReferenceAirKermaRate"], <add> "022B" : ["DS", "SourceStrength"], <add> "022C" : ["DA", "SourceStrengthReferenceDate"], <add> "022E" : ["TM", "SourceStrengthReferenceTime"], <add> "0230" : ["SQ", "ApplicationSetupSequence"], <add> "0232" : ["CS", "ApplicationSetupType"], <add> "0234" : ["IS", "ApplicationSetupNumber"], <add> "0236" : ["LO", "ApplicationSetupName"], <add> "0238" : ["LO", "ApplicationSetupManufacturer"], <add> "0240" : ["IS", "TemplateNumber"], <add> "0242" : ["SH", "TemplateType"], <add> "0244" : ["LO", "TemplateName"], <add> "0250" : ["DS", "TotalReferenceAirKerma"], <add> "0260" : ["SQ", "BrachyAccessoryDeviceSequence"], <add> "0262" : ["IS", "BrachyAccessoryDeviceNumber"], <add> "0263" : ["SH", "BrachyAccessoryDeviceID"], <add> "0264" : ["CS", "BrachyAccessoryDeviceType"], <add> "0266" : ["LO", "BrachyAccessoryDeviceName"], <add> "026A" : ["DS", "BrachyAccessoryDeviceNominalThickness"], <add> "026C" : ["DS", "BrachyAccessoryDeviceNominalTransmission"], <add> "0280" : ["SQ", "ChannelSequence"], <add> "0282" : ["IS", "ChannelNumber"], <add> "0284" : ["DS", "ChannelLength"], <add> "0286" : ["DS", "ChannelTotalTime"], <add> "0288" : ["CS", "SourceMovementType"], <add> "028A" : ["IS", "NumberOfPulses"], <add> "028C" : ["DS", "PulseRepetitionInterval"], <add> "0290" : ["IS", "SourceApplicatorNumber"], <add> "0291" : ["SH", "SourceApplicatorID"], <add> "0292" : ["CS", "SourceApplicatorType"], <add> "0294" : ["LO", "SourceApplicatorName"], <add> "0296" : ["DS", "SourceApplicatorLength"], <add> "0298" : ["LO", "SourceApplicatorManufacturer"], <add> "029C" : ["DS", "SourceApplicatorWallNominalThickness"], <add> "029E" : ["DS", "SourceApplicatorWallNominalTransmission"], <add> "02A0" : ["DS", "SourceApplicatorStepSize"], <add> "02A2" : ["IS", "TransferTubeNumber"], <add> "02A4" : ["DS", "TransferTubeLength"], <add> "02B0" : ["SQ", "ChannelShieldSequence"], <add> "02B2" : ["IS", "ChannelShieldNumber"], <add> "02B3" : ["SH", "ChannelShieldID"], <add> "02B4" : ["LO", "ChannelShieldName"], <add> "02B8" : ["DS", "ChannelShieldNominalThickness"], <add> "02BA" : ["DS", "ChannelShieldNominalTransmission"], <add> "02C8" : ["DS", "FinalCumulativeTimeWeight"], <add> "02D0" : ["SQ", "BrachyControlPointSequence"], <add> "02D2" : ["DS", "ControlPointRelativePosition"], <add> "02D4" : ["DS", "ControlPoint3DPosition"], <add> "02D6" : ["DS", "CumulativeTimeWeight"], <add> "02E0" : ["CS", "CompensatorDivergence"], <add> "02E1" : ["CS", "CompensatorMountingPosition"], <add> "02E2" : ["DS", "SourceToCompensatorDistance"], <add> "02E3" : ["FL", "TotalCompensatorTrayWaterEquivalentThickness"], <add> "02E4" : ["FL", "IsocenterToCompensatorTrayDistance"], <add> "02E5" : ["FL", "CompensatorColumnOffset"], <add> "02E6" : ["FL", "IsocenterToCompensatorDistances"], <add> "02E7" : ["FL", "CompensatorRelativeStoppingPowerRatio"], <add> "02E8" : ["FL", "CompensatorMillingToolDiameter"], <add> "02EA" : ["SQ", "IonRangeCompensatorSequence"], <add> "02EB" : ["LT", "CompensatorDescription"], <add> "0302" : ["IS", "RadiationMassNumber"], <add> "0304" : ["IS", "RadiationAtomicNumber"], <add> "0306" : ["SS", "RadiationChargeState"], <add> "0308" : ["CS", "ScanMode"], <add> "030A" : ["FL", "VirtualSourceAxisDistances"], <add> "030C" : ["SQ", "SnoutSequence"], <add> "030D" : ["FL", "SnoutPosition"], <add> "030F" : ["SH", "SnoutID"], <add> "0312" : ["IS", "NumberOfRangeShifters"], <add> "0314" : ["SQ", "RangeShifterSequence"], <add> "0316" : ["IS", "RangeShifterNumber"], <add> "0318" : ["SH", "RangeShifterID"], <add> "0320" : ["CS", "RangeShifterType"], <add> "0322" : ["LO", "RangeShifterDescription"], <add> "0330" : ["IS", "NumberOfLateralSpreadingDevices"], <add> "0332" : ["SQ", "LateralSpreadingDeviceSequence"], <add> "0334" : ["IS", "LateralSpreadingDeviceNumber"], <add> "0336" : ["SH", "LateralSpreadingDeviceID"], <add> "0338" : ["CS", "LateralSpreadingDeviceType"], <add> "033A" : ["LO", "LateralSpreadingDeviceDescription"], <add> "033C" : ["FL", "LateralSpreadingDeviceWaterEquivalentThickness"], <add> "0340" : ["IS", "NumberOfRangeModulators"], <add> "0342" : ["SQ", "RangeModulatorSequence"], <add> "0344" : ["IS", "RangeModulatorNumber"], <add> "0346" : ["SH", "RangeModulatorID"], <add> "0348" : ["CS", "RangeModulatorType"], <add> "034A" : ["LO", "RangeModulatorDescription"], <add> "034C" : ["SH", "BeamCurrentModulationID"], <add> "0350" : ["CS", "PatientSupportType"], <add> "0352" : ["SH", "PatientSupportID"], <add> "0354" : ["LO", "PatientSupportAccessoryCode"], <add> "0356" : ["FL", "FixationLightAzimuthalAngle"], <add> "0358" : ["FL", "FixationLightPolarAngle"], <add> "035A" : ["FL", "MetersetRate"], <add> "0360" : ["SQ", "RangeShifterSettingsSequence"], <add> "0362" : ["LO", "RangeShifterSetting"], <add> "0364" : ["FL", "IsocenterToRangeShifterDistance"], <add> "0366" : ["FL", "RangeShifterWaterEquivalentThickness"], <add> "0370" : ["SQ", "LateralSpreadingDeviceSettingsSequence"], <add> "0372" : ["LO", "LateralSpreadingDeviceSetting"], <add> "0374" : ["FL", "IsocenterToLateralSpreadingDeviceDistance"], <add> "0380" : ["SQ", "RangeModulatorSettingsSequence"], <add> "0382" : ["FL", "RangeModulatorGatingStartValue"], <add> "0384" : ["FL", "RangeModulatorGatingStopValue"], <add> "0386" : ["FL", "RangeModulatorGatingStartWaterEquivalentThickness"], <add> "0388" : ["FL", "RangeModulatorGatingStopWaterEquivalentThickness"], <add> "038A" : ["FL", "IsocenterToRangeModulatorDistance"], <add> "0390" : ["SH", "ScanSpotTuneID"], <add> "0392" : ["IS", "NumberOfScanSpotPositions"], <add> "0394" : ["FL", "ScanSpotPositionMap"], <add> "0396" : ["FL", "ScanSpotMetersetWeights"], <add> "0398" : ["FL", "ScanningSpotSize"], <add> "039A" : ["IS", "NumberOfPaintings"], <add> "03A0" : ["SQ", "IonToleranceTableSequence"], <add> "03A2" : ["SQ", "IonBeamSequence"], <add> "03A4" : ["SQ", "IonBeamLimitingDeviceSequence"], <add> "03A6" : ["SQ", "IonBlockSequence"], <add> "03A8" : ["SQ", "IonControlPointSequence"], <add> "03AA" : ["SQ", "IonWedgeSequence"], <add> "03AC" : ["SQ", "IonWedgePositionSequence"], <add> "0401" : ["SQ", "ReferencedSetupImageSequence"], <add> "0402" : ["ST", "SetupImageComment"], <add> "0410" : ["SQ", "MotionSynchronizationSequence"], <add> "0412" : ["FL", "ControlPointOrientation"], <add> "0420" : ["SQ", "GeneralAccessorySequence"], <add> "0421" : ["SH", "GeneralAccessoryID"], <add> "0422" : ["ST", "GeneralAccessoryDescription"], <add> "0423" : ["CS", "GeneralAccessoryType"], <add> "0424" : ["IS", "GeneralAccessoryNumber"], <add> "0431" : ["SQ", "ApplicatorGeometrySequence"], <add> "0432" : ["CS", "ApplicatorApertureShape"], <add> "0433" : ["FL", "ApplicatorOpening"], <add> "0434" : ["FL", "ApplicatorOpeningX"], <add> "0435" : ["FL", "ApplicatorOpeningY"], <add> "0436" : ["FL", "SourceToApplicatorMountingPositionDistance"] <add> }, <add> "300C" : { <add> "0002" : ["SQ", "ReferencedRTPlanSequence"], <add> "0004" : ["SQ", "ReferencedBeamSequence"], <add> "0006" : ["IS", "ReferencedBeamNumber"], <add> "0007" : ["IS", "ReferencedReferenceImageNumber"], <add> "0008" : ["DS", "StartCumulativeMetersetWeight"], <add> "0009" : ["DS", "EndCumulativeMetersetWeight"], <add> "000A" : ["SQ", "ReferencedBrachyApplicationSetupSequence"], <add> "000C" : ["IS", "ReferencedBrachyApplicationSetupNumber"], <add> "000E" : ["IS", "ReferencedSourceNumber"], <add> "0020" : ["SQ", "ReferencedFractionGroupSequence"], <add> "0022" : ["IS", "ReferencedFractionGroupNumber"], <add> "0040" : ["SQ", "ReferencedVerificationImageSequence"], <add> "0042" : ["SQ", "ReferencedReferenceImageSequence"], <add> "0050" : ["SQ", "ReferencedDoseReferenceSequence"], <add> "0051" : ["IS", "ReferencedDoseReferenceNumber"], <add> "0055" : ["SQ", "BrachyReferencedDoseReferenceSequence"], <add> "0060" : ["SQ", "ReferencedStructureSetSequence"], <add> "006A" : ["IS", "ReferencedPatientSetupNumber"], <add> "0080" : ["SQ", "ReferencedDoseSequence"], <add> "00A0" : ["IS", "ReferencedToleranceTableNumber"], <add> "00B0" : ["SQ", "ReferencedBolusSequence"], <add> "00C0" : ["IS", "ReferencedWedgeNumber"], <add> "00D0" : ["IS", "ReferencedCompensatorNumber"], <add> "00E0" : ["IS", "ReferencedBlockNumber"], <add> "00F0" : ["IS", "ReferencedControlPointIndex"], <add> "00F2" : ["SQ", "ReferencedControlPointSequence"], <add> "00F4" : ["IS", "ReferencedStartControlPointIndex"], <add> "00F6" : ["IS", "ReferencedStopControlPointIndex"], <add> "0100" : ["IS", "ReferencedRangeShifterNumber"], <add> "0102" : ["IS", "ReferencedLateralSpreadingDeviceNumber"], <add> "0104" : ["IS", "ReferencedRangeModulatorNumber"] <add> }, <add> "300E" : { <add> "0002" : ["CS", "ApprovalStatus"], <add> "0004" : ["DA", "ReviewDate"], <add> "0005" : ["TM", "ReviewTime"], <add> "0008" : ["PN", "ReviewerName"] <add> }, <add> "4000" : { <add> "0010" : ["LT", "Arbitrary"], <add> "4000" : ["LT", "TextComments"] <add> }, <add> "4008" : { <add> "0040" : ["SH", "ResultsID"], <add> "0042" : ["LO", "ResultsIDIssuer"], <add> "0050" : ["SQ", "ReferencedInterpretationSequence"], <add> "00FF" : ["CS", "ReportProductionStatusTrial"], <add> "0100" : ["DA", "InterpretationRecordedDate"], <add> "0101" : ["TM", "InterpretationRecordedTime"], <add> "0102" : ["PN", "InterpretationRecorder"], <add> "0103" : ["LO", "ReferenceToRecordedSound"], <add> "0108" : ["DA", "InterpretationTranscriptionDate"], <add> "0109" : ["TM", "InterpretationTranscriptionTime"], <add> "010A" : ["PN", "InterpretationTranscriber"], <add> "010B" : ["ST", "InterpretationText"], <add> "010C" : ["PN", "InterpretationAuthor"], <add> "0111" : ["SQ", "InterpretationApproverSequence"], <add> "0112" : ["DA", "InterpretationApprovalDate"], <add> "0113" : ["TM", "InterpretationApprovalTime"], <add> "0114" : ["PN", "PhysicianApprovingInterpretation"], <add> "0115" : ["LT", "InterpretationDiagnosisDescription"], <add> "0117" : ["SQ", "InterpretationDiagnosisCodeSequence"], <add> "0118" : ["SQ", "ResultsDistributionListSequence"], <add> "0119" : ["PN", "DistributionName"], <add> "011A" : ["LO", "DistributionAddress"], <add> "0200" : ["SH", "InterpretationID"], <add> "0202" : ["LO", "InterpretationIDIssuer"], <add> "0210" : ["CS", "InterpretationTypeID"], <add> "0212" : ["CS", "InterpretationStatusID"], <add> "0300" : ["ST", "Impressions"], <add> "4000" : ["ST", "ResultsComments"] <add> }, <add> "4010" : { <add> "0001" : ["CS", "LowEnergyDetectors"], <add> "0002" : ["CS", "HighEnergyDetectors"], <add> "0004" : ["SQ", "DetectorGeometrySequence"], <add> "1001" : ["SQ", "ThreatROIVoxelSequence"], <add> "1004" : ["FL", "ThreatROIBase"], <add> "1005" : ["FL", "ThreatROIExtents"], <add> "1006" : ["OB", "ThreatROIBitmap"], <add> "1007" : ["SH", "RouteSegmentID"], <add> "1008" : ["CS", "GantryType"], <add> "1009" : ["CS", "OOIOwnerType"], <add> "100A" : ["SQ", "RouteSegmentSequence"], <add> "1010" : ["US", "PotentialThreatObjectID"], <add> "1011" : ["SQ", "ThreatSequence"], <add> "1012" : ["CS", "ThreatCategory"], <add> "1013" : ["LT", "ThreatCategoryDescription"], <add> "1014" : ["CS", "ATDAbilityAssessment"], <add> "1015" : ["CS", "ATDAssessmentFlag"], <add> "1016" : ["FL", "ATDAssessmentProbability"], <add> "1017" : ["FL", "Mass"], <add> "1018" : ["FL", "Density"], <add> "1019" : ["FL", "ZEffective"], <add> "101A" : ["SH", "BoardingPassID"], <add> "101B" : ["FL", "CenterOfMass"], <add> "101C" : ["FL", "CenterOfPTO"], <add> "101D" : ["FL", "BoundingPolygon"], <add> "101E" : ["SH", "RouteSegmentStartLocationID"], <add> "101F" : ["SH", "RouteSegmentEndLocationID"], <add> "1020" : ["CS", "RouteSegmentLocationIDType"], <add> "1021" : ["CS", "AbortReason"], <add> "1023" : ["FL", "VolumeOfPTO"], <add> "1024" : ["CS", "AbortFlag"], <add> "1025" : ["DT", "RouteSegmentStartTime"], <add> "1026" : ["DT", "RouteSegmentEndTime"], <add> "1027" : ["CS", "TDRType"], <add> "1028" : ["CS", "InternationalRouteSegment"], <add> "1029" : ["LO", "ThreatDetectionAlgorithmandVersion"], <add> "102A" : ["SH", "AssignedLocation"], <add> "102B" : ["DT", "AlarmDecisionTime"], <add> "1031" : ["CS", "AlarmDecision"], <add> "1033" : ["US", "NumberOfTotalObjects"], <add> "1034" : ["US", "NumberOfAlarmObjects"], <add> "1037" : ["SQ", "PTORepresentationSequence"], <add> "1038" : ["SQ", "ATDAssessmentSequence"], <add> "1039" : ["CS", "TIPType"], <add> "103A" : ["CS", "DICOSVersion"], <add> "1041" : ["DT", "OOIOwnerCreationTime"], <add> "1042" : ["CS", "OOIType"], <add> "1043" : ["FL", "OOISize"], <add> "1044" : ["CS", "AcquisitionStatus"], <add> "1045" : ["SQ", "BasisMaterialsCodeSequence"], <add> "1046" : ["CS", "PhantomType"], <add> "1047" : ["SQ", "OOIOwnerSequence"], <add> "1048" : ["CS", "ScanType"], <add> "1051" : ["LO", "ItineraryID"], <add> "1052" : ["SH", "ItineraryIDType"], <add> "1053" : ["LO", "ItineraryIDAssigningAuthority"], <add> "1054" : ["SH", "RouteID"], <add> "1055" : ["SH", "RouteIDAssigningAuthority"], <add> "1056" : ["CS", "InboundArrivalType"], <add> "1058" : ["SH", "CarrierID"], <add> "1059" : ["CS", "CarrierIDAssigningAuthority"], <add> "1060" : ["FL", "SourceOrientation"], <add> "1061" : ["FL", "SourcePosition"], <add> "1062" : ["FL", "BeltHeight"], <add> "1064" : ["SQ", "AlgorithmRoutingCodeSequence"], <add> "1067" : ["CS", "TransportClassification"], <add> "1068" : ["LT", "OOITypeDescriptor"], <add> "1069" : ["FL", "TotalProcessingTime"], <add> "106C" : ["OB", "DetectorCalibrationData"] <add> } <add>}; <add> <ide> <ide> <ide> /*** Static Methods ***/ <ide> <ide> daikon.Dictionary.getVR = function (group, element) { <del> var vr = null, startIndex, ctr, num; <del> <del> startIndex = daikon.Dictionary.GROUP_INDICES[group]; <del> if (!startIndex) { <del> startIndex = daikon.Dictionary.GROUP_INDICES[daikon.Dictionary.GROUP_INDICES.length - 1]; <del> } <del> <del> num = daikon.Dictionary.dict.length; <del> <del> for (ctr = startIndex; ctr < num; ctr += 1) { <del> if ((daikon.Dictionary.dict[ctr][0] === group) && (daikon.Dictionary.dict[ctr][1] === element)) { <del> vr = daikon.Dictionary.dict[ctr][3]; <del> break; <del> } else if (daikon.Dictionary.dict[ctr][0] > group) { <del> break; <add> var vr, elementData, groupData; <add> <add> groupData = daikon.Dictionary.dict[daikon.Utils.dec2hex(group)]; <add> if (groupData) { <add> elementData = groupData[daikon.Utils.dec2hex(element)]; <add> if (elementData) { <add> vr = elementData[0]; <ide> } <ide> } <ide> <del> if (vr === null) { <del> num = daikon.Dictionary.dictPrivate.length; <del> for (ctr = 0; ctr < num; ctr += 1) { <del> if ((daikon.Dictionary.dictPrivate[ctr][0] === group) && <del> (daikon.Dictionary.dictPrivate[ctr][1] === element)) { <del> vr = daikon.Dictionary.dictPrivate[ctr][3]; <del> break; <add> if (!vr) { <add> groupData = daikon.Dictionary.dictPrivate[daikon.Utils.dec2hex(group)]; <add> if (groupData) { <add> elementData = groupData[daikon.Utils.dec2hex(element)]; <add> if (elementData) { <add> vr = elementData[0]; <ide> } <ide> } <del> <del> if (vr === null) { <del> vr = 'OB'; <add> } <add> <add> if (!vr) { <add> vr = 'OB'; <add> } <add> <add> return vr; <add>}; <add> <add> <add> <add>daikon.Dictionary.getDescription = function (group, element) { <add> var des, elementData, groupData; <add> <add> groupData = daikon.Dictionary.dict[daikon.Utils.dec2hex(group)]; <add> if (groupData) { <add> elementData = groupData[daikon.Utils.dec2hex(element)]; <add> if (elementData) { <add> des = elementData[1]; <ide> } <ide> } <ide> <del> return vr; <del>}; <del> <del> <del> <del>daikon.Dictionary.getDescription = function (group, element) { <del> var des = null, startIndex, ctr, num; <del> <del> startIndex = daikon.Dictionary.GROUP_INDICES[group]; <del> if (startIndex === undefined) { <del> startIndex = daikon.Dictionary.GROUP_INDICES[daikon.Dictionary.GROUP_INDICES.length - 1]; <del> } <del> <del> num = daikon.Dictionary.dict.length; <del> <del> for (ctr = startIndex; ctr < num; ctr += 1) { <del> if ((daikon.Dictionary.dict[ctr][0] === group) && (daikon.Dictionary.dict[ctr][1] === element)) { <del> des = daikon.Dictionary.dict[ctr][2]; <del> break; <del> } else if (daikon.Dictionary.dict[ctr][0] > group) { <del> break; <del> } <del> } <del> <del> if (des === null) { <del> num = daikon.Dictionary.dictPrivate.length; <del> for (ctr = 0; ctr < num; ctr += 1) { <del> if ((daikon.Dictionary.dictPrivate[ctr][0] === group) && <del> (daikon.Dictionary.dictPrivate[ctr][1] === element)) { <del> des = daikon.Dictionary.dictPrivate[ctr][2]; <del> break; <add> if (!des) { <add> groupData = daikon.Dictionary.dictPrivate[daikon.Utils.dec2hex(group)]; <add> if (groupData) { <add> elementData = groupData[daikon.Utils.dec2hex(element)]; <add> if (elementData) { <add> des = elementData[1]; <ide> } <ide> } <del> <del> if (des === null) { <del> des = 'PrivateData'; <del> } <add> } <add> <add> if (!des) { <add> des = 'PrivateData'; <ide> } <ide> <ide> return des; <ide> }; <ide> <ide> <del>/* <del>if (isMosaic) { <del> dcm.setMosaicCols(tempDicom[chosenFileIndex].getCols() / matSize[1]); <del> dcm.setMosaicRows(tempDicom[chosenFileIndex].getRows() / matSize[0]); <del> dcm.setMosaicWidth(tempDicom[chosenFileIndex].getCols()); <del> dcm.setMosaicHeight(tempDicom[chosenFileIndex].getRows()); <del>} <del>*/ <del> <del> <ide> <ide> daikon.Image.prototype.getMosaicCols = function() { <ide> return this.getCols() / this.getAcquisitionMatrix(); <ide> <ide> element = data.getUint16(offset, true); <ide> offset += 2; <del> <del> if ((group === 0) && (element === 0)) { <del> console.log("here"); <del> } <ide> <ide> if (this.explicit || !this.metaFinished) { <ide> vr = daikon.Utils.getStringAt(data, offset, 2);
Java
apache-2.0
275a9c8ec05e631235a8b39eb5bf9ca23a25b064
0
yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,yapengsong/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,zerodengxinchao/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,eayun/ovirt-engine,eayun/ovirt-engine,walteryang47/ovirt-engine,yapengsong/ovirt-engine,OpenUniversity/ovirt-engine,walteryang47/ovirt-engine,yingyun001/ovirt-engine,eayun/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,zerodengxinchao/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,yingyun001/ovirt-engine,walteryang47/ovirt-engine,OpenUniversity/ovirt-engine,eayun/ovirt-engine,yapengsong/ovirt-engine,yapengsong/ovirt-engine
package org.ovirt.engine.core.bll.tasks; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.ovirt.engine.core.bll.CommandBase; import org.ovirt.engine.core.bll.CommandMultiAsyncTasks; import org.ovirt.engine.core.bll.CommandsFactory; import org.ovirt.engine.core.bll.job.ExecutionContext; import org.ovirt.engine.core.bll.job.ExecutionHandler; import org.ovirt.engine.core.bll.tasks.interfaces.CommandCoordinator; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.asynctasks.AsyncTaskParameters; import org.ovirt.engine.core.common.asynctasks.EndedTaskInfo; import org.ovirt.engine.core.common.businessentities.AsyncTask; import org.ovirt.engine.core.common.businessentities.CommandEntity; import org.ovirt.engine.core.common.errors.VdcBLLException; import org.ovirt.engine.core.compat.CommandStatus; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for all tasks regarding a specific command. */ public class CommandAsyncTask extends SPMAsyncTask { private static final Logger log = LoggerFactory.getLogger(CommandAsyncTask.class); private static final Object _lockObject = new Object(); private static final Map<Guid, CommandMultiAsyncTasks> _multiTasksByCommandIds = new HashMap<Guid, CommandMultiAsyncTasks>(); public CommandMultiAsyncTasks getCommandMultiAsyncTasks() { CommandMultiAsyncTasks entityInfo = null; synchronized (_lockObject) { entityInfo = _multiTasksByCommandIds.get(getCommandId()); } return entityInfo; } public CommandAsyncTask(CommandCoordinator coco, AsyncTaskParameters parameters, boolean duringInit) { super(coco, parameters); boolean isNewCommandAdded = false; synchronized (_lockObject) { if (!_multiTasksByCommandIds.containsKey(getCommandId())) { log.info("CommandAsyncTask::Adding CommandMultiAsyncTasks object for command '{}'", getCommandId()); _multiTasksByCommandIds.put(getCommandId(), new CommandMultiAsyncTasks(getCommandId())); isNewCommandAdded = true; } CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks(); entityInfo.AttachTask(this); } if (duringInit && isNewCommandAdded) { CommandBase<?> command = CommandsFactory.createCommand(parameters.getDbAsyncTask().getActionType(), parameters.getDbAsyncTask().getActionParameters()); if (!command.acquireLockAsyncTask()) { log.warn("Failed to acquire locks for command '{}' with parameters '{}'", parameters.getDbAsyncTask().getActionType(), parameters.getDbAsyncTask().getActionParameters()); } } } @Override public void concreteStartPollingTask() { CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks(); entityInfo.StartPollingTask(getVdsmTaskId()); } @Override protected void onTaskEndSuccess() { logEndTaskSuccess(); endActionIfNecessary(); } private void endActionIfNecessary() { CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks(); if (entityInfo == null) { log.warn("CommandAsyncTask::endActionIfNecessary: No info is available for entity '{}', current" + " task ('{}') was probably created while other tasks were in progress, clearing task.", getCommandId(), getVdsmTaskId()); clearAsyncTask(); } else if (entityInfo.ShouldEndAction() && !hasRunningChildCommands()) { log.info( "CommandAsyncTask::endActionIfNecessary: All tasks of command '{}' has ended -> executing 'endAction'", getCommandId()); log.info("CommandAsyncTask::endAction: Ending action for '{}' tasks (command ID: '{}'): calling endAction '.", entityInfo.getTasksCountCurrentActionType(), entityInfo.getCommandId()); entityInfo.MarkAllWithAttemptingEndAction(); ThreadPoolUtil.execute(new Runnable() { @SuppressWarnings("synthetic-access") @Override public void run() { endCommandAction(); } }); } } private boolean hasRunningChildCommands() { Guid rootCmdId = getParameters().getDbAsyncTask().getRootCommandId(); for (CommandEntity entity : coco.getChildCmdsByParentCmdId(rootCmdId)) { if (!hasCompleted(entity) && !coco.doesCommandContainAsyncTask(entity.getId())) { return true; } } return false; } private boolean hasCompleted(CommandEntity entity) { return CommandStatus.SUCCEEDED.equals(entity.getCommandStatus()) || CommandStatus.FAILED.equals(entity.getCommandStatus()) || CommandStatus.FAILED_RESTARTED.equals(entity.getCommandStatus()); } private void endCommandAction() { CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks(); VdcReturnValueBase vdcReturnValue = null; ExecutionContext context = null; boolean endActionRuntimeException = false; AsyncTask dbAsyncTask = getParameters().getDbAsyncTask(); ArrayList<VdcActionParametersBase> imagesParameters = new ArrayList<VdcActionParametersBase>(); for (EndedTaskInfo taskInfo : entityInfo.getEndedTasksInfo().getTasksInfo()) { VdcActionParametersBase childTaskParameters = taskInfo.getTaskParameters().getDbAsyncTask().getTaskParameters(); boolean childTaskGroupSuccess = childTaskParameters.getTaskGroupSuccess() && taskInfo.getTaskStatus().getTaskEndedSuccessfully(); childTaskParameters .setTaskGroupSuccess(childTaskGroupSuccess); if (!childTaskParameters.equals(dbAsyncTask.getActionParameters())) { imagesParameters.add(childTaskParameters); } } dbAsyncTask.getActionParameters().setImagesParameters(imagesParameters); try { log.info("CommandAsyncTask::endCommandAction [within thread] context: Attempting to endAction '{}'," + " executionIndex: '{}'", dbAsyncTask.getActionParameters().getCommandType(), dbAsyncTask.getActionParameters().getExecutionIndex()); try { /** * Creates context for the job which monitors the action */ Guid stepId = dbAsyncTask.getStepId(); if (stepId != null) { context = ExecutionHandler.createFinalizingContext(stepId); } vdcReturnValue = coco.endAction(this, context); } catch (VdcBLLException ex) { log.error("{}: {}", getErrorMessage(), ex.getMessage()); log.debug("Exception", ex); } catch (RuntimeException ex) { log.error(getErrorMessage(), ex); endActionRuntimeException = true; } } catch (RuntimeException Ex2) { log.error("CommandAsyncTask::endCommandAction [within thread]: An exception has been thrown (not" + " related to 'endAction' itself)", Ex2); endActionRuntimeException = true; } finally { // if a RuntimeExcpetion occurs we clear the task from db and perform no other action if (endActionRuntimeException) { handleEndActionRuntimeException(entityInfo, dbAsyncTask); } else { boolean isTaskGroupSuccess = dbAsyncTask.getActionParameters().getTaskGroupSuccess(); handleEndActionResult(entityInfo, vdcReturnValue, context, isTaskGroupSuccess); } } } private String getErrorMessage() { return String.format("[within thread]: endAction for action type %1$s threw an exception.", getParameters().getDbAsyncTask().getActionParameters().getCommandType()); } private void handleEndActionRuntimeException(CommandMultiAsyncTasks commandInfo, AsyncTask dbAsyncTask) { try { VdcActionType actionType = getParameters().getDbAsyncTask().getActionType(); log.info("CommandAsyncTask::HandleEndActionResult: endAction for action type '{}' threw an" + " unrecoverable RuntimeException the task will be cleared.", actionType); commandInfo.clearTaskByVdsmTaskId(dbAsyncTask.getVdsmTaskId()); removeTaskFromDB(); if (commandInfo.getAllCleared()) { log.info("CommandAsyncTask::HandleEndActionRuntimeException: Removing CommandMultiAsyncTasks" + " object for entity '{}'", commandInfo.getCommandId()); synchronized (_lockObject) { _multiTasksByCommandIds.remove(commandInfo.getCommandId()); } } } catch (RuntimeException ex) { log.error("CommandAsyncTask::HandleEndActionResult [within thread]: an exception has been thrown", ex); } } private void handleEndActionResult(CommandMultiAsyncTasks commandInfo, VdcReturnValueBase vdcReturnValue, ExecutionContext context, boolean isTaskGroupSuccess) { try { VdcActionType actionType = getParameters().getDbAsyncTask().getActionType(); log.info("CommandAsyncTask::HandleEndActionResult [within thread]: endAction for action type '{}'" + " completed, handling the result.", actionType); if (vdcReturnValue == null || (!vdcReturnValue.getSucceeded() && vdcReturnValue.getEndActionTryAgain())) { log.info("CommandAsyncTask::HandleEndActionResult [within thread]: endAction for action type" + " '{}' hasn't succeeded, not clearing tasks, will attempt again next polling.", actionType); commandInfo.Repoll(); } else { log.info("CommandAsyncTask::HandleEndActionResult [within thread]: endAction for action type" + " '{}' {}succeeded, clearing tasks.", actionType, vdcReturnValue.getSucceeded() ? "" : "hasn't "); /** * Terminate the job by the return value of endAction. * The operation will end also the FINALIZING step. */ if (context != null) { ExecutionHandler.endTaskJob(context, vdcReturnValue.getSucceeded() && isTaskGroupSuccess); } commandInfo.ClearTasks(); synchronized (_lockObject) { if (commandInfo.getAllCleared()) { log.info("CommandAsyncTask::HandleEndActionResult [within thread]: Removing" + " CommandMultiAsyncTasks object for entity '{}'", commandInfo.getCommandId()); _multiTasksByCommandIds.remove(commandInfo.getCommandId()); } } } } catch (RuntimeException ex) { log.error("CommandAsyncTask::HandleEndActionResult [within thread]: an exception has been thrown", ex); } } @Override protected void onTaskEndFailure() { logEndTaskFailure(); endActionIfNecessary(); } @Override protected void onTaskDoesNotExist() { logTaskDoesntExist(); endActionIfNecessary(); } }
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/tasks/CommandAsyncTask.java
package org.ovirt.engine.core.bll.tasks; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import org.ovirt.engine.core.bll.CommandBase; import org.ovirt.engine.core.bll.CommandMultiAsyncTasks; import org.ovirt.engine.core.bll.CommandsFactory; import org.ovirt.engine.core.bll.job.ExecutionContext; import org.ovirt.engine.core.bll.job.ExecutionHandler; import org.ovirt.engine.core.bll.tasks.interfaces.CommandCoordinator; import org.ovirt.engine.core.common.action.VdcActionParametersBase; import org.ovirt.engine.core.common.action.VdcActionType; import org.ovirt.engine.core.common.action.VdcReturnValueBase; import org.ovirt.engine.core.common.asynctasks.AsyncTaskParameters; import org.ovirt.engine.core.common.asynctasks.EndedTaskInfo; import org.ovirt.engine.core.common.businessentities.AsyncTask; import org.ovirt.engine.core.common.businessentities.CommandEntity; import org.ovirt.engine.core.common.errors.VdcBLLException; import org.ovirt.engine.core.compat.CommandStatus; import org.ovirt.engine.core.compat.Guid; import org.ovirt.engine.core.utils.threadpool.ThreadPoolUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Base class for all tasks regarding a specific command. */ public class CommandAsyncTask extends SPMAsyncTask { private static final Logger log = LoggerFactory.getLogger(CommandAsyncTask.class); private static final Object _lockObject = new Object(); private static final Map<Guid, CommandMultiAsyncTasks> _multiTasksByCommandIds = new HashMap<Guid, CommandMultiAsyncTasks>(); public CommandMultiAsyncTasks getCommandMultiAsyncTasks() { CommandMultiAsyncTasks entityInfo = null; synchronized (_lockObject) { entityInfo = _multiTasksByCommandIds.get(getCommandId()); } return entityInfo; } public CommandAsyncTask(CommandCoordinator coco, AsyncTaskParameters parameters, boolean duringInit) { super(coco, parameters); boolean isNewCommandAdded = false; synchronized (_lockObject) { if (!_multiTasksByCommandIds.containsKey(getCommandId())) { log.info("CommandAsyncTask::Adding CommandMultiAsyncTasks object for command '{}'", getCommandId()); _multiTasksByCommandIds.put(getCommandId(), new CommandMultiAsyncTasks(getCommandId())); isNewCommandAdded = true; } CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks(); entityInfo.AttachTask(this); } if (duringInit && isNewCommandAdded) { CommandBase<?> command = CommandsFactory.createCommand(parameters.getDbAsyncTask().getActionType(), parameters.getDbAsyncTask().getActionParameters()); if (!command.acquireLockAsyncTask()) { log.warn("Failed to acquire locks for command '{}' with parameters '{}'", parameters.getDbAsyncTask().getActionType(), parameters.getDbAsyncTask().getActionParameters()); } } } @Override public void concreteStartPollingTask() { CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks(); entityInfo.StartPollingTask(getVdsmTaskId()); } @Override protected void onTaskEndSuccess() { logEndTaskSuccess(); endActionIfNecessary(); } private void endActionIfNecessary() { CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks(); if (entityInfo == null) { log.warn("CommandAsyncTask::endActionIfNecessary: No info is available for entity '{}', current" + " task ('{}') was probably created while other tasks were in progress, clearing task.", getCommandId(), getVdsmTaskId()); clearAsyncTask(); } else if (entityInfo.ShouldEndAction() && !hasRunningChildCommands()) { log.info( "CommandAsyncTask::endActionIfNecessary: All tasks of command '{}' has ended -> executing 'endAction'", getCommandId()); log.info("CommandAsyncTask::endAction: Ending action for '{}' tasks (command ID: '{}'): calling endAction '.", entityInfo.getTasksCountCurrentActionType(), entityInfo.getCommandId()); entityInfo.MarkAllWithAttemptingEndAction(); ThreadPoolUtil.execute(new Runnable() { @SuppressWarnings("synthetic-access") @Override public void run() { endCommandAction(); } }); } } private boolean hasRunningChildCommands() { Guid rootCmdId = getParameters().getDbAsyncTask().getRootCommandId(); for (CommandEntity entity : coco.getChildCmdsByParentCmdId(rootCmdId)) { if (!hasCompleted(entity) && !coco.doesCommandContainAsyncTask(entity.getId())) { return true; } } return false; } private boolean hasCompleted(CommandEntity entity) { return CommandStatus.SUCCEEDED.equals(entity.getCommandStatus()) || CommandStatus.FAILED.equals(entity.getCommandStatus()) || CommandStatus.FAILED_RESTARTED.equals(entity.getCommandStatus()); } private void endCommandAction() { CommandMultiAsyncTasks entityInfo = getCommandMultiAsyncTasks(); VdcReturnValueBase vdcReturnValue = null; ExecutionContext context = null; boolean endActionRuntimeException = false; AsyncTask dbAsyncTask = getParameters().getDbAsyncTask(); ArrayList<VdcActionParametersBase> imagesParameters = new ArrayList<VdcActionParametersBase>(); for (EndedTaskInfo taskInfo : entityInfo.getEndedTasksInfo().getTasksInfo()) { VdcActionParametersBase childTaskParameters = taskInfo.getTaskParameters().getDbAsyncTask().getTaskParameters(); boolean childTaskGroupSuccess = childTaskParameters.getTaskGroupSuccess() && taskInfo.getTaskStatus().getTaskEndedSuccessfully(); childTaskParameters .setTaskGroupSuccess(childTaskGroupSuccess); if (!childTaskParameters.equals(dbAsyncTask.getActionParameters())) { imagesParameters.add(childTaskParameters); } } dbAsyncTask.getActionParameters().setImagesParameters(imagesParameters); try { log.info("CommandAsyncTask::endCommandAction [within thread] context: Attempting to endAction '{}'," + " executionIndex: '{}'", dbAsyncTask.getActionParameters().getCommandType(), dbAsyncTask.getActionParameters().getExecutionIndex()); try { /** * Creates context for the job which monitors the action */ Guid stepId = dbAsyncTask.getStepId(); if (stepId != null) { context = ExecutionHandler.createFinalizingContext(stepId); } vdcReturnValue = coco.endAction(this, context); } catch (VdcBLLException ex) { log.error("{}: {}", getErrorMessage(), ex.getMessage()); log.debug("Exception", ex); } catch (RuntimeException ex) { log.error(getErrorMessage(), ex); endActionRuntimeException = true; } } catch (RuntimeException Ex2) { log.error("CommandAsyncTask::endCommandAction [within thread]: An exception has been thrown (not" + " related to 'endAction' itself)", Ex2); endActionRuntimeException = true; } finally { // if a RuntimeExcpetion occurs we clear the task from db and perform no other action if (endActionRuntimeException) { handleEndActionRuntimeException(entityInfo, dbAsyncTask); } else { boolean isTaskGroupSuccess = dbAsyncTask.getActionParameters().getTaskGroupSuccess(); handleEndActionResult(entityInfo, vdcReturnValue, context, isTaskGroupSuccess); } } } private VdcActionType getEndActionType(AsyncTask dbAsyncTask) { VdcActionType commandType = dbAsyncTask.getActionParameters().getCommandType(); if (!VdcActionType.Unknown.equals(commandType)) { return commandType; } return dbAsyncTask.getActionType(); } private String getErrorMessage() { return String.format("[within thread]: endAction for action type %1$s threw an exception.", getParameters().getDbAsyncTask().getActionParameters().getCommandType()); } private void handleEndActionRuntimeException(CommandMultiAsyncTasks commandInfo, AsyncTask dbAsyncTask) { try { VdcActionType actionType = getParameters().getDbAsyncTask().getActionType(); log.info("CommandAsyncTask::HandleEndActionResult: endAction for action type '{}' threw an" + " unrecoverable RuntimeException the task will be cleared.", actionType); commandInfo.clearTaskByVdsmTaskId(dbAsyncTask.getVdsmTaskId()); removeTaskFromDB(); if (commandInfo.getAllCleared()) { log.info("CommandAsyncTask::HandleEndActionRuntimeException: Removing CommandMultiAsyncTasks" + " object for entity '{}'", commandInfo.getCommandId()); synchronized (_lockObject) { _multiTasksByCommandIds.remove(commandInfo.getCommandId()); } } } catch (RuntimeException ex) { log.error("CommandAsyncTask::HandleEndActionResult [within thread]: an exception has been thrown", ex); } } private void handleEndActionResult(CommandMultiAsyncTasks commandInfo, VdcReturnValueBase vdcReturnValue, ExecutionContext context, boolean isTaskGroupSuccess) { try { VdcActionType actionType = getParameters().getDbAsyncTask().getActionType(); log.info("CommandAsyncTask::HandleEndActionResult [within thread]: endAction for action type '{}'" + " completed, handling the result.", actionType); if (vdcReturnValue == null || (!vdcReturnValue.getSucceeded() && vdcReturnValue.getEndActionTryAgain())) { log.info("CommandAsyncTask::HandleEndActionResult [within thread]: endAction for action type" + " '{}' hasn't succeeded, not clearing tasks, will attempt again next polling.", actionType); commandInfo.Repoll(); } else { log.info("CommandAsyncTask::HandleEndActionResult [within thread]: endAction for action type" + " '{}' {}succeeded, clearing tasks.", actionType, vdcReturnValue.getSucceeded() ? "" : "hasn't "); /** * Terminate the job by the return value of endAction. * The operation will end also the FINALIZING step. */ if (context != null) { ExecutionHandler.endTaskJob(context, vdcReturnValue.getSucceeded() && isTaskGroupSuccess); } commandInfo.ClearTasks(); synchronized (_lockObject) { if (commandInfo.getAllCleared()) { log.info("CommandAsyncTask::HandleEndActionResult [within thread]: Removing" + " CommandMultiAsyncTasks object for entity '{}'", commandInfo.getCommandId()); _multiTasksByCommandIds.remove(commandInfo.getCommandId()); } } } } catch (RuntimeException ex) { log.error("CommandAsyncTask::HandleEndActionResult [within thread]: an exception has been thrown", ex); } } @Override protected void onTaskEndFailure() { logEndTaskFailure(); endActionIfNecessary(); } @Override protected void onTaskDoesNotExist() { logTaskDoesntExist(); endActionIfNecessary(); } }
engine: Remove dead code Change-Id: Ibf02a0fc5229c0ca3223e0c2911ce8f24f391ecf Signed-off-by: Moti Asayag <[email protected]>
backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/tasks/CommandAsyncTask.java
engine: Remove dead code
<ide><path>ackend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/tasks/CommandAsyncTask.java <ide> } <ide> } <ide> <del> private VdcActionType getEndActionType(AsyncTask dbAsyncTask) { <del> VdcActionType commandType = dbAsyncTask.getActionParameters().getCommandType(); <del> if (!VdcActionType.Unknown.equals(commandType)) { <del> return commandType; <del> } <del> return dbAsyncTask.getActionType(); <del> } <del> <ide> private String getErrorMessage() { <ide> return String.format("[within thread]: endAction for action type %1$s threw an exception.", <ide> getParameters().getDbAsyncTask().getActionParameters().getCommandType());
Java
apache-2.0
2989fbfaf03eaf40a147395c00ea25dba70ecdd3
0
budioktaviyan/sikerang-android
package id.sikerang.mobile.utils; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; /** * @author Budi Oktaviyan Suryanto ([email protected]) */ public final class LocationTracker implements LocationListener { private static final String TAG = LocationTracker.class.getSimpleName(); private static volatile LocationTracker INSTANCE = null; private final Context mContext; private Location mLocation; private double mLatitude; private double mLongitude; protected LocationManager locationManager; public static synchronized LocationTracker getInstance(Context context) { if (INSTANCE == null) { INSTANCE = new LocationTracker(context); } return INSTANCE; } public LocationTracker(Context context) { mContext = context; getLocation(); } @Override public void onLocationChanged(Location location) { mLocation = location; } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } public Location getLocation() { boolean isGPSEnabled; boolean isNetworkEnabled; try { locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); Log.i(TAG, String.format("isGPSEnabled=%s", isGPSEnabled)); isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); Log.i(TAG, String.format("isNetworkEnabled=%s", isNetworkEnabled)); if (isNetworkEnabled) { mLocation = null; locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, Constants.MIN_TIME, Constants.MIN_DISTANCE, this); Log.i(TAG, "Network is Enabled!"); if (locationManager != null) { mLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (mLocation != null) { mLatitude = mLocation.getLatitude(); mLongitude = mLocation.getLongitude(); } locationManager.removeUpdates(this); } } if (isGPSEnabled) { mLocation = null; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Constants.MIN_TIME, Constants.MIN_DISTANCE, this); Log.i(TAG, "GPS is Enabled!"); if (locationManager != null) { mLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (mLocation != null) { mLatitude = mLocation.getLatitude(); mLongitude = mLocation.getLongitude(); } locationManager.removeUpdates(this); } } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return mLocation; } public double getLatitude() { if (mLocation != null) { mLatitude = mLocation.getLatitude(); } return mLatitude; } public double getLongitude() { if (mLocation != null) { mLongitude = mLocation.getLongitude(); } return mLongitude; } }
src/main/java/id/sikerang/mobile/utils/LocationTracker.java
package id.sikerang.mobile.utils; import android.content.Context; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.os.Bundle; import android.util.Log; /** * @author Budi Oktaviyan Suryanto ([email protected]) */ public final class LocationTracker implements LocationListener { private static final String TAG = LocationTracker.class.getSimpleName(); private static volatile LocationTracker INSTANCE = null; private final Context mContext; private Location mLocation; private double mLatitude; private double mLongitude; protected LocationManager locationManager; public static synchronized LocationTracker getInstance(Context context) { if (INSTANCE == null) { INSTANCE = new LocationTracker(context); } return INSTANCE; } public LocationTracker(Context context) { mContext = context; getLocation(); } @Override public void onLocationChanged(Location location) { mLocation = location; } @Override public void onStatusChanged(String s, int i, Bundle bundle) { } @Override public void onProviderEnabled(String s) { } @Override public void onProviderDisabled(String s) { } public Location getLocation() { boolean isGPSEnabled; boolean isNetworkEnabled; try { locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER); Log.i(TAG, String.format("isGPSEnabled=%s", isGPSEnabled)); isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER); Log.i(TAG, String.format("isNetworkEnabled=%s", isNetworkEnabled)); if (isNetworkEnabled) { mLocation = null; locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, Constants.MIN_TIME, Constants.MIN_DISTANCE, this); Log.i(TAG, "Network is Enabled!"); if (locationManager != null) { mLocation = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (mLocation != null) { mLatitude = mLocation.getLatitude(); mLongitude = mLocation.getLongitude(); } } } if (isGPSEnabled) { mLocation = null; locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, Constants.MIN_TIME, Constants.MIN_DISTANCE, this); Log.i(TAG, "GPS is Enabled!"); if (locationManager != null) { mLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (mLocation != null) { mLatitude = mLocation.getLatitude(); mLongitude = mLocation.getLongitude(); } } } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } return mLocation; } public double getLatitude() { if (mLocation != null) { mLatitude = mLocation.getLatitude(); } return mLatitude; } public double getLongitude() { if (mLocation != null) { mLongitude = mLocation.getLongitude(); } return mLongitude; } }
Fix location manager to switch on/off gps on demand
src/main/java/id/sikerang/mobile/utils/LocationTracker.java
Fix location manager to switch on/off gps on demand
<ide><path>rc/main/java/id/sikerang/mobile/utils/LocationTracker.java <ide> mLatitude = mLocation.getLatitude(); <ide> mLongitude = mLocation.getLongitude(); <ide> } <add> locationManager.removeUpdates(this); <ide> } <ide> } <ide> <ide> mLatitude = mLocation.getLatitude(); <ide> mLongitude = mLocation.getLongitude(); <ide> } <add> locationManager.removeUpdates(this); <ide> } <ide> } <ide> } catch (Exception e) {
Java
apache-2.0
e7899ffec59f9c5e2de4772a3f20740ebbf02bbc
0
CS-SI/Rugged,CS-SI/Rugged
/* Copyright 2013-2014 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS 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.orekit.rugged.core.duvenhage; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.commons.math3.util.FastMath; import org.orekit.bodies.GeodeticPoint; import org.orekit.errors.OrekitException; import org.orekit.rugged.api.RuggedException; import org.orekit.rugged.api.RuggedMessages; import org.orekit.rugged.api.TileUpdater; import org.orekit.rugged.core.ExtendedEllipsoid; import org.orekit.rugged.core.raster.IntersectionAlgorithm; import org.orekit.rugged.core.raster.Tile; import org.orekit.rugged.core.raster.TilesCache; /** Digital Elevation Model intersection using Bernardt Duvenhage's algorithm. * <p> * The algorithm is described in the 2009 paper: * <a href="http://researchspace.csir.co.za/dspace/bitstream/10204/3041/1/Duvenhage_2009.pdf">Using * An Implicit Min/Max KD-Tree for Doing Efficient Terrain Line of Sight Calculations</a>. * </p> * @author Luc Maisonobe */ public class DuvenhageAlgorithm implements IntersectionAlgorithm { /** Step size when skipping from one tile to a neighbor one, in meters. */ private static final double STEP = 0.01; /** Cache for DEM tiles. */ private TilesCache<MinMaxTreeTile> cache; /** Simple constructor. */ public DuvenhageAlgorithm() { } /** {@inheritDoc} */ @Override public void setUpTilesManagement(final TileUpdater updater, final int maxCachedTiles) { cache = new TilesCache<MinMaxTreeTile>(new MinMaxTreeTileFactory(), updater, maxCachedTiles); } /** {@inheritDoc} */ @Override public GeodeticPoint intersection(final ExtendedEllipsoid ellipsoid, final Vector3D position, final Vector3D los) throws RuggedException { try { // compute intersection with ellipsoid final GeodeticPoint gp0 = ellipsoid.pointOnGround(position, los); // locate the entry tile along the line-of-sight MinMaxTreeTile tile = cache.getTile(gp0.getLatitude(), gp0.getLongitude()); GeodeticPoint current = null; double hMax = tile.getMaxElevation(); while (current == null) { // find where line-of-sight crosses tile max altitude final Vector3D entryP = ellipsoid.pointAtAltitude(position, los, hMax + STEP); if (Vector3D.dotProduct(entryP.subtract(position), los) < 0) { // the entry point is behind spacecraft! throw new RuggedException(RuggedMessages.DEM_ENTRY_POINT_IS_BEHIND_SPACECRAFT); } current = ellipsoid.transform(entryP, ellipsoid.getBodyFrame(), null); if (tile.getLocation(current.getLatitude(), current.getLongitude()) != Tile.Location.IN_TILE) { // the entry point is in another tile tile = cache.getTile(current.getLatitude(), current.getLongitude()); hMax = FastMath.max(hMax, tile.getMaxElevation()); current = null; } } // loop along the path while (true) { // find where line-of-sight exit tile final LimitPoint exit = findExit(tile, ellipsoid, position, los); final GeodeticPoint intersection = recurseIntersection(0, ellipsoid, position, los, tile, current, tile.getLatitudeIndex(current.getLatitude()), tile.getLongitudeIndex(current.getLongitude()), exit.getPoint(), tile.getLatitudeIndex(exit.getPoint().getLatitude()), tile.getLongitudeIndex(exit.getPoint().getLongitude())); if (intersection != null) { // we have found the intersection return intersection; } else if (exit.atSide()) { // no intersection on this tile, we can proceed to next part of the line-of-sight // select next tile after current point final Vector3D forward = new Vector3D(1.0, ellipsoid.transform(exit.getPoint()), STEP, los); current = ellipsoid.transform(forward, ellipsoid.getBodyFrame(), null); tile = cache.getTile(current.getLatitude(), current.getLongitude()); if (tile.interpolateElevation(current.getLatitude(), current.getLongitude()) >= current.getAltitude()) { // extremely rare case! The line-of-sight traversed the Digital Elevation Model // during the very short forward step we used to move to next tile // we consider this point to be OK return current; } } else { // this should never happen // we should have left the loop with an intersection point throw RuggedException.createInternalError(null); } } } catch (OrekitException oe) { throw new RuggedException(oe, oe.getSpecifier(), oe.getParts()); } } /** Compute intersection of line with Digital Elevation Model in a sub-tile. * @param recursion depth * @param ellipsoid reference ellipsoid * @param position pixel position in ellipsoid frame * @param los pixel line-of-sight in ellipsoid frame * @param tile Digital Elevation Model tile * @param entry line-of-sight entry point in the sub-tile * @param entryLat index to use for interpolating entry point elevation * @param entryLon index to use for interpolating entry point elevation * @param exit line-of-sight exit point from the sub-tile * @param exitLat index to use for interpolating exit point elevation * @param exitLon index to use for interpolating exit point elevation * @return point at which the line first enters ground, or null if does not enter * ground in the search sub-tile * @exception RuggedException if intersection cannot be found * @exception OrekitException if points cannot be converted to geodetic coordinates */ private GeodeticPoint recurseIntersection(final int depth, final ExtendedEllipsoid ellipsoid, final Vector3D position, final Vector3D los, final MinMaxTreeTile tile, final GeodeticPoint entry, final int entryLat, final int entryLon, final GeodeticPoint exit, final int exitLat, final int exitLon) throws RuggedException, OrekitException { if (depth > 30) { // this should never happen throw RuggedException.createInternalError(null); } if (FastMath.min(entryLat, exitLat) < 0 || FastMath.max(entryLat, exitLat) >= tile.getLatitudeRows() || FastMath.min(entryLon, exitLon) < 0 || FastMath.max(entryLon, exitLon) >= tile.getLongitudeColumns()) { // search segment is outside of tile (probably due to the 1 offset with respect // to a boundary crossing index when splitting line-of-sight in the caller return null; } if (entryLat == exitLat && entryLon == exitLon) { // we have narrowed the search down to a single Digital Elevation Model pixel GeodeticPoint intersection = tile.pixelIntersection(entry, ellipsoid.convertLos(entry, los), exitLat, exitLon); if (intersection != null) { // improve the point, by projecting it back on the 3D line, // fixing the small body curvature remaining at pixel level final Vector3D delta = ellipsoid.transform(intersection).subtract(position); final double s = Vector3D.dotProduct(delta, los) / los.getNormSq(); final GeodeticPoint projected = ellipsoid.transform(new Vector3D(1, position, s, los), ellipsoid.getBodyFrame(), null); intersection = tile.pixelIntersection(projected, ellipsoid.convertLos(projected, los), exitLat, exitLon); } return intersection; } // find the deepest level in the min/max kd-tree at which entry and exit share a sub-tile final int level = tile.getMergeLevel(entryLat, entryLon, exitLat, exitLon); if (level >= 0 && exit.getAltitude() >= tile.getMaxElevation(exitLat, exitLon, level)) { // the line-of-sight segment is fully above Digital Elevation Model // we can safely reject it and proceed to next part of the line-of-sight return null; } GeodeticPoint previousGP = entry; int previousLat = entryLat; int previousLon = entryLon; // introduce all intermediate points corresponding to the line-of-sight // intersecting the boundary between level 0 sub-tiles if (tile.isColumnMerging(level + 1)) { // recurse through longitude crossings final int[] crossings = tile.getCrossedBoundaryColumns(previousLon, exitLon, level + 1); for (final int crossingLon : crossings) { // compute segment endpoints final double longitude = tile.getLongitudeAtIndex(crossingLon); if (longitude >= FastMath.min(entry.getLongitude(), exit.getLongitude()) && longitude <= FastMath.max(entry.getLongitude(), exit.getLongitude())) { final Vector3D crossingP = ellipsoid.pointAtLongitude(position, los, longitude); final GeodeticPoint crossingGP = ellipsoid.transform(crossingP, ellipsoid.getBodyFrame(), null); final int crossingLat = tile.getLatitudeIndex(crossingGP.getLatitude()); // adjust indices as the crossing point is by definition between the sub-tiles final int crossingLonBefore = crossingLon - (entryLon <= exitLon ? 1 : 0); final int crossingLonAfter = crossingLon - (entryLon <= exitLon ? 0 : 1); // look for intersection final GeodeticPoint intersection = recurseIntersection(depth + 1, ellipsoid, position, los, tile, previousGP, previousLat, previousLon, crossingGP, crossingLat, crossingLonBefore); if (intersection != null) { return intersection; } // prepare next segment previousGP = crossingGP; previousLat = crossingLat; previousLon = crossingLonAfter; } } } else { // recurse through latitude crossings final int[] crossings = tile.getCrossedBoundaryRows(previousLat, exitLat, level + 1); for (final int crossingLat : crossings) { // compute segment endpoints final double latitude = tile.getLatitudeAtIndex(crossingLat); if (latitude >= FastMath.min(entry.getLatitude(), exit.getLatitude()) && latitude <= FastMath.max(entry.getLatitude(), exit.getLatitude())) { final Vector3D crossingP = ellipsoid.pointAtLatitude(position, los, tile.getLatitudeAtIndex(crossingLat)); final GeodeticPoint crossingGP = ellipsoid.transform(crossingP, ellipsoid.getBodyFrame(), null); final int crossingLon = tile.getLongitudeIndex(crossingGP.getLongitude()); // adjust indices as the crossing point is by definition between the sub-tiles final int crossingLatBefore = crossingLat - (entryLat <= exitLat ? 1 : 0); final int crossingLatAfter = crossingLat - (entryLat <= exitLat ? 0 : 1); // look for intersection final GeodeticPoint intersection = recurseIntersection(depth + 1, ellipsoid, position, los, tile, previousGP, previousLat, previousLon, crossingGP, crossingLatBefore, crossingLon); if (intersection != null) { return intersection; } // prepare next segment previousGP = crossingGP; previousLat = crossingLatAfter; previousLon = crossingLon; } } } // last part of the segment, up to exit point return recurseIntersection(depth + 1, ellipsoid, position, los, tile, previousGP, previousLat, previousLon, exit, exitLat, exitLon); } /** Compute a line-of-sight exit point from a tile. * @param tile tile to consider * @param ellipsoid reference ellipsoid * @param position pixel position in ellipsoid frame * @param los pixel line-of-sight in ellipsoid frame * @return exit point * @exception RuggedException if exit point cannot be found * @exception OrekitException if geodetic coordinates cannot be computed */ private LimitPoint findExit(final Tile tile, final ExtendedEllipsoid ellipsoid, final Vector3D position, final Vector3D los) throws RuggedException, OrekitException { // look for an exit at bottom final Vector3D exitP = ellipsoid.pointAtAltitude(position, los, tile.getMinElevation() - STEP); final GeodeticPoint exitGP = ellipsoid.transform(exitP, ellipsoid.getBodyFrame(), null); switch (tile.getLocation(exitGP.getLatitude(), exitGP.getLongitude())) { case SOUTH_WEST : return new LimitPoint(ellipsoid, selectClosest(ellipsoid.pointAtLatitude(position, los, tile.getMinimumLatitude()), ellipsoid.pointAtLongitude(position, los, tile.getMinimumLongitude()), position), true); case WEST : return new LimitPoint(ellipsoid, ellipsoid.pointAtLongitude(position, los, tile.getMinimumLongitude()), true); case NORTH_WEST: return new LimitPoint(ellipsoid, selectClosest(ellipsoid.pointAtLatitude(position, los, tile.getMaximumLatitude()), ellipsoid.pointAtLongitude(position, los, tile.getMinimumLongitude()), position), true); case NORTH : return new LimitPoint(ellipsoid, ellipsoid.pointAtLatitude(position, los, tile.getMaximumLatitude()), true); case NORTH_EAST : return new LimitPoint(ellipsoid, selectClosest(ellipsoid.pointAtLatitude(position, los, tile.getMaximumLatitude()), ellipsoid.pointAtLongitude(position, los, tile.getMaximumLongitude()), position), true); case EAST : return new LimitPoint(ellipsoid, ellipsoid.pointAtLongitude(position, los, tile.getMaximumLongitude()), true); case SOUTH_EAST : return new LimitPoint(ellipsoid, selectClosest(ellipsoid.pointAtLatitude(position, los, tile.getMinimumLatitude()), ellipsoid.pointAtLongitude(position, los, tile.getMaximumLongitude()), position), true); case SOUTH : return new LimitPoint(ellipsoid, ellipsoid.pointAtLatitude(position, los, tile.getMinimumLatitude()), true); case IN_TILE : return new LimitPoint(exitGP, false); default : // this should never happen throw RuggedException.createInternalError(null); } } /** Select point closest to line-of-sight start. * @param p1 first point to consider * @param p2 second point to consider * @param position pixel position in ellipsoid frame * @return either p1 or p2, depending on which is closest to position */ private Vector3D selectClosest(final Vector3D p1, final Vector3D p2, final Vector3D position) { return Vector3D.distance(p1, position) <= Vector3D.distance(p2, position) ? p1 : p2; } /** Point at tile boundary. */ private static class LimitPoint { /** Coordinates. */ private final GeodeticPoint point; /** Limit status. */ private final boolean side; /** Simple constructor. * @param cartesian point cartesian * @param ellipsoid reference ellipsoid * @param side if true, the point is on a side limit, otherwise * it is on a top/bottom limit * @exception OrekitException if geodetic coordinates cannot be computed */ public LimitPoint(final ExtendedEllipsoid ellipsoid, final Vector3D cartesian, final boolean side) throws OrekitException { this(ellipsoid.transform(cartesian, ellipsoid.getBodyFrame(), null), side); } /** Simple constructor. * @param point coordinates * @param side if true, the point is on a side limit, otherwise * it is on a top/bottom limit */ public LimitPoint(final GeodeticPoint point, final boolean side) { this.point = point; this.side = side; } /** Get the point coordinates. * @return point coordinates */ public GeodeticPoint getPoint() { return point; } /** Check if point is on the side of a tile. * @return true if the point is on a side limit, otherwise * it is on a top/bottom limit */ public boolean atSide() { return side; } } }
src/main/java/org/orekit/rugged/core/duvenhage/DuvenhageAlgorithm.java
/* Copyright 2013-2014 CS Systèmes d'Information * Licensed to CS Systèmes d'Information (CS) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * CS 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.orekit.rugged.core.duvenhage; import org.apache.commons.math3.geometry.euclidean.threed.Vector3D; import org.apache.commons.math3.util.FastMath; import org.orekit.bodies.GeodeticPoint; import org.orekit.errors.OrekitException; import org.orekit.rugged.api.RuggedException; import org.orekit.rugged.api.RuggedMessages; import org.orekit.rugged.api.TileUpdater; import org.orekit.rugged.core.ExtendedEllipsoid; import org.orekit.rugged.core.raster.IntersectionAlgorithm; import org.orekit.rugged.core.raster.Tile; import org.orekit.rugged.core.raster.TilesCache; /** Digital Elevation Model intersection using Bernardt Duvenhage's algorithm. * <p> * The algorithm is described in the 2009 paper: * <a href="http://researchspace.csir.co.za/dspace/bitstream/10204/3041/1/Duvenhage_2009.pdf">Using * An Implicit Min/Max KD-Tree for Doing Efficient Terrain Line of Sight Calculations</a>. * </p> * @author Luc Maisonobe */ public class DuvenhageAlgorithm implements IntersectionAlgorithm { /** Step size when skipping from one tile to a neighbor one, in meters. */ private static final double STEP = 0.01; /** Cache for DEM tiles. */ private TilesCache<MinMaxTreeTile> cache; /** Simple constructor. */ public DuvenhageAlgorithm() { } /** {@inheritDoc} */ @Override public void setUpTilesManagement(final TileUpdater updater, final int maxCachedTiles) { cache = new TilesCache<MinMaxTreeTile>(new MinMaxTreeTileFactory(), updater, maxCachedTiles); } /** {@inheritDoc} */ @Override public GeodeticPoint intersection(final ExtendedEllipsoid ellipsoid, final Vector3D position, final Vector3D los) throws RuggedException { try { // compute intersection with ellipsoid final GeodeticPoint gp0 = ellipsoid.pointOnGround(position, los); // locate the entry tile along the line-of-sight MinMaxTreeTile tile = cache.getTile(gp0.getLatitude(), gp0.getLongitude()); GeodeticPoint current = null; double hMax = tile.getMaxElevation(); while (current == null) { // find where line-of-sight crosses tile max altitude final Vector3D entryP = ellipsoid.pointAtAltitude(position, los, hMax + STEP); if (Vector3D.dotProduct(entryP.subtract(position), los) < 0) { // the entry point is behind spacecraft! throw new RuggedException(RuggedMessages.DEM_ENTRY_POINT_IS_BEHIND_SPACECRAFT); } current = ellipsoid.transform(entryP, ellipsoid.getBodyFrame(), null); if (tile.getLocation(current.getLatitude(), current.getLongitude()) != Tile.Location.IN_TILE) { // the entry point is in another tile tile = cache.getTile(current.getLatitude(), current.getLongitude()); hMax = FastMath.max(hMax, tile.getMaxElevation()); current = null; } } // loop along the path while (true) { // find where line-of-sight exit tile final LimitPoint exit = findExit(tile, ellipsoid, position, los); final GeodeticPoint intersection = recurseIntersection(0, ellipsoid, position, los, tile, current, tile.getLatitudeIndex(current.getLatitude()), tile.getLongitudeIndex(current.getLongitude()), exit.getPoint(), tile.getLatitudeIndex(exit.getPoint().getLatitude()), tile.getLongitudeIndex(exit.getPoint().getLongitude())); if (intersection != null) { // we have found the intersection return intersection; } else if (exit.atSide()) { // no intersection on this tile, we can proceed to next part of the line-of-sight // select next tile after current point final Vector3D forward = new Vector3D(1.0, ellipsoid.transform(exit.getPoint()), STEP, los); current = ellipsoid.transform(forward, ellipsoid.getBodyFrame(), null); tile = cache.getTile(current.getLatitude(), current.getLongitude()); if (tile.interpolateElevation(current.getLatitude(), current.getLongitude()) <= current.getAltitude()) { // extremely rare case! The line-of-sight traversed the Digital Elevation Model // during the very short forward step we used to move to next tile // we consider this point to be OK return current; } } else { // this should never happen // we should have left the loop with an intersection point throw RuggedException.createInternalError(null); } } } catch (OrekitException oe) { throw new RuggedException(oe, oe.getSpecifier(), oe.getParts()); } } /** Compute intersection of line with Digital Elevation Model in a sub-tile. * @param recursion depth * @param ellipsoid reference ellipsoid * @param position pixel position in ellipsoid frame * @param los pixel line-of-sight in ellipsoid frame * @param tile Digital Elevation Model tile * @param entry line-of-sight entry point in the sub-tile * @param entryLat index to use for interpolating entry point elevation * @param entryLon index to use for interpolating entry point elevation * @param exit line-of-sight exit point from the sub-tile * @param exitLat index to use for interpolating exit point elevation * @param exitLon index to use for interpolating exit point elevation * @return point at which the line first enters ground, or null if does not enter * ground in the search sub-tile * @exception RuggedException if intersection cannot be found * @exception OrekitException if points cannot be converted to geodetic coordinates */ private GeodeticPoint recurseIntersection(final int depth, final ExtendedEllipsoid ellipsoid, final Vector3D position, final Vector3D los, final MinMaxTreeTile tile, final GeodeticPoint entry, final int entryLat, final int entryLon, final GeodeticPoint exit, final int exitLat, final int exitLon) throws RuggedException, OrekitException { if (depth > 30) { // this should never happen throw RuggedException.createInternalError(null); } if (FastMath.min(entryLat, exitLat) < 0 || FastMath.max(entryLat, exitLat) >= tile.getLatitudeRows() || FastMath.min(entryLon, exitLon) < 0 || FastMath.max(entryLon, exitLon) >= tile.getLongitudeColumns()) { // search segment is outside of tile (probably due to the 1 offset with respect // to a boundary crossing index when splitting line-of-sight in the caller return null; } if (entryLat == exitLat && entryLon == exitLon) { // we have narrowed the search down to a single Digital Elevation Model pixel GeodeticPoint intersection = tile.pixelIntersection(entry, ellipsoid.convertLos(entry, los), exitLat, exitLon); if (intersection != null) { // improve the point, by projecting it back on the 3D line, // fixing the small body curvature remaining at pixel level final Vector3D delta = ellipsoid.transform(intersection).subtract(position); final double s = Vector3D.dotProduct(delta, los) / los.getNormSq(); final GeodeticPoint projected = ellipsoid.transform(new Vector3D(1, position, s, los), ellipsoid.getBodyFrame(), null); intersection = tile.pixelIntersection(projected, ellipsoid.convertLos(projected, los), exitLat, exitLon); } return intersection; } // find the deepest level in the min/max kd-tree at which entry and exit share a sub-tile final int level = tile.getMergeLevel(entryLat, entryLon, exitLat, exitLon); if (level >= 0 && exit.getAltitude() >= tile.getMaxElevation(exitLat, exitLon, level)) { // the line-of-sight segment is fully above Digital Elevation Model // we can safely reject it and proceed to next part of the line-of-sight return null; } GeodeticPoint previousGP = entry; int previousLat = entryLat; int previousLon = entryLon; // introduce all intermediate points corresponding to the line-of-sight // intersecting the boundary between level 0 sub-tiles if (tile.isColumnMerging(level + 1)) { // recurse through longitude crossings final int[] crossings = tile.getCrossedBoundaryColumns(previousLon, exitLon, level + 1); for (final int crossingLon : crossings) { // compute segment endpoints final double longitude = tile.getLongitudeAtIndex(crossingLon); if (longitude >= FastMath.min(entry.getLongitude(), exit.getLongitude()) && longitude <= FastMath.max(entry.getLongitude(), exit.getLongitude())) { final Vector3D crossingP = ellipsoid.pointAtLongitude(position, los, longitude); final GeodeticPoint crossingGP = ellipsoid.transform(crossingP, ellipsoid.getBodyFrame(), null); final int crossingLat = tile.getLatitudeIndex(crossingGP.getLatitude()); // adjust indices as the crossing point is by definition between the sub-tiles final int crossingLonBefore = crossingLon - (entryLon <= exitLon ? 1 : 0); final int crossingLonAfter = crossingLon - (entryLon <= exitLon ? 0 : 1); // look for intersection final GeodeticPoint intersection = recurseIntersection(depth + 1, ellipsoid, position, los, tile, previousGP, previousLat, previousLon, crossingGP, crossingLat, crossingLonBefore); if (intersection != null) { return intersection; } // prepare next segment previousGP = crossingGP; previousLat = crossingLat; previousLon = crossingLonAfter; } } } else { // recurse through latitude crossings final int[] crossings = tile.getCrossedBoundaryRows(previousLat, exitLat, level + 1); for (final int crossingLat : crossings) { // compute segment endpoints final double latitude = tile.getLatitudeAtIndex(crossingLat); if (latitude >= FastMath.min(entry.getLatitude(), exit.getLatitude()) && latitude <= FastMath.max(entry.getLatitude(), exit.getLatitude())) { final Vector3D crossingP = ellipsoid.pointAtLatitude(position, los, tile.getLatitudeAtIndex(crossingLat)); final GeodeticPoint crossingGP = ellipsoid.transform(crossingP, ellipsoid.getBodyFrame(), null); final int crossingLon = tile.getLongitudeIndex(crossingGP.getLongitude()); // adjust indices as the crossing point is by definition between the sub-tiles final int crossingLatBefore = crossingLat - (entryLat <= exitLat ? 1 : 0); final int crossingLatAfter = crossingLat - (entryLat <= exitLat ? 0 : 1); // look for intersection final GeodeticPoint intersection = recurseIntersection(depth + 1, ellipsoid, position, los, tile, previousGP, previousLat, previousLon, crossingGP, crossingLatBefore, crossingLon); if (intersection != null) { return intersection; } // prepare next segment previousGP = crossingGP; previousLat = crossingLatAfter; previousLon = crossingLon; } } } // last part of the segment, up to exit point return recurseIntersection(depth + 1, ellipsoid, position, los, tile, previousGP, previousLat, previousLon, exit, exitLat, exitLon); } /** Compute a line-of-sight exit point from a tile. * @param tile tile to consider * @param ellipsoid reference ellipsoid * @param position pixel position in ellipsoid frame * @param los pixel line-of-sight in ellipsoid frame * @return exit point * @exception RuggedException if exit point cannot be found * @exception OrekitException if geodetic coordinates cannot be computed */ private LimitPoint findExit(final Tile tile, final ExtendedEllipsoid ellipsoid, final Vector3D position, final Vector3D los) throws RuggedException, OrekitException { // look for an exit at bottom final Vector3D exitP = ellipsoid.pointAtAltitude(position, los, tile.getMinElevation() - STEP); final GeodeticPoint exitGP = ellipsoid.transform(exitP, ellipsoid.getBodyFrame(), null); switch (tile.getLocation(exitGP.getLatitude(), exitGP.getLongitude())) { case SOUTH_WEST : return new LimitPoint(ellipsoid, selectClosest(ellipsoid.pointAtLatitude(position, los, tile.getMinimumLatitude()), ellipsoid.pointAtLongitude(position, los, tile.getMinimumLongitude()), position), true); case WEST : return new LimitPoint(ellipsoid, ellipsoid.pointAtLongitude(position, los, tile.getMinimumLongitude()), true); case NORTH_WEST: return new LimitPoint(ellipsoid, selectClosest(ellipsoid.pointAtLatitude(position, los, tile.getMaximumLatitude()), ellipsoid.pointAtLongitude(position, los, tile.getMinimumLongitude()), position), true); case NORTH : return new LimitPoint(ellipsoid, ellipsoid.pointAtLatitude(position, los, tile.getMaximumLatitude()), true); case NORTH_EAST : return new LimitPoint(ellipsoid, selectClosest(ellipsoid.pointAtLatitude(position, los, tile.getMaximumLatitude()), ellipsoid.pointAtLongitude(position, los, tile.getMaximumLongitude()), position), true); case EAST : return new LimitPoint(ellipsoid, ellipsoid.pointAtLongitude(position, los, tile.getMaximumLongitude()), true); case SOUTH_EAST : return new LimitPoint(ellipsoid, selectClosest(ellipsoid.pointAtLatitude(position, los, tile.getMinimumLatitude()), ellipsoid.pointAtLongitude(position, los, tile.getMaximumLongitude()), position), true); case SOUTH : return new LimitPoint(ellipsoid, ellipsoid.pointAtLatitude(position, los, tile.getMinimumLatitude()), true); case IN_TILE : return new LimitPoint(exitGP, false); default : // this should never happen throw RuggedException.createInternalError(null); } } /** Select point closest to line-of-sight start. * @param p1 first point to consider * @param p2 second point to consider * @param position pixel position in ellipsoid frame * @return either p1 or p2, depending on which is closest to position */ private Vector3D selectClosest(final Vector3D p1, final Vector3D p2, final Vector3D position) { return Vector3D.distance(p1, position) <= Vector3D.distance(p2, position) ? p1 : p2; } /** Point at tile boundary. */ private static class LimitPoint { /** Coordinates. */ private final GeodeticPoint point; /** Limit status. */ private final boolean side; /** Simple constructor. * @param cartesian point cartesian * @param ellipsoid reference ellipsoid * @param side if true, the point is on a side limit, otherwise * it is on a top/bottom limit * @exception OrekitException if geodetic coordinates cannot be computed */ public LimitPoint(final ExtendedEllipsoid ellipsoid, final Vector3D cartesian, final boolean side) throws OrekitException { this(ellipsoid.transform(cartesian, ellipsoid.getBodyFrame(), null), side); } /** Simple constructor. * @param point coordinates * @param side if true, the point is on a side limit, otherwise * it is on a top/bottom limit */ public LimitPoint(final GeodeticPoint point, final boolean side) { this.point = point; this.side = side; } /** Get the point coordinates. * @return point coordinates */ public GeodeticPoint getPoint() { return point; } /** Check if point is on the side of a tile. * @return true if the point is on a side limit, otherwise * it is on a top/bottom limit */ public boolean atSide() { return side; } } }
Fixed virtual "wall" appearing at tiles boundaries.
src/main/java/org/orekit/rugged/core/duvenhage/DuvenhageAlgorithm.java
Fixed virtual "wall" appearing at tiles boundaries.
<ide><path>rc/main/java/org/orekit/rugged/core/duvenhage/DuvenhageAlgorithm.java <ide> current = ellipsoid.transform(forward, ellipsoid.getBodyFrame(), null); <ide> tile = cache.getTile(current.getLatitude(), current.getLongitude()); <ide> <del> if (tile.interpolateElevation(current.getLatitude(), current.getLongitude()) <= current.getAltitude()) { <add> if (tile.interpolateElevation(current.getLatitude(), current.getLongitude()) >= current.getAltitude()) { <ide> // extremely rare case! The line-of-sight traversed the Digital Elevation Model <ide> // during the very short forward step we used to move to next tile <ide> // we consider this point to be OK
Java
apache-2.0
7ae8ba78321c16178576baa5d42dec871c6f20d6
0
EvilMcJerkface/Aeron,real-logic/Aeron,real-logic/Aeron,real-logic/Aeron,real-logic/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron,mikeb01/Aeron,mikeb01/Aeron,EvilMcJerkface/Aeron,EvilMcJerkface/Aeron,mikeb01/Aeron
/* * Copyright 2014-2020 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron; import io.aeron.driver.DefaultNameResolver; import io.aeron.driver.MediaDriver; import io.aeron.driver.NameResolver; import io.aeron.driver.ThreadingMode; import io.aeron.logbuffer.FragmentHandler; import io.aeron.logbuffer.Header; import io.aeron.logbuffer.LogBufferDescriptor; import io.aeron.test.MediaDriverTestWatcher; import io.aeron.test.SlowTest; import io.aeron.test.TestMediaDriver; import io.aeron.test.Tests; import org.agrona.BitUtil; import org.agrona.CloseHelper; import org.agrona.DirectBuffer; import org.agrona.collections.MutableInteger; import org.agrona.concurrent.UnsafeBuffer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static io.aeron.CommonContext.ENDPOINT_PARAM_NAME; import static io.aeron.CommonContext.MDC_CONTROL_PARAM_NAME; import static org.mockito.Mockito.*; public class NameReResolutionTest { private static final String ENDPOINT_NAME = "ReResTestEndpoint"; private static final String PUBLICATION_MANUAL_MDC_URI = "aeron:udp?control=localhost:24327|control-mode=manual"; private static final String PUBLICATION_URI = "aeron:udp?endpoint=" + ENDPOINT_NAME; private static final String FIRST_SUBSCRIPTION_URI = "aeron:udp?endpoint=localhost:24325"; private static final String SECOND_SUBSCRIPTION_URI = "aeron:udp?endpoint=localhost:24326"; private static final String CONTROL_NAME = "ReResTestControl"; private static final String FIRST_PUBLICATION_DYNAMIC_MDC_URI = "aeron:udp?control=localhost:24327|control-mode=dynamic|linger=0"; private static final String SECOND_PUBLICATION_DYNAMIC_MDC_URI = "aeron:udp?control=localhost:24328|control-mode=dynamic"; private static final String SUBSCRIPTION_DYNAMIC_MDC_URI = "aeron:udp?control=" + CONTROL_NAME + "|control-mode=dynamic"; private static final String SUBSCRIPTION_MDS_URI = "aeron:udp?control-mode=manual"; private static final String STUB_LOOKUP_CONFIGURATION = ENDPOINT_NAME + "," + ENDPOINT_PARAM_NAME + "," + "localhost:24326,localhost:24325|" + CONTROL_NAME + "," + MDC_CONTROL_PARAM_NAME + "," + "localhost:24328,localhost:24327|"; private static final int STREAM_ID = 1001; private Aeron client; private TestMediaDriver driver; private Subscription subscription; private Publication publication; @RegisterExtension public MediaDriverTestWatcher testWatcher = new MediaDriverTestWatcher(); private final UnsafeBuffer buffer = new UnsafeBuffer(new byte[4096]); private final FragmentHandler handler = mock(FragmentHandler.class); private final NameResolver lookupResolver = new StubNameResolver(STUB_LOOKUP_CONFIGURATION); @BeforeEach public void before() { TestMediaDriver.notSupportedOnCMediaDriverYet("ReResolution"); driver = TestMediaDriver.launch( new MediaDriver.Context() .errorHandler(Throwable::printStackTrace) .publicationTermBufferLength(LogBufferDescriptor.TERM_MIN_LENGTH) .threadingMode(ThreadingMode.SHARED) .nameResolver(lookupResolver), testWatcher); client = Aeron.connect(); } @AfterEach public void after() { CloseHelper.closeAll(client, driver); driver.context().deleteDirectory(); } @SlowTest @Test @Timeout(10) public void shouldReResolveEndpointOnNoConnected() throws Exception { buffer.putInt(0, 1); subscription = client.addSubscription(FIRST_SUBSCRIPTION_URI, STREAM_ID); publication = client.addPublication(PUBLICATION_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } final MutableInteger fragmentsRead = new MutableInteger(); Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); fragmentsRead.set(0); subscription.close(); // wait for disconnect to ensure we stay in lock step while (publication.isConnected()) { Thread.sleep(100); Tests.checkInterruptStatus(); } subscription = client.addSubscription(SECOND_SUBSCRIPTION_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); verify(handler, times(2)).onFragment( any(DirectBuffer.class), anyInt(), eq(BitUtil.SIZE_OF_INT), any(Header.class)); } @SlowTest @Test @Timeout(10) public void shouldReResolveMdcManualEndpointOnNoConnected() throws Exception { buffer.putInt(0, 1); subscription = client.addSubscription(FIRST_SUBSCRIPTION_URI, STREAM_ID); publication = client.addPublication(PUBLICATION_MANUAL_MDC_URI, STREAM_ID); publication.addDestination(PUBLICATION_URI); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } final MutableInteger fragmentsRead = new MutableInteger(); Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); fragmentsRead.set(0); subscription.close(); // wait for disconnect to ensure we stay in lock step while (publication.isConnected()) { Thread.sleep(100); Tests.checkInterruptStatus(); } subscription = client.addSubscription(SECOND_SUBSCRIPTION_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); verify(handler, times(2)).onFragment( any(DirectBuffer.class), anyInt(), eq(BitUtil.SIZE_OF_INT), any(Header.class)); } @SlowTest @Test @Timeout(15) public void shouldReResolveMdcDynamicControlOnNoConnected() throws Exception { buffer.putInt(0, 1); subscription = client.addSubscription(SUBSCRIPTION_DYNAMIC_MDC_URI, STREAM_ID); publication = client.addPublication(FIRST_PUBLICATION_DYNAMIC_MDC_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } final MutableInteger fragmentsRead = new MutableInteger(); Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); fragmentsRead.set(0); publication.close(); // wait for disconnect to ensure we stay in lock step while (subscription.isConnected()) { Thread.sleep(100); Tests.checkInterruptStatus(); } publication = client.addPublication(SECOND_PUBLICATION_DYNAMIC_MDC_URI, STREAM_ID); while (!publication.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); verify(handler, times(2)).onFragment( any(DirectBuffer.class), anyInt(), eq(BitUtil.SIZE_OF_INT), any(Header.class)); } @SlowTest @Test @Timeout(15) public void shouldReResolveMdcDynamicControlOnManualDestinationSubscriptionOnNoConnected() throws Exception { TestMediaDriver.notSupportedOnCMediaDriverYet("Multi-Destination-Subscriptions"); buffer.putInt(0, 1); subscription = client.addSubscription(SUBSCRIPTION_MDS_URI, STREAM_ID); subscription.addDestination(SUBSCRIPTION_DYNAMIC_MDC_URI); publication = client.addPublication(FIRST_PUBLICATION_DYNAMIC_MDC_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } final MutableInteger fragmentsRead = new MutableInteger(); Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); fragmentsRead.set(0); publication.close(); // wait for disconnect to ensure we stay in lock step while (subscription.isConnected()) { Thread.sleep(100); Tests.checkInterruptStatus(); } publication = client.addPublication(SECOND_PUBLICATION_DYNAMIC_MDC_URI, STREAM_ID); while (!publication.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); verify(handler, times(2)).onFragment( any(DirectBuffer.class), anyInt(), eq(BitUtil.SIZE_OF_INT), any(Header.class)); } private static class StubNameResolver implements NameResolver { private final List<String[]> lookupNames = new ArrayList<>(); StubNameResolver(final String stubLookupConfiguration) { final String[] lines = stubLookupConfiguration.split("\\|"); for (final String line : lines) { final String[] params = line.split(","); if (4 != params.length) { throw new IllegalArgumentException("Expect 4 elements per row"); } lookupNames.add(params); } } public InetAddress resolve(final String name, final String uriParamName, final boolean isReResolution) { return DefaultNameResolver.INSTANCE.resolve(name, uriParamName, isReResolution); } public String lookup(final String name, final String uriParamName, final boolean isReLookup) { for (final String[] lookupName : lookupNames) { if (lookupName[1].equals(uriParamName) && lookupName[0].equals(name)) { return isReLookup ? lookupName[2] : lookupName[3]; } } return name; } } }
aeron-system-tests/src/test/java/io/aeron/NameReResolutionTest.java
/* * Copyright 2014-2020 Real Logic Limited. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.aeron; import io.aeron.driver.DefaultNameResolver; import io.aeron.driver.MediaDriver; import io.aeron.driver.NameResolver; import io.aeron.driver.ThreadingMode; import io.aeron.logbuffer.FragmentHandler; import io.aeron.logbuffer.Header; import io.aeron.logbuffer.LogBufferDescriptor; import io.aeron.test.MediaDriverTestWatcher; import io.aeron.test.SlowTest; import io.aeron.test.TestMediaDriver; import io.aeron.test.Tests; import org.agrona.BitUtil; import org.agrona.CloseHelper; import org.agrona.DirectBuffer; import org.agrona.collections.MutableInteger; import org.agrona.concurrent.UnsafeBuffer; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.extension.RegisterExtension; import java.net.InetAddress; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import static io.aeron.CommonContext.ENDPOINT_PARAM_NAME; import static io.aeron.CommonContext.MDC_CONTROL_PARAM_NAME; import static org.mockito.Mockito.*; public class NameReResolutionTest { private static final String ENDPOINT_NAME = "ReResTestEndpoint"; private static final String PUBLICATION_MANUAL_MDC_URI = "aeron:udp?control=localhost:24327|control-mode=manual"; private static final String PUBLICATION_URI = "aeron:udp?endpoint=" + ENDPOINT_NAME; private static final String FIRST_SUBSCRIPTION_URI = "aeron:udp?endpoint=localhost:24325"; private static final String SECOND_SUBSCRIPTION_URI = "aeron:udp?endpoint=localhost:24326"; private static final String CONTROL_NAME = "ReResTestControl"; private static final String FIRST_PUBLICATION_DYNAMIC_MDC_URI = "aeron:udp?control=localhost:24327|control-mode=dynamic|linger=0"; private static final String SECOND_PUBLICATION_DYNAMIC_MDC_URI = "aeron:udp?control=localhost:24328|control-mode=dynamic"; private static final String SUBSCRIPTION_DYNAMIC_MDC_URI = "aeron:udp?control=" + CONTROL_NAME + "|control-mode=dynamic"; private static final String SUBSCRIPTION_MDS_URI = "aeron:udp?control-mode=manual"; private static final String STUB_LOOKUP_CONFIGURATION = ENDPOINT_PARAM_NAME + "," + ENDPOINT_NAME + ",localhost:24326,localhost:24325|" + MDC_CONTROL_PARAM_NAME + "," + CONTROL_NAME + ",localhost:24328,localhost:24327|"; private static final int STREAM_ID = 1001; private Aeron client; private TestMediaDriver driver; private Subscription subscription; private Publication publication; @RegisterExtension public MediaDriverTestWatcher testWatcher = new MediaDriverTestWatcher(); private final UnsafeBuffer buffer = new UnsafeBuffer(new byte[4096]); private final FragmentHandler handler = mock(FragmentHandler.class); private final NameResolver lookupResolver = new StubNameResolver(STUB_LOOKUP_CONFIGURATION); @BeforeEach public void before() { TestMediaDriver.notSupportedOnCMediaDriverYet("ReResolution"); driver = TestMediaDriver.launch( new MediaDriver.Context() .errorHandler(Throwable::printStackTrace) .publicationTermBufferLength(LogBufferDescriptor.TERM_MIN_LENGTH) .threadingMode(ThreadingMode.SHARED) .nameResolver(lookupResolver), testWatcher); client = Aeron.connect(); } @AfterEach public void after() { CloseHelper.closeAll(client, driver); driver.context().deleteDirectory(); } @SlowTest @Test @Timeout(10) public void shouldReResolveEndpointOnNoConnected() throws Exception { buffer.putInt(0, 1); subscription = client.addSubscription(FIRST_SUBSCRIPTION_URI, STREAM_ID); publication = client.addPublication(PUBLICATION_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } final MutableInteger fragmentsRead = new MutableInteger(); Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); fragmentsRead.set(0); subscription.close(); // wait for disconnect to ensure we stay in lock step while (publication.isConnected()) { Thread.sleep(100); Tests.checkInterruptStatus(); } subscription = client.addSubscription(SECOND_SUBSCRIPTION_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); verify(handler, times(2)).onFragment( any(DirectBuffer.class), anyInt(), eq(BitUtil.SIZE_OF_INT), any(Header.class)); } @SlowTest @Test @Timeout(10) public void shouldReResolveMdcManualEndpointOnNoConnected() throws Exception { buffer.putInt(0, 1); subscription = client.addSubscription(FIRST_SUBSCRIPTION_URI, STREAM_ID); publication = client.addPublication(PUBLICATION_MANUAL_MDC_URI, STREAM_ID); publication.addDestination(PUBLICATION_URI); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } final MutableInteger fragmentsRead = new MutableInteger(); Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); fragmentsRead.set(0); subscription.close(); // wait for disconnect to ensure we stay in lock step while (publication.isConnected()) { Thread.sleep(100); Tests.checkInterruptStatus(); } subscription = client.addSubscription(SECOND_SUBSCRIPTION_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); verify(handler, times(2)).onFragment( any(DirectBuffer.class), anyInt(), eq(BitUtil.SIZE_OF_INT), any(Header.class)); } @SlowTest @Test @Timeout(15) public void shouldReResolveMdcDynamicControlOnNoConnected() throws Exception { buffer.putInt(0, 1); subscription = client.addSubscription(SUBSCRIPTION_DYNAMIC_MDC_URI, STREAM_ID); publication = client.addPublication(FIRST_PUBLICATION_DYNAMIC_MDC_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } final MutableInteger fragmentsRead = new MutableInteger(); Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); fragmentsRead.set(0); publication.close(); // wait for disconnect to ensure we stay in lock step while (subscription.isConnected()) { Thread.sleep(100); Tests.checkInterruptStatus(); } publication = client.addPublication(SECOND_PUBLICATION_DYNAMIC_MDC_URI, STREAM_ID); while (!publication.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); verify(handler, times(2)).onFragment( any(DirectBuffer.class), anyInt(), eq(BitUtil.SIZE_OF_INT), any(Header.class)); } @SlowTest @Test @Timeout(15) public void shouldReResolveMdcDynamicControlOnManualDestinationSubscriptionOnNoConnected() throws Exception { TestMediaDriver.notSupportedOnCMediaDriverYet("Multi-Destination-Subscriptions"); buffer.putInt(0, 1); subscription = client.addSubscription(SUBSCRIPTION_MDS_URI, STREAM_ID); subscription.addDestination(SUBSCRIPTION_DYNAMIC_MDC_URI); publication = client.addPublication(FIRST_PUBLICATION_DYNAMIC_MDC_URI, STREAM_ID); while (!subscription.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } final MutableInteger fragmentsRead = new MutableInteger(); Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); fragmentsRead.set(0); publication.close(); // wait for disconnect to ensure we stay in lock step while (subscription.isConnected()) { Thread.sleep(100); Tests.checkInterruptStatus(); } publication = client.addPublication(SECOND_PUBLICATION_DYNAMIC_MDC_URI, STREAM_ID); while (!publication.isConnected()) { Thread.yield(); Tests.checkInterruptStatus(); } while (publication.offer(buffer, 0, BitUtil.SIZE_OF_INT) < 0L) { Thread.yield(); Tests.checkInterruptStatus(); } Tests.executeUntil( () -> fragmentsRead.get() > 0, (i) -> { fragmentsRead.value += subscription.poll(handler, 1); Thread.yield(); }, Integer.MAX_VALUE, TimeUnit.MILLISECONDS.toNanos(5900)); verify(handler, times(2)).onFragment( any(DirectBuffer.class), anyInt(), eq(BitUtil.SIZE_OF_INT), any(Header.class)); } private static class StubNameResolver implements NameResolver { private final List<String[]> lookupNames = new ArrayList<>(); StubNameResolver(final String stubLookupConfiguration) { final String[] lines = stubLookupConfiguration.split("\\|"); for (final String line : lines) { final String[] params = line.split(","); if (4 != params.length) { throw new IllegalArgumentException("Expect 4 elements per row"); } lookupNames.add(params); } } public InetAddress resolve(final String name, final String uriParamName, final boolean isReResolution) { return DefaultNameResolver.INSTANCE.resolve(name, uriParamName, isReResolution); } public String lookup(final String name, final String uriParamName, final boolean isReLookup) { for (final String[] lookupName : lookupNames) { if (lookupName[0].equals(uriParamName) && lookupName[1].equals(name)) { return isReLookup ? lookupName[2] : lookupName[3]; } } return name; } } }
[Java] Flip order of parameters in CSV config to match order of parameters in calling function.
aeron-system-tests/src/test/java/io/aeron/NameReResolutionTest.java
[Java] Flip order of parameters in CSV config to match order of parameters in calling function.
<ide><path>eron-system-tests/src/test/java/io/aeron/NameReResolutionTest.java <ide> private static final String SUBSCRIPTION_MDS_URI = "aeron:udp?control-mode=manual"; <ide> <ide> private static final String STUB_LOOKUP_CONFIGURATION = <del> ENDPOINT_PARAM_NAME + "," + ENDPOINT_NAME + ",localhost:24326,localhost:24325|" + <del> MDC_CONTROL_PARAM_NAME + "," + CONTROL_NAME + ",localhost:24328,localhost:24327|"; <add> ENDPOINT_NAME + "," + ENDPOINT_PARAM_NAME + "," + "localhost:24326,localhost:24325|" + <add> CONTROL_NAME + "," + MDC_CONTROL_PARAM_NAME + "," + "localhost:24328,localhost:24327|"; <ide> <ide> private static final int STREAM_ID = 1001; <ide> <ide> { <ide> for (final String[] lookupName : lookupNames) <ide> { <del> if (lookupName[0].equals(uriParamName) && lookupName[1].equals(name)) <add> if (lookupName[1].equals(uriParamName) && lookupName[0].equals(name)) <ide> { <ide> return isReLookup ? lookupName[2] : lookupName[3]; <ide> }
Java
apache-2.0
ef93ba060a3895e22a93291b0a5706b0b44ae6be
0
xkr47/vertx-acme4j,xkr47/vertx-acme4j,xkr47/vertx-acme4j
/* * Copyright 2016-2017 Nitor Creations Oy, Jonas Berlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nitor.vertx.acme4j.tls; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.nitor.vertx.acme4j.async.AsyncKeyPairUtils; import io.nitor.vertx.acme4j.tls.AcmeConfig.Account; import io.nitor.vertx.acme4j.tls.DynamicCertManager.CertCombo; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.shredzone.acme4j.*; import org.shredzone.acme4j.challenge.Challenge; import org.shredzone.acme4j.challenge.TlsSni01Challenge; import org.shredzone.acme4j.challenge.TlsSni02Challenge; import org.shredzone.acme4j.exception.AcmeConflictException; import org.shredzone.acme4j.exception.AcmeException; import org.shredzone.acme4j.exception.AcmeRetryAfterException; import org.shredzone.acme4j.util.CSRBuilder; import org.shredzone.acme4j.util.CertificateUtils; import org.shredzone.acme4j.util.KeyPairUtils; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.security.KeyPair; import java.security.PrivateKey; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.*; import java.util.AbstractMap.SimpleEntry; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static io.vertx.core.Future.*; import static io.vertx.core.buffer.Buffer.buffer; import static java.lang.System.currentTimeMillis; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.stream.Collectors.toList; public class AcmeManager { static final String ACCOUNT_KEY_PAIR_FILE = "account-keypair.pem"; static final String CERTIFICATE_KEY_PAIR_FILE = "certificate-keypair.pem"; static final String DOMAIN_ACCOUNT_LOCATION_FILE = "accountLocation.txt"; static final String ACCEPTED_TERMS_LOCATION_FILE = "acceptedTermsLocation.txt"; static final String ACTIVE_CONF_PATH = "active.json"; //static final String ACME_SERVER_URI = "acme://letsencrypt.org/staging"; // static final String AGREEMENT_URI = "https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"; private static Logger logger = LogManager.getLogger(AcmeManager.class); private final Vertx vertx; private final DynamicCertManager dynamicCertManager; private final String dbPath; private final AcmeConfigManager configManager = new AcmeConfigManager(); private AcmeConfig cur; enum State { NOT_STARTED, UPDATING, OK, FAILED } private State state = State.NOT_STARTED; public AcmeManager(Vertx vertx, DynamicCertManager dynamicCertManager, String dbPath) { this.vertx = vertx; this.dynamicCertManager = dynamicCertManager; this.dbPath = dbPath.endsWith("/") ? dbPath : dbPath + '/'; } class AcmeConfigManager { public Future<Void> update(final AcmeConfig oldC, final AcmeConfig newC) { newC.validate(); return mapDiff(oldC == null ? new HashMap<>() : oldC.accounts, newC.accounts) .stream() .map((account) -> (Function<Future<Void>, Future<Void>>) prev -> { final AccountManager am = new AccountManager(account.key, account.oldValue, account.newValue); final Future<Void> cur = future(); am.updateCached().setHandler(ar1 -> { if (ar1.failed()) { logger.error("While handling account " + account.key, ar1.cause()); prev.setHandler(cur); return; } prev.setHandler(prevResult -> { am.updateOthers().setHandler(ar2 -> { if (ar2.failed()) { logger.error("While handling account " + account.key, ar2.cause()); cur.fail("Some account(s) failed"); return; } cur.handle(prevResult); }); }); }); return cur; }) .reduce(Function::andThen) .orElse(f -> f) .apply(succeededFuture()) .map(v -> { logger.info("Done updating " + newC.accounts.size() + " accounts"); return v; }); } } class AccountManager { final String accountId; final Account oldAOrig; final Account newAOrig; final String oldAccountDbId; final String newAccountDbId; Map<String, Authorization> authorizations; Registration registration; public AccountManager(String accountId, Account oldA, Account newA) { this.accountId = accountId; this.oldAOrig = oldA; this.newAOrig = newA; oldAccountDbId = accountDbIdFor(accountId, oldA); newAccountDbId = accountDbIdFor(accountId, newA); } public Future<Void> updateCached() { if (newAOrig == null || !newAccountDbId.equals(oldAccountDbId)) { // deregister all certificates for old account; account destruction should be handled in some other way return updateCached2(oldAccountDbId, oldAOrig, null) // register all certificates for new account .compose(v -> updateCached2(newAccountDbId, null, newAOrig)); } else { // update all certificates for same account return updateCached2(newAccountDbId, oldAOrig, newAOrig); } } private Future<Void> updateCached2(String accountDbId, Account oldA, Account newA) { Map<String, AcmeConfig.Certificate> oldCs = oldA == null ? new HashMap<>() : oldA.certificates; Map<String, AcmeConfig.Certificate> newCs = newA == null ? new HashMap<>() : newA.certificates; Stream<Future<Void>> futures = mapDiff(oldCs, newCs) .stream() .map((certificate) -> { final CertificateManager cm = new CertificateManager(null, accountDbId, newA.minimumValidityDays, null, certificate.key, certificate.oldValue, certificate.newValue); return cm.updateCached().recover(describeFailure("For certificate " + certificate.key)); }); return join(futures); } public Future<Void> updateOthers() { if (newAOrig == null || !newAccountDbId.equals(oldAccountDbId)) { /*// deregister all certificates for old account; account destruction should be handled in some other way updateOthers2(oldAccountDbId, oldAOrig, null, ar -> { */ // register all certificates for new account return updateOthers2(null); /* }); */ } else { // update all certificates for same account return updateOthers2(oldAOrig); } } public Future<Void> updateOthers2(Account oldA) { return getOrCreateAccountKeyPair(newAccountDbId).compose(accountKeyPair -> { Session session; try { session = new Session(new URI(newAOrig.providerUrl), accountKeyPair); } catch (URISyntaxException e) { return failedFuture(e); } logger.info(accountId + ": Session set up"); return getOrCreateRegistration(newAccountDbId, newAOrig, session).compose(registration -> { this.registration = registration; Map<String, AcmeConfig.Certificate> oldCs = oldA == null ? new HashMap<>() : oldA.certificates; Map<String, AcmeConfig.Certificate> newCs = newAOrig == null ? new HashMap<>() : newAOrig.certificates; Stream<Future<Void>> futures = mapDiff(oldCs, newCs) .stream() .map((certificate) -> { final CertificateManager cm = new CertificateManager(registration, newAccountDbId, newAOrig.minimumValidityDays, this::getAuthorization, certificate.key, certificate.oldValue, certificate.newValue); return cm.updateOthers().recover(describeFailure("For certificate " + certificate.key)); }); return join(futures); }); }); } private Future<Authorization> getAuthorization(String domain) { return (authorizations != null ? succeededFuture(authorizations) : executeBlocking((Future<Map<String, Authorization>> fut) -> { fut.complete(authorizations = new AbstractCollection<Authorization>() { @Override public Iterator<Authorization> iterator() { try { return registration.getAuthorizations(); } catch (AcmeException e) { throw new RuntimeException("Problem fetching existing authorizations", e); } } @Override public int size() { throw new UnsupportedOperationException(); } }.stream().collect(Collectors.toMap(Authorization::getDomain, t -> t))); })).compose(fut -> { Authorization authorization = authorizations.get(domain); return authorization != null ? succeededFuture(authorization) : executeBlocking((Future<Authorization> fut2) -> { try { fut2.complete(registration.authorizeDomain(domain)); } catch (AcmeException e) { fut2.fail(new RuntimeException("Problem creating new authorization", e)); } }); }); } private String accountDbIdFor(String accountId, Account account) { try { return account == null ? null : accountId + '-' + URLEncoder.encode(account.providerUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private Future<KeyPair> getOrCreateAccountKeyPair(String accountDbId) { String accountKeyPairFile = dbPath + accountDbId + '-' + ACCOUNT_KEY_PAIR_FILE; return getOrCreateKeyPair("account", accountKeyPairFile, () -> AsyncKeyPairUtils.createKeyPair(vertx, 4096)); //keyPairFut = AsyncKeyPairUtils.createECKeyPair(vertx, "secp256r1"); } private Future<Registration> getOrCreateRegistration(String accountDbId, Account account, Session session) { // TODO update registration when agreement, contact or others change (save to file what were last used values) String domainAccountLocationFile = dbPath + accountDbId + '-' + DOMAIN_ACCOUNT_LOCATION_FILE; final List<String> contactURIs = account.contactURIs == null ? Collections.emptyList() : account.contactURIs; return future((Future<Boolean> fut) -> vertx.fileSystem().exists(domainAccountLocationFile, fut)).recover( describeFailure("Domain account location file check")).compose((Boolean keyFileExists) -> { if (keyFileExists) { logger.info("Domain account location file " + domainAccountLocationFile + " exists, using.."); return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(domainAccountLocationFile, fut)).recover( describeFailure("Domain account location file read")).compose(domainAccountLocation -> { String locationStr = domainAccountLocation.toString(); logger.info("Domain account location: " + locationStr); URI location; try { location = new URI(locationStr); } catch (URISyntaxException e) { return failedFuture(e); } Registration registration = Registration.bind(session, location); logger.info("Registration successfully bound"); return succeededFuture(new SimpleEntry<>(registration, false)); }); } else { return executeBlocking((Future<Entry<Registration, Boolean>> createFut) -> { logger.info("No domain account location file, attempting to create new registration"); RegistrationBuilder builder = new RegistrationBuilder(); for (String uri : contactURIs) { builder.addContact(uri); } boolean created = false; Registration registration; try { registration = builder.create(session); created = true; logger.info("Registration successfully created"); } catch (AcmeConflictException e) { logger.info("Registration existed, using provided location: " + e.getLocation()); registration = Registration.bind(session, e.getLocation()); logger.info("Registration successfully bound"); } catch (AcmeException e) { createFut.fail(e); return; } createFut.complete(new SimpleEntry<>(registration, created)); }).compose(creation -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(domainAccountLocationFile, buffer(creation.getKey().getLocation().toASCIIString()), fut)) .recover(describeFailure("Domain account location file write")) .map(v -> { logger.info("Domain account location file " + domainAccountLocationFile + " saved"); return creation; })); } }).compose(registrationCombo -> { final Registration registration = registrationCombo.getKey(); final boolean created = registrationCombo.getValue(); String acceptedTermsLocationFile = dbPath + accountDbId + '-' + ACCEPTED_TERMS_LOCATION_FILE; boolean contactsChanged = !created && !registration.getContacts().equals(account.contactURIs.stream().map(URI::create).collect(Collectors.toList())); return (contactsChanged || created ? succeededFuture(true) : future((Future<Boolean> fut) -> vertx.fileSystem().exists(acceptedTermsLocationFile, fut)).recover( describeFailure("Accepted terms location file check")).compose(termsFileExists -> !termsFileExists ? succeededFuture(true) : future((Future<Buffer> fut) -> vertx.fileSystem().readFile(acceptedTermsLocationFile, fut)).recover( describeFailure("Accepted terms location file read")).map(buf -> !buf.toString().equals(account.acceptedAgreementUrl))) ).compose(registrationPropsChanged -> { if (!registrationPropsChanged) { return succeededFuture(registration); } Registration.EditableRegistration editableRegistration = registration.modify(); List<URI> editableContacts = editableRegistration.getContacts(); editableContacts.clear(); for (String uri : contactURIs) { editableContacts.add(URI.create(uri)); } editableRegistration.setAgreement(URI.create(account.acceptedAgreementUrl)); return executeBlocking(fut -> { try { editableRegistration.commit(); future((Future<Void> fut2) -> vertx.fileSystem().writeFile(acceptedTermsLocationFile, buffer(account.acceptedAgreementUrl), fut2)) .recover(describeFailure("Accepted terms location file write")) .map(registration) .setHandler(fut); } catch (AcmeException e) { fut.fail(e); } }); }); }); } } class CertificateManager { final Registration registration; final String accountDbId; final int minimumValidityDays; final Function<String, Future<Authorization>> getAuthorization; final String certificateId; final String fullCertificateId; final AcmeConfig.Certificate oldC; final AcmeConfig.Certificate newC; final String privateKeyFile; final String certificateFile; public CertificateManager(Registration registration, String accountDbId, int minimumValidityDays, Function<String, Future<Authorization>> getAuthorization, String certificateId, AcmeConfig.Certificate oldC, AcmeConfig.Certificate newC) { this.registration = registration; this.accountDbId = accountDbId; this.minimumValidityDays = minimumValidityDays; this.getAuthorization = getAuthorization; this.certificateId = certificateId; this.fullCertificateId = accountDbId + "-" + certificateId; this.oldC = oldC; this.newC = newC; privateKeyFile = dbPath + accountDbId + "-" + certificateId + "-key.pem"; certificateFile = dbPath + accountDbId + "-" + certificateId + "-certchain.pem"; } public Future<Void> updateCached() { if (newC == null) { // deregister certificate; certificate destruction should be handled in some other way dynamicCertManager.remove(fullCertificateId); return succeededFuture(); } if (dynamicCertManager.get(fullCertificateId) != null) { // already loaded return succeededFuture(); } final Future<Boolean> certificateFileExists = future((Future<Boolean> fut) -> vertx.fileSystem().exists(certificateFile, fut)) .recover(describeFailure("Certificate file check")); final Future<Boolean> privateKeyFileExists = future((Future<Boolean> fut) -> vertx.fileSystem().exists(privateKeyFile, fut)) .recover(describeFailure("Private key file check")); return join(asList(certificateFileExists, privateKeyFileExists).stream()).compose(x -> succeededFuture(certificateFileExists.result() && privateKeyFileExists.result())).compose(filesExist -> { if (!filesExist) { // some files missing, can't use cached data return succeededFuture(); } Future<Buffer> certificateFut = future((Future<Buffer> fut) -> vertx.fileSystem().readFile(certificateFile, fut)) .recover(describeFailure("Certificate file read")); Future<Buffer> privateKeyFut = future((Future<Buffer> fut) -> vertx.fileSystem().readFile(privateKeyFile, fut)) .recover(describeFailure("Private key file read")); return executeBlocking((Future<Void> fut) -> { X509Certificate[] certChain = PemLoader.loadCerts(certificateFut.result()); PrivateKey privateKey = PemLoader.loadPrivateKey(privateKeyFut.result()); // TODO consider filtering subset of hostnames to be served dynamicCertManager.put(fullCertificateId, privateKey, certChain); fut.complete(); }); }); } public Future<Void> updateOthers() { if (newC == null) { return succeededFuture(); } if (oldC.equals(newC)) { // certificate is configuration-wise up-to-date CertCombo certCombo = dynamicCertManager.get(fullCertificateId); if (certCombo != null) { X509Certificate cert = (X509Certificate) certCombo.certWithChain[0]; try { cert.checkValidity(new Date(currentTimeMillis() + DAYS.toMillis(minimumValidityDays))); return succeededFuture(); } catch (CertificateNotYetValidException e) { return failedFuture(new RuntimeException("Unexpected certificate validity period", e)); } catch (CertificateExpiredException e) { // not valid anymore in <minimumValidityDays> days, request new } } } logger.info("Domains to authorize: {}", newC.hostnames); return chain(newC.hostnames .stream() .map((domainName) -> (Supplier<Future<Void>>) () -> { logger.info("Authorizing domain {}", domainName); /* } catch (AcmeUnauthorizedException e) { if (registration.getAgreement().equals(AGREEMENT_URI)) { logger.info("Agreeing to " + AGREEMENT_URI); registration.modify().setAgreement(new URI(AGREEMENT_URI)).commit(); auth = registration.authorizeDomain(domainName); } else { throw new RuntimeException("You need to agree to the Subscriber Agreement at: " + registration.getAgreement(), e); } } */ return getAuthorization.apply(domainName).compose(auth -> executeBlocking((Future<Status> fut) -> fut.complete(auth.getStatus())).compose(status -> { logger.info("Domain {} authorization status: {}", domainName, status); if (status == Status.VALID) return succeededFuture(); // TODO what statuses really? logger.info("Challenge combinations supported: " + auth.getCombinations()); Collection<Challenge> combination = auth.findCombination(SUPPORTED_CHALLENGES); logger.info("Challenges to complete: " + combination); return chain(combination.stream().map(challenge -> (Supplier<Future<Void>>) () -> executeChallenge(domainName, challenge))).map(v -> { logger.info("Domain {} successfully associated with account", domainName); return null; }); })).<Void>mapEmpty(); })) .compose(v -> { logger.info("All domains successfully authorized by account"); return createCertificate(registration, accountDbId, certificateId, privateKeyFile, certificateFile, newC.hostnames, newC.organization).map(w -> { logger.info("Certificate successfully activated. All done."); return w; }); }); } public void writePrivateKey(PrivateKey key, Writer w) throws IOException { try (JcaPEMWriter jw = new JcaPEMWriter(w)) { jw.writeObject(key); } } private Future<KeyPair> getOrCreateCertificateKeyPair() { String certificateKeyPairFile = dbPath + accountDbId + '-' + certificateId + "-" + CERTIFICATE_KEY_PAIR_FILE; //keyPairFut = AsyncKeyPairUtils.createECKeyPair(vertx, "secp256r1"); return getOrCreateKeyPair("certificate", certificateKeyPairFile, () -> AsyncKeyPairUtils.createKeyPair(vertx, 4096)); } private Future<Void> createCertificate(Registration registration, String accountDbId, String certificateId, String privateKeyFile, String certificateFile, List<String> domainNames, String organization) { logger.info("Creating private key"); return getOrCreateCertificateKeyPair().compose(domainKeyPair -> executeBlocking((Future<Void> fut) -> { // write(privateKeyFile, w -> writePrivateKey(domainKeyPair.getPrivate(), w)); final CSRBuilder csrb; try { logger.info("Creating certificate request (CSR)"); csrb = new CSRBuilder(); for (String domainName : domainNames) { csrb.addDomain(domainName); } csrb.setOrganization(organization); csrb.sign(domainKeyPair); logger.info("Saving certificate request for renewal purposes"); StringWriter sw = new StringWriter(); csrb.write(sw); final Buffer buffer = buffer(sw.toString()); future((Future<Void> fut2) -> { String csrFile = dbPath + accountDbId + "-" + certificateId + "-cert-request.csr"; vertx.fileSystem().writeFile(csrFile, buffer, fut2); }).recover(describeFailure("Certificate Request file write")).compose(v -> { logger.info("Requesting certificate meta.."); return fetchWithRetry(() -> registration.requestCertificate(csrb.getEncoded())) .recover(describeFailure("Certificate request")).compose(certificate -> { logger.info("Requesting certificate.."); return fetchWithRetry(() -> certificate.download()) .recover(describeFailure("Certificate download")).compose(cert -> { logger.info("Requesting certificate chain.."); return fetchWithRetry(() -> certificate.downloadChain()) .recover(describeFailure("Certificate chain download")).compose(chain -> { logger.info("Saving certificate chain"); return executeBlocking((Future<Buffer> writeCert) -> { try { StringWriter certSw = new StringWriter(); CertificateUtils.writeX509CertificateChain(certSw, cert, chain); writeCert.complete(buffer(certSw.toString())); } catch (IOException e) { writeCert.fail(e); } }).compose(certBuffer -> future((Future<Void> fut4) -> vertx.fileSystem().writeFile(certificateFile, certBuffer, fut4)) .recover(describeFailure("Certificate file write")).compose(vv -> { logger.info("Installing certificate"); dynamicCertManager.put("letsencrypt-cert-" + certificateId, domainKeyPair.getPrivate(), cert, chain); return Future.<Void>succeededFuture(); })); }); }); }); }).setHandler(fut); } catch (IOException e) { fut.fail(e); return; } })); } private final String[] SUPPORTED_CHALLENGES = { TlsSni01Challenge.TYPE, TlsSni02Challenge.TYPE }; private Future<Void> executeChallenge(String domainName, Challenge challenge) { return executeBlocking((Future<String> fut) -> { try { KeyPair sniKeyPair = KeyPairUtils.createKeyPair(4096); X509Certificate cert; switch (challenge.getType()) { case TlsSni01Challenge.TYPE: { TlsSni01Challenge c = (TlsSni01Challenge) challenge; cert = CertificateUtils.createTlsSniCertificate(sniKeyPair, c.getSubject()); break; } case TlsSni02Challenge.TYPE: { TlsSni02Challenge c = (TlsSni02Challenge) challenge; cert = CertificateUtils.createTlsSni02Certificate(sniKeyPair, c.getSubject(), c.getSanB()); break; } default: throw new UnsupportedOperationException("Internal error, unsupported challenge type " + challenge.getType()); } final String id = "letsencrypt-challenge-" + domainName; dynamicCertManager.put(id, sniKeyPair.getPrivate(), cert); logger.info("Challenge {} prepared, executing..", challenge.getType()); challenge.trigger(); fut.complete(id); } catch (Exception e) { fut.fail(e); } }).compose(id -> { return fetchWithRetry(new Callable<Boolean>() { Status reportedStatus = null; @Override public Boolean call() throws Exception { if (challenge.getStatus() != reportedStatus) { logger.info("Challenge status: " + challenge.getStatus()); reportedStatus = challenge.getStatus(); } if (challenge.getStatus() == Status.VALID || challenge.getStatus() == Status.INVALID) { // final state return true; } challenge.update(); return null; } }).recover(t -> { dynamicCertManager.remove(id); logger.info("Challenge {} cleaned up", challenge.getType()); return failedFuture(t); }).compose(s -> { logger.info("Challenge execution completed with status " + challenge.getStatus()); dynamicCertManager.remove(id); logger.info("Challenge {} cleaned up", challenge.getType()); if (challenge.getStatus() == Status.VALID) { return succeededFuture(); } return failedFuture(new RuntimeException("Challenge " + challenge.getType() + " for " + domainName + " failed with status " + challenge.getStatus())); }); }); } } private String activeConfigPath() { return dbPath + ACTIVE_CONF_PATH; } public Future<Void> start() { return initDb().compose(v -> { if (state != State.NOT_STARTED) { throw new IllegalStateException("Already started"); } synchronized (AcmeManager.this) { state = State.UPDATING; } String file = activeConfigPath(); return doUpdate(future((Future<Boolean> fut) -> vertx.fileSystem().exists(file, fut)) .recover(describeFailure("Error checking previous config " + file)) .compose(exists -> exists ? readConf(file) : future((Future<AcmeConfig> fut) -> { AcmeConfig emptyConf = new AcmeConfig(); emptyConf.accounts = emptyMap(); fut.complete(emptyConf); }))); }); } public Future<Void> start(AcmeConfig conf) { return initDb().compose(v -> configure(State.NOT_STARTED, conf)); } public Future<Void> reconfigure(AcmeConfig conf) { return configure(State.OK, conf); } private Future<Void> configure(State expectedState, AcmeConfig conf) { synchronized (AcmeManager.this) { if (state != expectedState) { throw new IllegalStateException("Wrong state " + state); } state = State.UPDATING; } final AcmeConfig conf2 = conf.clone(); // TODO if something goes wrong on account level, continue with other accounts before failing // TODO likewise for certificate level return doUpdate(succeededFuture(conf2)); } Future<Void> doUpdate(Future<AcmeConfig> confFut) { return confFut.compose(conf -> configManager.update(cur, conf).compose(v -> { cur = conf; return writeConf(activeConfigPath(), conf); })) .map(v -> { synchronized (AcmeManager.this) { state = State.OK; } return v; }).recover(t -> { synchronized (AcmeManager.this) { state = State.FAILED; } return failedFuture(t); }); } private Future<Void> initDb() { return future((Future<Void> fut) -> vertx.fileSystem().mkdirs(dbPath, fut)) .recover(describeFailure("DB directory create")); } private Future<AcmeConfig> readConf(final String file) { return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(file, fut)) .recover(describeFailure("Error loading previous config " + file)) .compose(buf -> executeBlocking(fut -> { try { ObjectMapper objectMapper = new ObjectMapper(); fut.complete(objectMapper.readValue(buf.getBytes(), AcmeConfig.class)); } catch (IOException e) { fut.fail(new RuntimeException("Previous config file " + file + " broken", e)); } })); } private Future<Void> writeConf(final String file, final AcmeConfig newConf) { return executeBlocking(((Future<Buffer> fut) -> { try { fut.complete(buffer(new ObjectMapper().writeValueAsBytes(newConf))); } catch (JsonProcessingException e) { fut.fail(e); } })).compose(buf -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(file, buf, fut)) .recover(describeFailure("Active config file write"))); } private static <K, V> List<MapDiff<K,V>> mapDiff(final Map<K, V> old, final Map<K, V> nev) { List<MapDiff<K, V>> res = old.entrySet().stream() .map(e -> new MapDiff<>(e.getKey(), e.getValue(), nev.get(e.getKey()))) .collect(toList()); List<MapDiff<K, V>> res2 = nev.entrySet().stream() .filter(e -> !old.containsKey(e.getKey())) .map(e -> new MapDiff<>(e.getKey(), null, e.getValue())) .collect(toList()); res.addAll(res2); return res; } private <T> Function<Throwable, Future<T>> describeFailure(String msg) { return t -> failedFuture(new RuntimeException(msg, t)); } Future<KeyPair> getOrCreateKeyPair(String type, final String keyPairFile, final Supplier<Future<KeyPair>> creator) { return future((Future<Boolean> fut) -> vertx.fileSystem().exists(keyPairFile, fut)) .recover(describeFailure("Keypair for " + type + " file check")).compose(keyFileExists -> { if (keyFileExists) { // file exists return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(keyPairFile, fut)) .recover(describeFailure("Keypair for " + type + " file read")) .compose(existingKeyFile -> AsyncKeyPairUtils.readKeyPair(vertx, existingKeyFile)) .map((KeyPair readKeyPair) -> { logger.info("Existing " + type + " keypair read from " + keyPairFile); return readKeyPair; }); } else { // file doesn't exist return creator.get().compose(createdKeyPair -> AsyncKeyPairUtils.writeKeyPair(vertx, createdKeyPair) .compose(keyPairSerialized -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(keyPairFile, keyPairSerialized, fut)) .recover(describeFailure("Keypar for " + type + " file write"))) .map(v -> { logger.info("New " + type + " keypair written to " + keyPairFile); return createdKeyPair; })); } }); } <T> Future<T> fetchWithRetry(Callable<T> blockingHandler) { return future((Future<T> fut) -> fetchWithRetry(blockingHandler, fut)); } <T> void fetchWithRetry(Callable<T> blockingHandler, Future<T> done) { vertx.executeBlocking((Future<T> fut) -> { try { fut.complete(blockingHandler.call()); } catch (Exception e) { fut.fail(e); } }, ar -> { if (ar.failed() && !(ar.cause() instanceof AcmeRetryAfterException)) { done.fail(ar.cause()); return; } if (ar.succeeded() && ar.result() != null) { done.complete(ar.result()); return; } long nextSleep = ar.succeeded() ? 3000 : ((AcmeRetryAfterException) ar.cause()).getRetryAfter().getTime() - currentTimeMillis(); logger.info("Recheck in {}ms", nextSleep); vertx.setTimer(nextSleep, timerId -> fetchWithRetry(blockingHandler, done)); }); } public static class MapDiff<K, V> { public final K key; public final V oldValue; public final V newValue; public MapDiff(K key, V oldValue, V newValue) { this.key = key; this.oldValue = oldValue; this.newValue = newValue; } } // wait for all futures to finish, discard success values, collect & wrap all exceptions thrown, returned as failed future static <T> Future<Void> join(Stream<Future<T>> futures) { return futures .map((fut) -> (Function<Future<List<Throwable>>, Future<List<Throwable>>>) prev -> prev.compose(throwables -> { Future<List<Throwable>> res = future(); fut.setHandler(futRes -> { if (futRes.failed()) { throwables.add(futRes.cause()); } res.complete(throwables); }); return res; })) .reduce(Function::andThen) .orElse(f -> f) .apply(succeededFuture(new ArrayList<>())) .compose(throwables -> { if (!throwables.isEmpty()) { return failedFuture(MultiException.wrapIfNeeded(throwables)); } return succeededFuture(); }); } // for a stream of callable functions returning futures, execute each in order, waiting for the previous' Future to complete, and returning a future completing when all completes. Aborts on failure, returning failure without executing rest of futures static Future<Void> chain(Stream<Supplier<Future<Void>>> stream) { return stream.reduce((Supplier<Future<Void>> a, Supplier<Future<Void>> b) -> () -> a.get().compose(v -> b.get())) .orElse(() -> succeededFuture()) .get(); } <T> Future<T> executeBlocking(Handler<Future<T>> blockingHandler) { return future((Future<T> fut) -> vertx.executeBlocking(blockingHandler, fut)); } }
src/main/java/io/nitor/vertx/acme4j/tls/AcmeManager.java
/* * Copyright 2016-2017 Nitor Creations Oy, Jonas Berlin * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nitor.vertx.acme4j.tls; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import io.nitor.vertx.acme4j.async.AsyncKeyPairUtils; import io.nitor.vertx.acme4j.tls.AcmeConfig.Account; import io.nitor.vertx.acme4j.tls.DynamicCertManager.CertCombo; import io.vertx.core.Future; import io.vertx.core.Handler; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.bouncycastle.openssl.jcajce.JcaPEMWriter; import org.shredzone.acme4j.*; import org.shredzone.acme4j.challenge.Challenge; import org.shredzone.acme4j.challenge.TlsSni01Challenge; import org.shredzone.acme4j.challenge.TlsSni02Challenge; import org.shredzone.acme4j.exception.AcmeConflictException; import org.shredzone.acme4j.exception.AcmeException; import org.shredzone.acme4j.exception.AcmeRetryAfterException; import org.shredzone.acme4j.util.CSRBuilder; import org.shredzone.acme4j.util.CertificateUtils; import org.shredzone.acme4j.util.KeyPairUtils; import java.io.IOException; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.security.KeyPair; import java.security.PrivateKey; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateNotYetValidException; import java.security.cert.X509Certificate; import java.util.*; import java.util.AbstractMap.SimpleEntry; import java.util.Map.Entry; import java.util.concurrent.Callable; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static io.vertx.core.Future.*; import static io.vertx.core.buffer.Buffer.buffer; import static java.lang.System.currentTimeMillis; import static java.util.Arrays.asList; import static java.util.Collections.emptyMap; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.stream.Collectors.toList; public class AcmeManager { static final String ACCOUNT_KEY_PAIR_FILE = "account-keypair.pem"; static final String CERTIFICATE_KEY_PAIR_FILE = "certificate-keypair.pem"; static final String DOMAIN_ACCOUNT_LOCATION_FILE = "accountLocation.txt"; static final String ACCEPTED_TERMS_LOCATION_FILE = "acceptedTermsLocation.txt"; static final String ACTIVE_CONF_PATH = "active.json"; //static final String ACME_SERVER_URI = "acme://letsencrypt.org/staging"; // static final String AGREEMENT_URI = "https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"; private static Logger logger = LogManager.getLogger(AcmeManager.class); private final Vertx vertx; private final DynamicCertManager dynamicCertManager; private final String dbPath; private final AcmeConfigManager configManager = new AcmeConfigManager(); private AcmeConfig cur; enum State { NOT_STARTED, UPDATING, OK, FAILED } private State state = State.NOT_STARTED; public AcmeManager(Vertx vertx, DynamicCertManager dynamicCertManager, String dbPath) { this.vertx = vertx; this.dynamicCertManager = dynamicCertManager; this.dbPath = dbPath.endsWith("/") ? dbPath : dbPath + '/'; } class AcmeConfigManager { public Future<Void> update(final AcmeConfig oldC, final AcmeConfig newC) { newC.validate(); return mapDiff(oldC == null ? new HashMap<>() : oldC.accounts, newC.accounts) .stream() .map((account) -> (Function<Future<Void>, Future<Void>>) prev -> { final AccountManager am = new AccountManager(account.key, account.oldValue, account.newValue); final Future<Void> cur = future(); am.updateCached().setHandler(ar1 -> { if (ar1.failed()) { logger.error("While handling account " + account.key, ar1.cause()); prev.setHandler(cur); return; } prev.setHandler(prevResult -> { am.updateOthers().setHandler(ar2 -> { if (ar2.failed()) { logger.error("While handling account " + account.key, ar2.cause()); cur.fail("Some account(s) failed"); return; } cur.handle(prevResult); }); }); }); return cur; }) .reduce(Function::andThen) .orElse(f -> f) .apply(succeededFuture()) .map(v -> { logger.info("Done updating " + newC.accounts.size() + " accounts"); return v; }); } } class AccountManager { final String accountId; final Account oldAOrig; final Account newAOrig; final String oldAccountDbId; final String newAccountDbId; Map<String, Authorization> authorizations; Registration registration; public AccountManager(String accountId, Account oldA, Account newA) { this.accountId = accountId; this.oldAOrig = oldA; this.newAOrig = newA; oldAccountDbId = accountDbIdFor(accountId, oldA); newAccountDbId = accountDbIdFor(accountId, newA); } public Future<Void> updateCached() { if (newAOrig == null || !newAccountDbId.equals(oldAccountDbId)) { // deregister all certificates for old account; account destruction should be handled in some other way return updateCached2(oldAccountDbId, oldAOrig, null) // register all certificates for new account .compose(v -> updateCached2(newAccountDbId, null, newAOrig)); } else { // update all certificates for same account return updateCached2(newAccountDbId, oldAOrig, newAOrig); } } private Future<Void> updateCached2(String accountDbId, Account oldA, Account newA) { Map<String, AcmeConfig.Certificate> oldCs = oldA == null ? new HashMap<>() : oldA.certificates; Map<String, AcmeConfig.Certificate> newCs = newA == null ? new HashMap<>() : newA.certificates; Stream<Future<Void>> futures = mapDiff(oldCs, newCs) .stream() .map((certificate) -> { final CertificateManager cm = new CertificateManager(null, accountDbId, newA.minimumValidityDays, null, certificate.key, certificate.oldValue, certificate.newValue); return cm.updateCached().recover(describeFailure("For certificate " + certificate.key)); }); return join(futures); } public Future<Void> updateOthers() { if (newAOrig == null || !newAccountDbId.equals(oldAccountDbId)) { /*// deregister all certificates for old account; account destruction should be handled in some other way updateOthers2(oldAccountDbId, oldAOrig, null, ar -> { */ // register all certificates for new account return updateOthers2(null); /* }); */ } else { // update all certificates for same account return updateOthers2(oldAOrig); } } public Future<Void> updateOthers2(Account oldA) { return getOrCreateAccountKeyPair(newAccountDbId).compose(accountKeyPair -> { Session session; try { session = new Session(new URI(newAOrig.providerUrl), accountKeyPair); } catch (URISyntaxException e) { return failedFuture(e); } logger.info(accountId + ": Session set up"); return getOrCreateRegistration(newAccountDbId, newAOrig, session).compose(registration -> { this.registration = registration; Map<String, AcmeConfig.Certificate> oldCs = oldA == null ? new HashMap<>() : oldA.certificates; Map<String, AcmeConfig.Certificate> newCs = newAOrig == null ? new HashMap<>() : newAOrig.certificates; Stream<Future<Void>> futures = mapDiff(oldCs, newCs) .stream() .map((certificate) -> { final CertificateManager cm = new CertificateManager(registration, newAccountDbId, newAOrig.minimumValidityDays, this::getAuthorization, certificate.key, certificate.oldValue, certificate.newValue); return cm.updateOthers().recover(describeFailure("For certificate " + certificate.key)); }); return join(futures); }); }); } private Future<Authorization> getAuthorization(String domain) { return (authorizations != null ? succeededFuture(authorizations) : executeBlocking((Future<Map<String, Authorization>> fut) -> { fut.complete(authorizations = new AbstractCollection<Authorization>() { @Override public Iterator<Authorization> iterator() { try { return registration.getAuthorizations(); } catch (AcmeException e) { throw new RuntimeException("Problem fetching existing authorizations", e); } } @Override public int size() { throw new UnsupportedOperationException(); } }.stream().collect(Collectors.toMap(Authorization::getDomain, t -> t))); })).compose(fut -> { Authorization authorization = authorizations.get(domain); return authorization != null ? succeededFuture(authorization) : executeBlocking((Future<Authorization> fut2) -> { try { fut2.complete(registration.authorizeDomain(domain)); } catch (AcmeException e) { fut2.fail(new RuntimeException("Problem creating new authorization", e)); } }); }); } private String accountDbIdFor(String accountId, Account account) { try { return account == null ? null : accountId + '-' + URLEncoder.encode(account.providerUrl, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } } private Future<KeyPair> getOrCreateAccountKeyPair(String accountDbId) { String accountKeyPairFile = dbPath + accountDbId + '-' + ACCOUNT_KEY_PAIR_FILE; return getOrCreateKeyPair("account", accountKeyPairFile, () -> AsyncKeyPairUtils.createKeyPair(vertx, 4096)); //keyPairFut = AsyncKeyPairUtils.createECKeyPair(vertx, "secp256r1"); } private Future<Registration> getOrCreateRegistration(String accountDbId, Account account, Session session) { // TODO update registration when agreement, contact or others change (save to file what were last used values) String domainAccountLocationFile = dbPath + accountDbId + '-' + DOMAIN_ACCOUNT_LOCATION_FILE; final List<String> contactURIs = account.contactURIs == null ? Collections.emptyList() : account.contactURIs; return future((Future<Boolean> fut) -> vertx.fileSystem().exists(domainAccountLocationFile, fut)).compose((Boolean keyFileExists) -> { if (keyFileExists) { logger.info("Domain account location file " + domainAccountLocationFile + " exists, using.."); return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(domainAccountLocationFile, fut)).compose(domainAccountLocation -> { String locationStr = domainAccountLocation.toString(); logger.info("Domain account location: " + locationStr); URI location; try { location = new URI(locationStr); } catch (URISyntaxException e) { return failedFuture(e); } Registration registration = Registration.bind(session, location); logger.info("Registration successfully bound"); return succeededFuture(new SimpleEntry<>(registration, false)); }); } else { return executeBlocking((Future<Entry<Registration, Boolean>> createFut) -> { logger.info("No domain account location file, attempting to create new registration"); RegistrationBuilder builder = new RegistrationBuilder(); for (String uri : contactURIs) { builder.addContact(uri); } boolean created = false; Registration registration; try { registration = builder.create(session); created = true; logger.info("Registration successfully created"); } catch (AcmeConflictException e) { logger.info("Registration existed, using provided location: " + e.getLocation()); registration = Registration.bind(session, e.getLocation()); logger.info("Registration successfully bound"); } catch (AcmeException e) { createFut.fail(e); return; } createFut.complete(new SimpleEntry<>(registration, created)); }).compose(creation -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(domainAccountLocationFile, buffer(creation.getKey().getLocation().toASCIIString()), fut)) .map(v -> { logger.info("Domain account location file " + domainAccountLocationFile + " saved"); return creation; })); } }).compose(registrationCombo -> { final Registration registration = registrationCombo.getKey(); final boolean created = registrationCombo.getValue(); String acceptedTermsLocationFile = dbPath + accountDbId + '-' + ACCEPTED_TERMS_LOCATION_FILE; boolean contactsChanged = !created && !registration.getContacts().equals(account.contactURIs.stream().map(URI::create).collect(Collectors.toList())); return (contactsChanged || created ? succeededFuture(true) : future((Future<Boolean> fut) -> vertx.fileSystem().exists(acceptedTermsLocationFile, fut)).compose(termsFileExists -> !termsFileExists ? succeededFuture(true) : future((Future<Buffer> fut) -> vertx.fileSystem().readFile(acceptedTermsLocationFile, fut)).map(buf -> !buf.toString().equals(account.acceptedAgreementUrl))) ).compose(registrationPropsChanged -> { if (!registrationPropsChanged) { return succeededFuture(registration); } Registration.EditableRegistration editableRegistration = registration.modify(); List<URI> editableContacts = editableRegistration.getContacts(); editableContacts.clear(); for (String uri : contactURIs) { editableContacts.add(URI.create(uri)); } editableRegistration.setAgreement(URI.create(account.acceptedAgreementUrl)); return executeBlocking(fut -> { try { editableRegistration.commit(); vertx.fileSystem().writeFile(acceptedTermsLocationFile, buffer(account.acceptedAgreementUrl), ar -> fut.handle(ar.map(registration))); } catch (AcmeException e) { fut.fail(e); } }); }); }); } } class CertificateManager { final Registration registration; final String accountDbId; final int minimumValidityDays; final Function<String, Future<Authorization>> getAuthorization; final String certificateId; final String fullCertificateId; final AcmeConfig.Certificate oldC; final AcmeConfig.Certificate newC; final String privateKeyFile; final String certificateFile; public CertificateManager(Registration registration, String accountDbId, int minimumValidityDays, Function<String, Future<Authorization>> getAuthorization, String certificateId, AcmeConfig.Certificate oldC, AcmeConfig.Certificate newC) { this.registration = registration; this.accountDbId = accountDbId; this.minimumValidityDays = minimumValidityDays; this.getAuthorization = getAuthorization; this.certificateId = certificateId; this.fullCertificateId = accountDbId + "-" + certificateId; this.oldC = oldC; this.newC = newC; privateKeyFile = dbPath + accountDbId + "-" + certificateId + "-key.pem"; certificateFile = dbPath + accountDbId + "-" + certificateId + "-certchain.pem"; } public Future<Void> updateCached() { if (newC == null) { // deregister certificate; certificate destruction should be handled in some other way dynamicCertManager.remove(fullCertificateId); return succeededFuture(); } if (dynamicCertManager.get(fullCertificateId) != null) { // already loaded return succeededFuture(); } final Future<Boolean> certificateFileExists = future((Future<Boolean> fut) -> vertx.fileSystem().exists(certificateFile, fut)); final Future<Boolean> privateKeyFileExists = future((Future<Boolean> fut) -> vertx.fileSystem().exists(privateKeyFile, fut)); return join(asList(certificateFileExists, privateKeyFileExists).stream()).compose(x -> succeededFuture(certificateFileExists.result() && privateKeyFileExists.result())).compose(filesExist -> { if (!filesExist) { // some files missing, can't use cached data return succeededFuture(); } Future<Buffer> certificateFut = future((Future<Buffer> fut) -> vertx.fileSystem().readFile(certificateFile, fut)); Future<Buffer> privateKeyFut = future((Future<Buffer> fut) -> vertx.fileSystem().readFile(privateKeyFile, fut)); return executeBlocking((Future<Void> fut) -> { X509Certificate[] certChain = PemLoader.loadCerts(certificateFut.result()); PrivateKey privateKey = PemLoader.loadPrivateKey(privateKeyFut.result()); // TODO consider filtering subset of hostnames to be served dynamicCertManager.put(fullCertificateId, privateKey, certChain); fut.complete(); }); }); } public Future<Void> updateOthers() { if (newC == null) { return succeededFuture(); } if (oldC.equals(newC)) { // certificate is configuration-wise up-to-date CertCombo certCombo = dynamicCertManager.get(fullCertificateId); if (certCombo != null) { X509Certificate cert = (X509Certificate) certCombo.certWithChain[0]; try { cert.checkValidity(new Date(currentTimeMillis() + DAYS.toMillis(minimumValidityDays))); return succeededFuture(); } catch (CertificateNotYetValidException e) { return failedFuture(new RuntimeException("Unexpected certificate validity period", e)); } catch (CertificateExpiredException e) { // not valid anymore in <minimumValidityDays> days, request new } } } logger.info("Domains to authorize: {}", newC.hostnames); return chain(newC.hostnames .stream() .map((domainName) -> (Supplier<Future<Void>>) () -> { logger.info("Authorizing domain {}", domainName); /* } catch (AcmeUnauthorizedException e) { if (registration.getAgreement().equals(AGREEMENT_URI)) { logger.info("Agreeing to " + AGREEMENT_URI); registration.modify().setAgreement(new URI(AGREEMENT_URI)).commit(); auth = registration.authorizeDomain(domainName); } else { throw new RuntimeException("You need to agree to the Subscriber Agreement at: " + registration.getAgreement(), e); } } */ return getAuthorization.apply(domainName).compose(auth -> executeBlocking((Future<Status> fut) -> fut.complete(auth.getStatus())).compose(status -> { logger.info("Domain {} authorization status: {}", domainName, status); if (status == Status.VALID) return succeededFuture(); // TODO what statuses really? logger.info("Challenge combinations supported: " + auth.getCombinations()); Collection<Challenge> combination = auth.findCombination(SUPPORTED_CHALLENGES); logger.info("Challenges to complete: " + combination); return chain(combination.stream().map(challenge -> (Supplier<Future<Void>>) () -> executeChallenge(domainName, challenge))).map(v -> { logger.info("Domain {} successfully associated with account", domainName); return null; }); })).<Void>mapEmpty(); })) .compose(v -> { logger.info("All domains successfully authorized by account"); return createCertificate(registration, accountDbId, certificateId, privateKeyFile, certificateFile, newC.hostnames, newC.organization).map(w -> { logger.info("Certificate successfully activated. All done."); return w; }); }); } public void writePrivateKey(PrivateKey key, Writer w) throws IOException { try (JcaPEMWriter jw = new JcaPEMWriter(w)) { jw.writeObject(key); } } private Future<KeyPair> getOrCreateCertificateKeyPair() { String certificateKeyPairFile = dbPath + accountDbId + '-' + certificateId + "-" + CERTIFICATE_KEY_PAIR_FILE; //keyPairFut = AsyncKeyPairUtils.createECKeyPair(vertx, "secp256r1"); return getOrCreateKeyPair("certificate", certificateKeyPairFile, () -> AsyncKeyPairUtils.createKeyPair(vertx, 4096)); } private Future<Void> createCertificate(Registration registration, String accountDbId, String certificateId, String privateKeyFile, String certificateFile, List<String> domainNames, String organization) { logger.info("Creating private key"); return getOrCreateCertificateKeyPair().compose(domainKeyPair -> executeBlocking((Future<Void> fut) -> { // write(privateKeyFile, w -> writePrivateKey(domainKeyPair.getPrivate(), w)); final CSRBuilder csrb; try { logger.info("Creating certificate request (CSR)"); csrb = new CSRBuilder(); for (String domainName : domainNames) { csrb.addDomain(domainName); } csrb.setOrganization(organization); csrb.sign(domainKeyPair); logger.info("Saving certificate request for renewal purposes"); StringWriter sw = new StringWriter(); csrb.write(sw); final Buffer buffer = buffer(sw.toString()); future((Future<Void> fut2) -> { String csrFile = dbPath + accountDbId + "-" + certificateId + "-cert-request.csr"; vertx.fileSystem().writeFile(csrFile, buffer, fut2); }).compose(v -> { logger.info("Requesting certificate meta.."); return fetchWithRetry(() -> registration.requestCertificate(csrb.getEncoded())).compose(certificate -> { logger.info("Requesting certificate.."); return fetchWithRetry(() -> certificate.download()).compose(cert -> { logger.info("Requesting certificate chain.."); return fetchWithRetry(() -> certificate.downloadChain()).compose(chain -> { logger.info("Saving certificate chain"); return executeBlocking((Future<Buffer> writeCert) -> { try { StringWriter certSw = new StringWriter(); CertificateUtils.writeX509CertificateChain(certSw, cert, chain); writeCert.complete(buffer(certSw.toString())); } catch (IOException e) { writeCert.fail(e); } }).compose(certBuffer -> future((Future<Void> fut4) -> vertx.fileSystem().writeFile(certificateFile, certBuffer, fut4)).compose(vv -> { logger.info("Installing certificate"); dynamicCertManager.put("letsencrypt-cert-" + certificateId, domainKeyPair.getPrivate(), cert, chain); return Future.<Void>succeededFuture(); })); }); }); }); }).setHandler(fut); } catch (IOException e) { fut.fail(e); return; } })); } private final String[] SUPPORTED_CHALLENGES = { TlsSni01Challenge.TYPE, TlsSni02Challenge.TYPE }; private Future<Void> executeChallenge(String domainName, Challenge challenge) { return executeBlocking((Future<String> fut) -> { try { KeyPair sniKeyPair = KeyPairUtils.createKeyPair(4096); X509Certificate cert; switch (challenge.getType()) { case TlsSni01Challenge.TYPE: { TlsSni01Challenge c = (TlsSni01Challenge) challenge; cert = CertificateUtils.createTlsSniCertificate(sniKeyPair, c.getSubject()); break; } case TlsSni02Challenge.TYPE: { TlsSni02Challenge c = (TlsSni02Challenge) challenge; cert = CertificateUtils.createTlsSni02Certificate(sniKeyPair, c.getSubject(), c.getSanB()); break; } default: throw new UnsupportedOperationException("Internal error, unsupported challenge type " + challenge.getType()); } final String id = "letsencrypt-challenge-" + domainName; dynamicCertManager.put(id, sniKeyPair.getPrivate(), cert); logger.info("Challenge {} prepared, executing..", challenge.getType()); challenge.trigger(); fut.complete(id); } catch (Exception e) { fut.fail(e); } }).compose(id -> { return fetchWithRetry(new Callable<Boolean>() { Status reportedStatus = null; @Override public Boolean call() throws Exception { if (challenge.getStatus() != reportedStatus) { logger.info("Challenge status: " + challenge.getStatus()); reportedStatus = challenge.getStatus(); } if (challenge.getStatus() == Status.VALID || challenge.getStatus() == Status.INVALID) { // final state return true; } challenge.update(); return null; } }).recover(t -> { dynamicCertManager.remove(id); logger.info("Challenge {} cleaned up", challenge.getType()); return failedFuture(t); }).compose(s -> { logger.info("Challenge execution completed with status " + challenge.getStatus()); dynamicCertManager.remove(id); logger.info("Challenge {} cleaned up", challenge.getType()); if (challenge.getStatus() == Status.VALID) { return succeededFuture(); } return failedFuture(new RuntimeException("Challenge " + challenge.getType() + " for " + domainName + " failed with status " + challenge.getStatus())); }); }); } } private String activeConfigPath() { return dbPath + ACTIVE_CONF_PATH; } public Future<Void> start() { if (state != State.NOT_STARTED) { throw new IllegalStateException("Already started"); } synchronized (AcmeManager.this) { state = State.UPDATING; } String file = activeConfigPath(); return doUpdate(future((Future<Boolean> fut) -> vertx.fileSystem().exists(file, fut)) .recover(describeFailure("Error checking previous config " + file)) .compose(exists -> exists ? readConf(file) : future((Future<AcmeConfig> fut) -> { AcmeConfig emptyConf = new AcmeConfig(); emptyConf.accounts = emptyMap(); fut.complete(emptyConf); }))); } public Future<Void> start(AcmeConfig conf) { return configure(State.NOT_STARTED, conf); } public Future<Void> reconfigure(AcmeConfig conf) { return configure(State.OK, conf); } private Future<Void> configure(State expectedState, AcmeConfig conf) { synchronized (AcmeManager.this) { if (state != expectedState) { throw new IllegalStateException("Wrong state " + state); } state = State.UPDATING; } final AcmeConfig conf2 = conf.clone(); // TODO if something goes wrong on account level, continue with other accounts before failing // TODO likewise for certificate level return doUpdate(succeededFuture(conf2)); } Future<Void> doUpdate(Future<AcmeConfig> confFut) { return confFut.compose(conf -> configManager.update(cur, conf).compose(v -> { cur = conf; return writeConf(activeConfigPath(), conf); })) .map(v -> { synchronized (AcmeManager.this) { state = State.OK; } return v; }).recover(t -> { synchronized (AcmeManager.this) { state = State.FAILED; } return failedFuture(t); }); } private Future<AcmeConfig> readConf(final String file) { return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(file, fut)) .recover(describeFailure("Error loading previous config " + file)) .compose(buf -> executeBlocking(fut -> { try { ObjectMapper objectMapper = new ObjectMapper(); fut.complete(objectMapper.readValue(buf.getBytes(), AcmeConfig.class)); } catch (IOException e) { fut.fail(new RuntimeException("Previous config file " + file + " broken", e)); } })); } private Future<Void> writeConf(final String file, final AcmeConfig newConf) { return executeBlocking(((Future<Buffer> fut) -> { try { fut.complete(buffer(new ObjectMapper().writeValueAsBytes(newConf))); } catch (JsonProcessingException e) { fut.fail(e); } })).compose(buf -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(file, buf, fut))); } private static <K, V> List<MapDiff<K,V>> mapDiff(final Map<K, V> old, final Map<K, V> nev) { List<MapDiff<K, V>> res = old.entrySet().stream() .map(e -> new MapDiff<>(e.getKey(), e.getValue(), nev.get(e.getKey()))) .collect(toList()); List<MapDiff<K, V>> res2 = nev.entrySet().stream() .filter(e -> !old.containsKey(e.getKey())) .map(e -> new MapDiff<>(e.getKey(), null, e.getValue())) .collect(toList()); res.addAll(res2); return res; } private <T> Function<Throwable, Future<T>> describeFailure(String msg) { return t -> failedFuture(new RuntimeException(msg, t)); } Future<KeyPair> getOrCreateKeyPair(String type, final String keyPairFile, final Supplier<Future<KeyPair>> creator) { return future((Future<Boolean> fut) -> vertx.fileSystem().exists(keyPairFile, fut)).compose(keyFileExists -> { if (keyFileExists) { // file exists return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(keyPairFile, fut)) .compose(existingKeyFile -> AsyncKeyPairUtils.readKeyPair(vertx, existingKeyFile)) .map((KeyPair readKeyPair) -> { logger.info("Existing " + type + " keypair read from " + keyPairFile); return readKeyPair; }); } else { // file doesn't exist return creator.get().compose(createdKeyPair -> AsyncKeyPairUtils.writeKeyPair(vertx, createdKeyPair) .compose(keyPairSerialized -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(keyPairFile, keyPairSerialized, fut))) .map(v -> { logger.info("New " + type + " keypair written to " + keyPairFile); return createdKeyPair; })); } }); } <T> Future<T> fetchWithRetry(Callable<T> blockingHandler) { return future((Future<T> fut) -> fetchWithRetry(blockingHandler, fut)); } <T> void fetchWithRetry(Callable<T> blockingHandler, Future<T> done) { vertx.executeBlocking((Future<T> fut) -> { try { fut.complete(blockingHandler.call()); } catch (Exception e) { fut.fail(e); } }, ar -> { if (ar.failed() && !(ar.cause() instanceof AcmeRetryAfterException)) { done.fail(ar.cause()); return; } if (ar.succeeded() && ar.result() != null) { done.complete(ar.result()); return; } long nextSleep = ar.succeeded() ? 3000 : ((AcmeRetryAfterException) ar.cause()).getRetryAfter().getTime() - currentTimeMillis(); logger.info("Recheck in {}ms", nextSleep); vertx.setTimer(nextSleep, timerId -> fetchWithRetry(blockingHandler, done)); }); } public static class MapDiff<K, V> { public final K key; public final V oldValue; public final V newValue; public MapDiff(K key, V oldValue, V newValue) { this.key = key; this.oldValue = oldValue; this.newValue = newValue; } } // wait for all futures to finish, discard success values, collect & wrap all exceptions thrown, returned as failed future static <T> Future<Void> join(Stream<Future<T>> futures) { return futures .map((fut) -> (Function<Future<List<Throwable>>, Future<List<Throwable>>>) prev -> prev.compose(throwables -> { Future<List<Throwable>> res = future(); fut.setHandler(futRes -> { if (futRes.failed()) { throwables.add(futRes.cause()); } res.complete(throwables); }); return res; })) .reduce(Function::andThen) .orElse(f -> f) .apply(succeededFuture(new ArrayList<>())) .compose(throwables -> { if (!throwables.isEmpty()) { return failedFuture(MultiException.wrapIfNeeded(throwables)); } return succeededFuture(); }); } // for a stream of callable functions returning futures, execute each in order, waiting for the previous' Future to complete, and returning a future completing when all completes. Aborts on failure, returning failure without executing rest of futures static Future<Void> chain(Stream<Supplier<Future<Void>>> stream) { return stream.reduce((Supplier<Future<Void>> a, Supplier<Future<Void>> b) -> () -> a.get().compose(v -> b.get())) .orElse(() -> succeededFuture()) .get(); } <T> Future<T> executeBlocking(Handler<Future<T>> blockingHandler) { return future((Future<T> fut) -> vertx.executeBlocking(blockingHandler, fut)); } }
Describe failures & ensure DB dir is created
src/main/java/io/nitor/vertx/acme4j/tls/AcmeManager.java
Describe failures & ensure DB dir is created
<ide><path>rc/main/java/io/nitor/vertx/acme4j/tls/AcmeManager.java <ide> // TODO update registration when agreement, contact or others change (save to file what were last used values) <ide> String domainAccountLocationFile = dbPath + accountDbId + '-' + DOMAIN_ACCOUNT_LOCATION_FILE; <ide> final List<String> contactURIs = account.contactURIs == null ? Collections.emptyList() : account.contactURIs; <del> return future((Future<Boolean> fut) -> vertx.fileSystem().exists(domainAccountLocationFile, fut)).compose((Boolean keyFileExists) -> { <add> return future((Future<Boolean> fut) -> vertx.fileSystem().exists(domainAccountLocationFile, fut)).recover( <add> describeFailure("Domain account location file check")).compose((Boolean keyFileExists) -> { <ide> if (keyFileExists) { <ide> logger.info("Domain account location file " + domainAccountLocationFile + " exists, using.."); <del> return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(domainAccountLocationFile, fut)).compose(domainAccountLocation -> { <add> return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(domainAccountLocationFile, fut)).recover( <add> describeFailure("Domain account location file read")).compose(domainAccountLocation -> { <ide> String locationStr = domainAccountLocation.toString(); <ide> logger.info("Domain account location: " + locationStr); <ide> URI location; <ide> createFut.complete(new SimpleEntry<>(registration, created)); <ide> }).compose(creation -> future((Future<Void> fut) -> <ide> vertx.fileSystem().writeFile(domainAccountLocationFile, buffer(creation.getKey().getLocation().toASCIIString()), fut)) <add> .recover(describeFailure("Domain account location file write")) <ide> .map(v -> { <ide> logger.info("Domain account location file " + domainAccountLocationFile + " saved"); <ide> return creation; <ide> String acceptedTermsLocationFile = dbPath + accountDbId + '-' + ACCEPTED_TERMS_LOCATION_FILE; <ide> boolean contactsChanged = !created && !registration.getContacts().equals(account.contactURIs.stream().map(URI::create).collect(Collectors.toList())); <ide> return (contactsChanged || created ? succeededFuture(true) : <del> future((Future<Boolean> fut) -> vertx.fileSystem().exists(acceptedTermsLocationFile, fut)).compose(termsFileExists -> <add> future((Future<Boolean> fut) -> vertx.fileSystem().exists(acceptedTermsLocationFile, fut)).recover( <add> describeFailure("Accepted terms location file check")).compose(termsFileExists -> <ide> !termsFileExists ? succeededFuture(true) : <del> future((Future<Buffer> fut) -> vertx.fileSystem().readFile(acceptedTermsLocationFile, fut)).map(buf -> <add> future((Future<Buffer> fut) -> vertx.fileSystem().readFile(acceptedTermsLocationFile, fut)).recover( <add> describeFailure("Accepted terms location file read")).map(buf -> <ide> !buf.toString().equals(account.acceptedAgreementUrl))) <ide> ).compose(registrationPropsChanged -> { <ide> if (!registrationPropsChanged) { <ide> return executeBlocking(fut -> { <ide> try { <ide> editableRegistration.commit(); <del> vertx.fileSystem().writeFile(acceptedTermsLocationFile, buffer(account.acceptedAgreementUrl), ar -> <del> fut.handle(ar.map(registration))); <add> future((Future<Void> fut2) -> vertx.fileSystem().writeFile(acceptedTermsLocationFile, buffer(account.acceptedAgreementUrl), fut2)) <add> .recover(describeFailure("Accepted terms location file write")) <add> .map(registration) <add> .setHandler(fut); <ide> } catch (AcmeException e) { <ide> fut.fail(e); <ide> } <ide> // already loaded <ide> return succeededFuture(); <ide> } <del> final Future<Boolean> certificateFileExists = future((Future<Boolean> fut) -> vertx.fileSystem().exists(certificateFile, fut)); <del> final Future<Boolean> privateKeyFileExists = future((Future<Boolean> fut) -> vertx.fileSystem().exists(privateKeyFile, fut)); <add> final Future<Boolean> certificateFileExists = future((Future<Boolean> fut) -> vertx.fileSystem().exists(certificateFile, fut)) <add> .recover(describeFailure("Certificate file check")); <add> final Future<Boolean> privateKeyFileExists = future((Future<Boolean> fut) -> vertx.fileSystem().exists(privateKeyFile, fut)) <add> .recover(describeFailure("Private key file check")); <ide> return join(asList(certificateFileExists, privateKeyFileExists).stream()).compose(x -> <ide> succeededFuture(certificateFileExists.result() && privateKeyFileExists.result())).compose(filesExist -> { <ide> if (!filesExist) { <ide> // some files missing, can't use cached data <ide> return succeededFuture(); <ide> } <del> Future<Buffer> certificateFut = future((Future<Buffer> fut) -> vertx.fileSystem().readFile(certificateFile, fut)); <del> Future<Buffer> privateKeyFut = future((Future<Buffer> fut) -> vertx.fileSystem().readFile(privateKeyFile, fut)); <add> Future<Buffer> certificateFut = future((Future<Buffer> fut) -> vertx.fileSystem().readFile(certificateFile, fut)) <add> .recover(describeFailure("Certificate file read")); <add> Future<Buffer> privateKeyFut = future((Future<Buffer> fut) -> vertx.fileSystem().readFile(privateKeyFile, fut)) <add> .recover(describeFailure("Private key file read")); <ide> return executeBlocking((Future<Void> fut) -> { <ide> X509Certificate[] certChain = PemLoader.loadCerts(certificateFut.result()); <ide> PrivateKey privateKey = PemLoader.loadPrivateKey(privateKeyFut.result()); <ide> future((Future<Void> fut2) -> { <ide> String csrFile = dbPath + accountDbId + "-" + certificateId + "-cert-request.csr"; <ide> vertx.fileSystem().writeFile(csrFile, buffer, fut2); <del> }).compose(v -> { <add> }).recover(describeFailure("Certificate Request file write")).compose(v -> { <ide> logger.info("Requesting certificate meta.."); <del> return fetchWithRetry(() -> registration.requestCertificate(csrb.getEncoded())).compose(certificate -> { <add> return fetchWithRetry(() -> registration.requestCertificate(csrb.getEncoded())) <add> .recover(describeFailure("Certificate request")).compose(certificate -> { <ide> logger.info("Requesting certificate.."); <del> return fetchWithRetry(() -> certificate.download()).compose(cert -> { <add> return fetchWithRetry(() -> certificate.download()) <add> .recover(describeFailure("Certificate download")).compose(cert -> { <ide> logger.info("Requesting certificate chain.."); <del> return fetchWithRetry(() -> certificate.downloadChain()).compose(chain -> { <add> return fetchWithRetry(() -> certificate.downloadChain()) <add> .recover(describeFailure("Certificate chain download")).compose(chain -> { <ide> logger.info("Saving certificate chain"); <ide> return executeBlocking((Future<Buffer> writeCert) -> { <ide> try { <ide> writeCert.fail(e); <ide> } <ide> }).compose(certBuffer -> <del> future((Future<Void> fut4) -> vertx.fileSystem().writeFile(certificateFile, certBuffer, fut4)).compose(vv -> { <add> future((Future<Void> fut4) -> vertx.fileSystem().writeFile(certificateFile, certBuffer, fut4)) <add> .recover(describeFailure("Certificate file write")).compose(vv -> { <ide> logger.info("Installing certificate"); <ide> dynamicCertManager.put("letsencrypt-cert-" + certificateId, domainKeyPair.getPrivate(), cert, chain); <ide> return Future.<Void>succeededFuture(); <ide> } <ide> <ide> public Future<Void> start() { <del> if (state != State.NOT_STARTED) { <del> throw new IllegalStateException("Already started"); <del> } <del> synchronized (AcmeManager.this) { <del> state = State.UPDATING; <del> } <del> String file = activeConfigPath(); <del> return doUpdate(future((Future<Boolean> fut) -> vertx.fileSystem().exists(file, fut)) <del> .recover(describeFailure("Error checking previous config " + file)) <del> .compose(exists -> <del> exists ? readConf(file) : future((Future<AcmeConfig> fut) -> { <del> AcmeConfig emptyConf = new AcmeConfig(); <del> emptyConf.accounts = emptyMap(); <del> fut.complete(emptyConf); <del> }))); <add> return initDb().compose(v -> { <add> if (state != State.NOT_STARTED) { <add> throw new IllegalStateException("Already started"); <add> } <add> synchronized (AcmeManager.this) { <add> state = State.UPDATING; <add> } <add> String file = activeConfigPath(); <add> return doUpdate(future((Future<Boolean> fut) -> vertx.fileSystem().exists(file, fut)) <add> .recover(describeFailure("Error checking previous config " + file)) <add> .compose(exists -> <add> exists ? readConf(file) : future((Future<AcmeConfig> fut) -> { <add> AcmeConfig emptyConf = new AcmeConfig(); <add> emptyConf.accounts = emptyMap(); <add> fut.complete(emptyConf); <add> }))); <add> }); <ide> } <ide> <ide> <ide> public Future<Void> start(AcmeConfig conf) { <del> return configure(State.NOT_STARTED, conf); <add> return initDb().compose(v -> configure(State.NOT_STARTED, conf)); <ide> } <ide> <ide> public Future<Void> reconfigure(AcmeConfig conf) { <ide> }); <ide> } <ide> <add> private Future<Void> initDb() { <add> return future((Future<Void> fut) -> vertx.fileSystem().mkdirs(dbPath, fut)) <add> .recover(describeFailure("DB directory create")); <add> } <add> <ide> private Future<AcmeConfig> readConf(final String file) { <ide> return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(file, fut)) <ide> .recover(describeFailure("Error loading previous config " + file)) <ide> } catch (JsonProcessingException e) { <ide> fut.fail(e); <ide> } <del> })).compose(buf -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(file, buf, fut))); <add> })).compose(buf -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(file, buf, fut)) <add> .recover(describeFailure("Active config file write"))); <ide> } <ide> <ide> private static <K, V> List<MapDiff<K,V>> mapDiff(final Map<K, V> old, final Map<K, V> nev) { <ide> } <ide> <ide> Future<KeyPair> getOrCreateKeyPair(String type, final String keyPairFile, final Supplier<Future<KeyPair>> creator) { <del> return future((Future<Boolean> fut) -> vertx.fileSystem().exists(keyPairFile, fut)).compose(keyFileExists -> { <add> return future((Future<Boolean> fut) -> vertx.fileSystem().exists(keyPairFile, fut)) <add> .recover(describeFailure("Keypair for " + type + " file check")).compose(keyFileExists -> { <ide> if (keyFileExists) { <ide> // file exists <ide> return future((Future<Buffer> fut) -> vertx.fileSystem().readFile(keyPairFile, fut)) <add> .recover(describeFailure("Keypair for " + type + " file read")) <ide> .compose(existingKeyFile -> AsyncKeyPairUtils.readKeyPair(vertx, existingKeyFile)) <ide> .map((KeyPair readKeyPair) -> { <ide> logger.info("Existing " + type + " keypair read from " + keyPairFile); <ide> } else { <ide> // file doesn't exist <ide> return creator.get().compose(createdKeyPair -> AsyncKeyPairUtils.writeKeyPair(vertx, createdKeyPair) <del> .compose(keyPairSerialized -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(keyPairFile, keyPairSerialized, fut))) <add> .compose(keyPairSerialized -> future((Future<Void> fut) -> vertx.fileSystem().writeFile(keyPairFile, keyPairSerialized, fut)) <add> .recover(describeFailure("Keypar for " + type + " file write"))) <ide> .map(v -> { <ide> logger.info("New " + type + " keypair written to " + keyPairFile); <ide> return createdKeyPair;
JavaScript
mit
d548b04bfccd71827ee9f61240a6bef5c4603448
0
dsauerbrun/climbcation-front,dsauerbrun/climbcation-front
var home = angular.module('app', ['ngToast','ngSanitize','trackScroll','infinite-scroll','ui.bootstrap','helperService','filter-directives','location-list-item-directives','section-form-directive','ngRoute','facebookComments','ezfb','ui.bootstrap','duScroll','customFilters']); home.config( function($routeProvider, $locationProvider) { $routeProvider .when('/', { redirectTo: function(current, path, search) { if (search.goto) { // if we were passed in a search param, and it has a path // to redirect to, then redirect to that path return "/" + search.goto } else { // else just redirect back to this location // angular is smart enough to only do this once. return "/home" } } }) .when('/home', { templateUrl: 'views/home/home.tpl.html', }) .when('/new-location', { templateUrl: 'views/new_location/submitpage.tpl.html', }) .when('/location/:slug', { templateUrl: 'views/location/location.tpl.html', controller: 'LocationPageController', }) .otherwise({ redirectTo: '/home' }); $locationProvider.html5Mode(true); }); home.config(function(ezfbProvider){ ezfbProvider.setInitParams({ appId: '604556333018328', version: 'v2.5' }) }) home.filter('removeSpaces', function () { return function (text) { var str = text.replace(/\s+/g, ''); return str; }; }); home.controller('LocationPageController',function(ngToast,$scope,$rootScope,$q,helperService,$http,$routeParams,$location,$anchorScroll,$timeout, LocationsGetter){ slug = $routeParams.slug; var editMessage = 'Your edit has been submitted and will be approved by a moderator shortly!'; $scope.name = 'hello'; $scope.gmap; $scope.originAirport = 'Denver International Airport'; $scope.originAirportCode = 'DEN'; $scope.nearbyShow = false; $scope.editingAccommodation = false; $scope.editingGettingIn = false; $scope.editingFoodOptions = false; $scope.helperService = helperService; $scope.getAirport = function(item, model, label, event) { $scope.originAirportCode = item.iata; $scope.originAirport = item.name; LocationsGetter.getFlightQuotes([$scope.locationData.slug], $scope.originAirportCode).then(function(promiseQuotes) { $timeout(function(){ setLocationHighchart(promiseQuotes,$scope.originAirportCode); }); }); } $scope.toggleEditAccommodation = function() { $scope.editingAccommodation = !$scope.editingAccommodation; } $scope.toggleEditGettingIn = function() { $scope.editingGettingIn = !$scope.editingGettingIn; } $scope.toggleEditFoodOptions = function() { $scope.editingFoodOptions = !$scope.editingFoodOptions; } var emptySectionTemplate = {previewOff: false, newSection: true, title:'', body: '', subsections: [{title:'', subsectionDescriptions:[{desc:''}]}]} emptySectionTemplate.clone = function(){ return jQuery.extend(true, {}, this); }; $scope.emptySection = {previewOff: false, newSection: true, title:'', body: '', subsections: [{title:'', subsectionDescriptions:[{desc:''}]}]} $scope.scrollTo = function(id){ $('html,body').animate({ scrollTop: $('#'+id.replace(/\s+/g, '')).offset().top }, 1000); }; $http.get('api/location/'+slug).then( function(success){ if (success.status == 200) { success = success.data; $scope.longitude = success['location']['longitude']; $scope.latitude = success['location']['latitude']; $scope.sections = success['sections']; $scope.tableOfContents = processTableContents($scope.sections); $scope.locationData = success['location'] $scope.nearby = success['nearby']; $scope.gmap = createMap('map-canvas',$scope.latitude,$scope.longitude,4); addCloseLocations($scope.gmap,success['nearby']); addMarker($scope.gmap,$scope.latitude,$scope.longitude,success['location']['title'],'<p>'+success['location']['title']+'</p>',false); populateEditables($scope.locationData); LocationsGetter.getFlightQuotes([$scope.locationData.slug], $scope.originAirportCode).then(function(promiseQuotes) { $timeout(function(){ setLocationHighchart(promiseQuotes,$scope.originAirportCode); }); }); } } ); $scope.toggleNearby = function() { $scope.nearbyShow = !$scope.nearbyShow; } // EDITING FUNCTIONALITY BELOW $scope.locationObj = { submitter_email: '', name: '', country: '', continent: '', airport: '', price_floor: '', price_ceiling: '', months: {}, accommodations: {}, climbingTypes: {}, grade: '', sections: [], closestAccommodation: '<1 mile', foodOptions: {}, transportations: {}, foodOptionDetails: {} }; $scope.submitAccommodationChanges = function() { if (!$scope.saving) { $('.submit-button').addClass('disabled'); $scope.saving = true; $http.post('api/locations/' + $scope.locationData.id +'/accommodations', {location: $scope.locationObj} ).then(function(response) { if (response.status == 200) { $http.get('api/location/'+slug).then(function(response) { $scope.locationData.accommodations = response.data.location.accommodations; $scope.locationData.accommodation_notes = response.data.location.accommodation_notes; $scope.locationData.closest_accommodation = response.data.location.closest_accommodation; $scope.toggleEditAccommodation(); ngToast.create({ additionalClasses: 'climbcation-toast', content: editMessage }); }); } $scope.saving = false; $('.submit-button').removeClass('disabled'); }); } } $scope.selectAccommodation = function(accommodation) { var accommodationExists = $scope.locationObj.accommodations[accommodation.id]; if (accommodationExists) { //remove it from list of accommodations $scope.locationObj.accommodations[accommodationExists.id] = null; } else { //mark the id and create a cost range field $scope.locationObj.accommodations[accommodation.id] = {id: accommodation.id, cost: ''}; } }; $scope.submitGettingInChanges = function() { if (!$scope.saving) { $('.submit-button').addClass('disabled'); $scope.saving = true; $http.post('api/locations/' + $scope.locationData.id +'/gettingin', {location: $scope.locationObj} ).then(function(response) { if (response.status == 200) { $http.get('api/location/'+slug).then(function(response) { $scope.locationData.transportations = response.data.location.transportations; $scope.locationData.getting_in_notes = response.data.location.getting_in_notes; $scope.locationData.best_transportation = response.data.location.best_transportation; $scope.locationData.walking_distance = response.data.location.walking_distance; $scope.toggleEditGettingIn(); ngToast.create({ additionalClasses: 'climbcation-toast', content: editMessage }); }); } $('.submit-button').removeClass('disabled'); $scope.saving = false; }); } } $scope.selectBestTransportation = function(id) { // set the best transportation $scope.locationObj.bestTransportationId = id; $scope.locationObj.bestTransportationCost = null; //set ranges var bestTransportation = _.find($scope.transportations, function(transportation) { return transportation.id == id; }) $scope.bestTransportationName = bestTransportation.name; $scope.bestTransportationCostOptions = []; _.forEach(bestTransportation.ranges, function(range) { var rangeObj = { cost: range, active: false } $scope.bestTransportationCostOptions.push(rangeObj); }); } $scope.selectBestTransportationCost = function(cost) { // reset active _.forEach($scope.bestTransportationCostOptions, function(costOption) { costOption.active = false; if ( costOption.cost == cost || costOption.cost == cost.cost) { costOption.active = true; $scope.locationObj.bestTransportationCost = cost.cost || cost; } }); } $scope.submitFoodOptionsChanges = function() { if (!$scope.saving) { $('.submit-button').addClass('disabled'); $scope.saving = true; $http.post('api/locations/' + $scope.locationData.id +'/foodoptions', {location: $scope.locationObj} ).then(function(response) { if (response.status == 200) { $http.get('api/location/'+slug).then(function(response) { $scope.locationData.food_options = response.data.location.food_options; $scope.locationData.common_expenses_notes = response.data.location.common_expenses_notes; $scope.locationData.saving_money_tip = response.data.location.saving_money_tip; $scope.toggleEditFoodOptions(); ngToast.create({ additionalClasses: 'climbcation-toast', content: editMessage }); }); } $('.submit-button').removeClass('disabled'); $scope.saving = false; }); } } $scope.selectFoodOptionDetail = function(id, range) { $scope.locationObj.foodOptionDetails[id] = {}; $scope.locationObj.foodOptionDetails[id].id = id; $scope.locationObj.foodOptionDetails[id].cost = range; } $scope.cleanFoodOptionDetails = function() { _.forEach($scope.locationObj.foodOptions, function(foodOption, key) { if (!foodOption) { $scope.locationObj.foodOptionDetails[key] = null; } else if (!$scope.locationObj.foodOptionDetails[key]) { $scope.locationObj.foodOptionDetails[key] = {}; $scope.locationObj.foodOptionDetails[key].id = key; $scope.locationObj.foodOptionDetails[key].cost = null; } }); } $scope.addSection = function() { $scope.sections.new = {title: '', body: '', previewOff: true}; } function populateEditables(location) { $http.get('api/get_attribute_options').then(function(data){ var respData = data.data $scope.accommodations = respData['accommodations']; $scope.climbingTypes = respData['climbing_types']; $scope.months = respData['months']; $scope.grades = respData['grades']; $scope.foodOptions = respData['food_options']; $scope.transportations = respData['transportations']; }).then(function() { _.forEach(location.accommodations, function(accommodation) { $scope.locationObj.accommodations[accommodation.id] = { id: accommodation.id, cost: accommodation.cost}; }) $scope.locationObj.accommodationNotes = location.accommodation_notes; $scope.locationObj.closestAccommodation = location.closest_accommodation; _.forEach(location.transportations, function(transportation) { $scope.locationObj.transportations[transportation.id] = true; }); location.best_transportation.id && $scope.selectBestTransportation(location.best_transportation.id); location.best_transportation.cost && $scope.selectBestTransportationCost(location.best_transportation.cost) $scope.locationObj.gettingInNotes = location.getting_in_notes; $scope.locationObj.walkingDistance = location.walking_distance; _.forEach(location.food_options, function(foodOption) { $scope.locationObj.foodOptions[foodOption.id] = true; foodOption.cost && $scope.selectFoodOptionDetail(foodOption.id, foodOption.cost); }); $scope.locationObj.commonExpensesNotes = location.common_expenses_notes $scope.locationObj.savingMoneyTips = location.saving_money_tip; }) } $scope.stopPropagation = function($event) { $event.stopPropagation(); }; }); home.controller('LocationsController',function($scope, $timeout,LocationsGetter, $location, $document, $http, helperService){ var locations = this; $scope.locationData = []; $scope.LocationsGetter = LocationsGetter; $scope.originAirport = "Denver International Airport"; $scope.originAirportCode = "DEN"; $scope.slugArray = []; $scope.helperService = helperService; LocationsGetter.locations = LocationsGetter.locations || []; // if we are returning to the front page we want to reset the locations and clear the filters if(LocationsGetter.locations.length > 0) { LocationsGetter.locations = []; LocationsGetter.clearFilters(); LocationsGetter.setFilterTimer(0); } $scope.getAirportPrices = function(item, model, label, event) { $scope.originAirportCode = item.iata; LocationsGetter.getFlightQuotes($scope.slugArray, item.iata); } $scope.$watch('LocationsGetter.flightQuotes', function(){ //set the lowest price and date for location _.forEach(LocationsGetter.flightQuotes, function(quote, key) { var splitKey = key.split('-'); var locationId = splitKey[splitKey.length - 1]; var location = _.find($scope.locationData, function(locationIter) { return locationIter.location.id == locationId; }); var lowestPrice = 9999999; var lowestPriceDate = ''; _.forEach(quote, function(monthArray, month) { _.forEach(monthArray, function(cost, day) { if (lowestPrice > cost) { lowestPrice = cost; lowestPriceDate = month + '/' + day; } }); }); location.lowestPrice = {}; location.lowestPrice.date = lowestPriceDate; location.lowestPrice.cost = lowestPrice; }); $timeout(function(){ setHighcharts(LocationsGetter.flightQuotes,$scope.originAirportCode); }); }); $scope.$watch('LocationsGetter.locations.length', function() { $scope.locationData = LocationsGetter.locations; $scope.slugArray = []; $.each($scope.locationData, function(key, promiseLocation){ $scope.slugArray.push(this['slug']); }); LocationsGetter.getFlightQuotes($scope.slugArray, $scope.originAirportCode); }) $scope.goToFilter = function() { var filter = angular.element(document.getElementById('filter')); $document.scrollToElement(filter, 0, 500); } }); home.controller('MapFilterController',function($rootScope,$scope,LocationsGetter, $timeout, $window){ var filterId; if ($window.innerWidth < 768) { filterId = 'mapFilterMobile'; } else { filterId = 'mapFilter'; } $scope.mapFilterEnabled = true; $rootScope.filterMap = createMap(filterId,70,-160,2); LocationsGetter.markerMap = {}; $rootScope.filterMap.addListener('dragend', function() { LocationsGetter.mapFilter['northeast']['longitude'] = $rootScope.filterMap.getBounds().getNorthEast().lng(); LocationsGetter.mapFilter['northeast']['latitude'] = $rootScope.filterMap.getBounds().getNorthEast().lat(); LocationsGetter.mapFilter['southwest']['longitude'] = $rootScope.filterMap.getBounds().getSouthWest().lng(); LocationsGetter.mapFilter['southwest']['latitude'] = $rootScope.filterMap.getBounds().getSouthWest().lat(); $scope.mapFilterEnabled && LocationsGetter.setFilterTimer(1.5); }); $rootScope.filterMap.addListener('zoom_changed', function() { if (!firstMapLoad) { LocationsGetter.mapFilter['northeast']['longitude'] = $rootScope.filterMap.getBounds().getNorthEast().lng(); LocationsGetter.mapFilter['northeast']['latitude'] = $rootScope.filterMap.getBounds().getNorthEast().lat(); LocationsGetter.mapFilter['southwest']['longitude'] = $rootScope.filterMap.getBounds().getSouthWest().lng(); LocationsGetter.mapFilter['southwest']['latitude'] = $rootScope.filterMap.getBounds().getSouthWest().lat(); $scope.mapFilterEnabled && LocationsGetter.setFilterTimer(1.5); } else { firstMapLoad = false; } }); function notDefaultBounds(bounds) { if (bounds.H.H <= -80 && bounds.H.j >= 80 && bounds.j.H >= 180 && bounds.j.j <= -180) { return false } else { return true; } } var firstMapLoad = true; $scope.$watch('LocationsGetter.unpaginatedLocations.length', function(){ if (LocationsGetter.unpaginatedLocations.length != 0) { $rootScope.filterMap.removeMarkers(); LocationsGetter.markerMap = {}; //redo map points $.each(LocationsGetter.unpaginatedLocations,function(){ LocationsGetter.markerMap[this['slug']] = addMarker($rootScope.filterMap, this['latitude'], this['longitude'], this['name'], '<p><a href="/location/'+this['slug']+'">'+this['name']+'</a></p>',true); LocationsGetter.markerMap[this['slug']].setOptions({opacity: .5}) }); // we set firstMapLoad to false when the zoom_changed watch catches the fitBounds call if (firstMapLoad && filterId == 'mapFilter') { var allowedBounds = new google.maps.LatLngBounds( new google.maps.LatLng(85, -180), // top left corner of map new google.maps.LatLng(-85, 180) // bottom right corner ); var k = 5; var n = allowedBounds.getNorthEast().lat() - k; var e = allowedBounds.getNorthEast().lng() - k; var s = allowedBounds.getSouthWest().lat() + k; var w = allowedBounds.getSouthWest().lng() + k; var neNew = new google.maps.LatLng( n, e ); var swNew = new google.maps.LatLng( s, w ); boundsNew = new google.maps.LatLngBounds(); boundsNew.extend(neNew); boundsNew.extend(swNew); $rootScope.filterMap.fitBounds(allowedBounds); } } }); }); home.factory("LocationsGetter",function($q,$http, $timeout){ var LocationsGetter = {}; LocationsGetter.flightQuotes = null; var filter = {}; LocationsGetter.locations = []; LocationsGetter.unpaginatedLocations = []; LocationsGetter.pageNum = 1; LocationsGetter.filterTimer = null; LocationsGetter.mapFilter = {}; LocationsGetter.markerMap = {}; LocationsGetter.filter = filter; LocationsGetter.scrollLock = false; filter['climbing_types'] = []; filter['accommodations'] = []; filter['continents'] = []; filter['price_max'] = []; filter['sort'] = []; filter['search'] = ''; filter['start_month'] = 1; filter['end_month'] = 12; LocationsGetter.mapFilter['northeast'] = {}; LocationsGetter.mapFilter['northeast']['longitude'] = null; LocationsGetter.mapFilter['northeast']['latitude'] = null; LocationsGetter.mapFilter['southwest'] = {}; LocationsGetter.mapFilter['southwest']['longitude'] = null; LocationsGetter.mapFilter['southwest']['latitude'] = null; LocationsGetter.loading = false; var sort = {}; sort['price'] = []; sort['grade'] = []; LocationsGetter.setFilterTimer = function(seconds) { LocationsGetter.cancelFilterTimer(); LocationsGetter.filterTimer = $timeout(function() { LocationsGetter.pageNum = 1; LocationsGetter.locations = []; LocationsGetter.getNextPage(); }, seconds*1000); } LocationsGetter.cancelFilterTimer = function() { LocationsGetter.filterTimer && $timeout.cancel(LocationsGetter.filterTimer); } LocationsGetter.clearFilters = function() { this.mapFilter = {}; this.markerMap = {}; this.pageNum = 1; filter['climbing_types'] = []; filter['accommodations'] = []; filter['continents'] = []; filter['price_max'] = []; filter['sort'] = []; filter['search'] = ''; filter['start_month'] = 1; filter['end_month'] = 12; this.mapFilter['northeast'] = {}; this.mapFilter['northeast']['longitude'] = null; this.mapFilter['northeast']['latitude'] = null; this.mapFilter['southwest'] = {}; this.mapFilter['southwest']['longitude'] = null; this.mapFilter['southwest']['latitude'] = null; this.loading = false; sort['price'] = []; sort['grade'] = []; }; LocationsGetter.toggleFilterButton = function(eventItem,filterArray,filterValue){ toggleButtonActive(angular.element(eventItem.currentTarget)); angular.element(eventItem.currentTarget).blur(); if(filterValue != 'sort' && $.inArray(filterValue,filter[filterArray]) != -1){ //remove item from filter filter[filterArray].splice($.inArray(filterValue,filter[filterArray]), 1); } else if( filterValue == 'All'){ filter[filterArray] = []; resetButtonsGroup(angular.element(eventItem.currentTarget).parent()); } else{ filter[filterArray].push(filterValue); inactivateGroupAll(angular.element(eventItem.currentTarget).parent()); //only one sorter can be active at a time so we have special cases for it if(filterArray == 'sort'){ resetButtonsGroup(angular.element(eventItem.currentTarget).parent()); toggleButtonActive(angular.element(eventItem.currentTarget)); inactivateGroupAll(angular.element(eventItem.currentTarget).parent()); } } LocationsGetter.setFilterTimer(1); }; LocationsGetter.filterByMonth = function(startMonth, endMonth) { filter['start_month'] = startMonth; filter['end_month'] = endMonth; LocationsGetter.setFilterTimer(1.5); } LocationsGetter.filterByQuery = function(eventItem){ filter['search'] = eventItem; LocationsGetter.setFilterTimer(0); } LocationsGetter.getFlightQuotes = function(slugs,originAirportCode){ return $http.post('/api/collect_locations_quotes', {slugs: slugs, origin_airport: originAirportCode}).then(function(response){ LocationsGetter.flightQuotes = response.data; return response.data; }); }; LocationsGetter.getNextPage = function() { LocationsGetter.scrollLock = true; return LocationsGetter.getLocations().then(function(locations) { LocationsGetter.pageNum++; LocationsGetter.scrollLock = false; return locations; }); }; LocationsGetter.setSorting = function(sortBy, asc) { if (sortBy == 'distance') { navigator.geolocation.getCurrentPosition( function(position) { LocationsGetter.myLat = position.coords.latitude; LocationsGetter.myLong = position.coords.longitude; filter.sort ={distance: {latitude: LocationsGetter.myLat, longitude: LocationsGetter.myLong}}; LocationsGetter.setFilterTimer(0); }, function() { console.error('error getting location(probably blocked)'); alert('Need location permission to sort by distance, ' + 'if you arent given the option to grant permission, ' + 'it is probably because your browser doesnt support non-ssl geolocation requests... the webmaster is a cheap bastard' + 'and doesnt want to spend $20/mo, go to https://climbcation.herokuapp.com and it should work just fine'); } ); } else { filter.sort = {}; filter.sort[sortBy] = {asc: asc}; LocationsGetter.setFilterTimer(0); } } LocationsGetter.getLocations = function(){ LocationsGetter.loading = true; return $http.post('/api/filter_locations', {filter: filter, mapFilter: LocationsGetter.mapFilter, page: LocationsGetter.pageNum}).then(function(response){ LocationsGetter.loading = false; if (response.data.unpaginated.length != LocationsGetter.unpaginatedLocations.length && response.data.unpaginated.length != 0) { LocationsGetter.unpaginatedLocations = response.data.unpaginated; } var promiseLocations = response.data.paginated; LocationsGetter.locations || (LocationsGetter.locations = []); $.each(promiseLocations, function(key, promiseLocation){ var exists = _.find(LocationsGetter.locations, function(locationIter) { return locationIter.id == promiseLocation.id; }); !exists && LocationsGetter.locations.push(promiseLocation); }); if (_.size(promiseLocations) == 0) { LocationsGetter.scrollEnded = true; } else { LocationsGetter.scrollEnded = false; } return response.data; }); }; return LocationsGetter; }); function toggleButtonActive(clickedButton){ if(clickedButton.hasClass('active')){ clickedButton.removeClass('active'); } else{ clickedButton.addClass('active'); } } function resetButtonsGroup(buttonGroup){ buttonGroup.children('button').each(function(){ $(this).removeClass('active'); if($(this).hasClass('all')){ $(this).addClass('active'); } }); } function inactivateGroupAll(buttonGroup){ buttonGroup.children('button').each(function(){ if($(this).hasClass('all')){ $(this).removeClass('active'); } }); } function createMap(mapId,latitude,longitude,zoom){ var map =new GMaps({ div: '#'+mapId, lat: latitude, lng: longitude, zoom: zoom, scrollwheel: false }); $('body').on('click', function(element) { map.setOptions({scrollwheel:false}); }); $('#'+mapId).on('click', function (e) { e.stopPropagation(); map.setOptions({scrollwheel:true}); return; }); return map; } function addCloseLocations(map,locationMap){ $.each(locationMap,function(){ addMarker(map,this['lat'],this['lng'],this['name'],'<p><a href="/location/'+this['slug']+'">'+this['name']+'</a></p>',true); }); } function addMarker(map,lat,lng,title,infowindow,isSecondary){ return map.addMarker({ lat: lat, lng: lng, title: title, icon: isSecondary?'':'https://s3-us-west-2.amazonaws.com/climbcation-front/assets/primary.png', infoWindow:{ content: infowindow } }); } function processTableContents(sectionMap){ var titleArray = []; var counter = 0; $.each(sectionMap,function(){ index = parseInt(counter/3) if(!(index in titleArray)){ titleArray[index] = []; } titleArray[index].push(this['title']); counter++; }); return titleArray; } function processSectionsByPair(sectionMap){ pairMap = {}; var counter = 0; var sectCounter = 0; $.each(sectionMap, function(){ counter = 0; if(this['data'] != null){ pairMap = {}; $.each(this['data'],function(key,value){ pairIndex = parseInt(counter/2); if(counter % 2 == 0){ pairMap[pairIndex] = {} } //pairMap[pairIndex][counter%2] = value; pairMap[pairIndex][key] = value; counter++; }); this['data'] = pairMap; } sectCounter++; }); } function setHighcharts(locationQuoteData, origin_airport){ $.each(locationQuoteData,function(slug,months){ destinationAirport = slug.split("-")[0] quote_array = []; var maxPrice = 0; $.each(this,function(monthKey,value){ if (monthKey != 'referral') { $.each(value, function(dayKey,cost){ quote_array.push([monthKey+'/'+dayKey,cost]) if(cost > maxPrice) { maxPrice = cost; } }); } }); $('#highchart'+slug).highcharts({ chart: { type: 'line', height: '100' }, title: { useHTML: true, text: 'One Way cost from '+origin_airport+' to '+destinationAirport + '<a href="' + this.referral + '" target="_blank"><img src="/images/skyscannerinline.png"></a>', floating: false }, xAxis: { visible: false, type: 'category', title: { text: 'Date' }, labels: { rotation: -45, style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }, yAxis: { visible: false, min: 0, title: { text: 'Price(USD)' }, tickInterval: 50, max: maxPrice }, legend: { enabled: false }, tooltip: { pointFormat: 'Price: <b>${point.y:.1f} </b>' }, series: [{ name: 'Price', data: quote_array, dataLabels: { enabled: false, rotation: -90, color: '#FFFFFF', align: 'right', format: '{point.y:.1f}', // one decimal y: 10, // 10 pixels down from the top style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }] }); }); $('text:contains("Highcharts.com")').hide(); } function setLocationHighchart(locationQuoteData, origin_airport){ $.each(locationQuoteData,function(slug, months){ destinationAirport = slug.split("-")[0] quote_array = []; var maxPrice = 0; $.each(this,function(monthKey,value){ if (monthKey != 'referral') { $.each(value, function(dayKey,cost){ quote_array.push([monthKey+'/'+dayKey,cost]) if(cost > maxPrice) { maxPrice = cost; } }); } }); $('#highchart'+slug).highcharts({ chart: { type: 'line', height: '200' }, title: { useHTML: true, text: 'One Way cost from '+origin_airport+' to '+destinationAirport + '<a href="' + this.referral + '" target="_blank"><img src="/images/skyscannerinline.png"></a>', floating: false }, xAxis: { visible: true, type: 'category', title: { text: 'Date' }, labels: { rotation: -45, style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }, yAxis: { visible: true, min: 0, title: { text: 'Price(USD)' }, tickInterval: 50, max: maxPrice }, legend: { enabled: false }, tooltip: { pointFormat: 'Price: <b>${point.y:.1f} </b>' }, series: [{ name: 'Price', data: quote_array, dataLabels: { enabled: false, rotation: -90, color: '#FFFFFF', align: 'right', format: '{point.y:.1f}', // one decimal y: 10, // 10 pixels down from the top style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }] }); }); }
app/js/app.js
var home = angular.module('app', ['ngToast','ngSanitize','trackScroll','infinite-scroll','ui.bootstrap','helperService','filter-directives','location-list-item-directives','section-form-directive','ngRoute','facebookComments','ezfb','ui.bootstrap','duScroll','customFilters']); home.config( function($routeProvider, $locationProvider) { $routeProvider .when('/', { redirectTo: function(current, path, search) { if (search.goto) { // if we were passed in a search param, and it has a path // to redirect to, then redirect to that path return "/" + search.goto } else { // else just redirect back to this location // angular is smart enough to only do this once. return "/home" } } }) .when('/home', { templateUrl: 'views/home/home.tpl.html', }) .when('/new-location', { templateUrl: 'views/new_location/submitpage.tpl.html', }) .when('/location/:slug', { templateUrl: 'views/location/location.tpl.html', controller: 'LocationPageController', }) .otherwise({ redirectTo: '/home' }); $locationProvider.html5Mode(true); }); home.config(function(ezfbProvider){ ezfbProvider.setInitParams({ appId: '604556333018328', version: 'v2.5' }) }) home.filter('removeSpaces', function () { return function (text) { var str = text.replace(/\s+/g, ''); return str; }; }); home.controller('LocationPageController',function(ngToast,$scope,$rootScope,$q,helperService,$http,$routeParams,$location,$anchorScroll,$timeout, LocationsGetter){ slug = $routeParams.slug; var editMessage = 'Your edit has been submitted and will be approved by a moderator shortly!'; $scope.name = 'hello'; $scope.gmap; $scope.originAirport = 'Denver International Airport'; $scope.originAirportCode = 'DEN'; $scope.nearbyShow = false; $scope.editingAccommodation = false; $scope.editingGettingIn = false; $scope.editingFoodOptions = false; $scope.helperService = helperService; $scope.getAirport = function(item, model, label, event) { $scope.originAirportCode = item.iata; $scope.originAirport = item.name; LocationsGetter.getFlightQuotes([$scope.locationData.slug], $scope.originAirportCode).then(function(promiseQuotes) { $timeout(function(){ setLocationHighchart(promiseQuotes,$scope.originAirportCode); }); }); } $scope.toggleEditAccommodation = function() { $scope.editingAccommodation = !$scope.editingAccommodation; } $scope.toggleEditGettingIn = function() { $scope.editingGettingIn = !$scope.editingGettingIn; } $scope.toggleEditFoodOptions = function() { $scope.editingFoodOptions = !$scope.editingFoodOptions; } var emptySectionTemplate = {previewOff: false, newSection: true, title:'', body: '', subsections: [{title:'', subsectionDescriptions:[{desc:''}]}]} emptySectionTemplate.clone = function(){ return jQuery.extend(true, {}, this); }; $scope.emptySection = {previewOff: false, newSection: true, title:'', body: '', subsections: [{title:'', subsectionDescriptions:[{desc:''}]}]} $scope.scrollTo = function(id){ $('html,body').animate({ scrollTop: $('#'+id.replace(/\s+/g, '')).offset().top }, 1000); }; $http.get('api/location/'+slug).then( function(success){ if (success.status == 200) { success = success.data; $scope.longitude = success['location']['longitude']; $scope.latitude = success['location']['latitude']; $scope.sections = success['sections']; $scope.tableOfContents = processTableContents($scope.sections); $scope.locationData = success['location'] $scope.nearby = success['nearby']; $scope.gmap = createMap('map-canvas',$scope.latitude,$scope.longitude,4); addCloseLocations($scope.gmap,success['nearby']); addMarker($scope.gmap,$scope.latitude,$scope.longitude,success['location']['title'],'<p>'+success['location']['title']+'</p>',false); populateEditables($scope.locationData); LocationsGetter.getFlightQuotes([$scope.locationData.slug], $scope.originAirportCode).then(function(promiseQuotes) { $timeout(function(){ setLocationHighchart(promiseQuotes,$scope.originAirportCode); }); }); } } ); $scope.toggleNearby = function() { $scope.nearbyShow = !$scope.nearbyShow; } // EDITING FUNCTIONALITY BELOW $scope.locationObj = { submitter_email: '', name: '', country: '', continent: '', airport: '', price_floor: '', price_ceiling: '', months: {}, accommodations: {}, climbingTypes: {}, grade: '', sections: [], closestAccommodation: '<1 mile', foodOptions: {}, transportations: {}, foodOptionDetails: {} }; $scope.submitAccommodationChanges = function() { if (!$scope.saving) { $('.submit-button').addClass('disabled'); $scope.saving = true; $http.post('api/locations/' + $scope.locationData.id +'/accommodations', {location: $scope.locationObj} ).then(function(response) { if (response.status == 200) { $http.get('api/location/'+slug).then(function(response) { $scope.locationData.accommodations = response.data.location.accommodations; $scope.locationData.accommodation_notes = response.data.location.accommodation_notes; $scope.locationData.closest_accommodation = response.data.location.closest_accommodation; $scope.toggleEditAccommodation(); ngToast.create({ additionalClasses: 'climbcation-toast', content: editMessage }); }); } $scope.saving = false; $('.submit-button').removeClass('disabled'); }); } } $scope.selectAccommodation = function(accommodation) { var accommodationExists = $scope.locationObj.accommodations[accommodation.id]; if (accommodationExists) { //remove it from list of accommodations $scope.locationObj.accommodations[accommodationExists.id] = null; } else { //mark the id and create a cost range field $scope.locationObj.accommodations[accommodation.id] = {id: accommodation.id, cost: ''}; } }; $scope.submitGettingInChanges = function() { if (!$scope.saving) { $('.submit-button').addClass('disabled'); $scope.saving = true; $http.post('api/locations/' + $scope.locationData.id +'/gettingin', {location: $scope.locationObj} ).then(function(response) { if (response.status == 200) { $http.get('api/location/'+slug).then(function(response) { $scope.locationData.transportations = response.data.location.transportations; $scope.locationData.getting_in_notes = response.data.location.getting_in_notes; $scope.locationData.best_transportation = response.data.location.best_transportation; $scope.locationData.walking_distance = response.data.location.walking_distance; $scope.toggleEditGettingIn(); ngToast.create({ additionalClasses: 'climbcation-toast', content: editMessage }); }); } $('.submit-button').removeClass('disabled'); $scope.saving = false; }); } } $scope.selectBestTransportation = function(id) { // set the best transportation $scope.locationObj.bestTransportationId = id; $scope.locationObj.bestTransportationCost = null; //set ranges var bestTransportation = _.find($scope.transportations, function(transportation) { return transportation.id == id; }) $scope.bestTransportationName = bestTransportation.name; $scope.bestTransportationCostOptions = []; _.forEach(bestTransportation.ranges, function(range) { var rangeObj = { cost: range, active: false } $scope.bestTransportationCostOptions.push(rangeObj); }); } $scope.selectBestTransportationCost = function(cost) { // reset active _.forEach($scope.bestTransportationCostOptions, function(costOption) { costOption.active = false; if ( costOption.cost == cost || costOption.cost == cost.cost) { costOption.active = true; $scope.locationObj.bestTransportationCost = cost.cost || cost; } }); } $scope.submitFoodOptionsChanges = function() { if (!$scope.saving) { $('.submit-button').addClass('disabled'); $scope.saving = true; $http.post('api/locations/' + $scope.locationData.id +'/foodoptions', {location: $scope.locationObj} ).then(function(response) { if (response.status == 200) { $http.get('api/location/'+slug).then(function(response) { $scope.locationData.food_options = response.data.location.food_options; $scope.locationData.common_expenses_notes = response.data.location.common_expenses_notes; $scope.locationData.saving_money_tip = response.data.location.saving_money_tip; $scope.toggleEditFoodOptions(); ngToast.create({ additionalClasses: 'climbcation-toast', content: editMessage }); }); } $('.submit-button').removeClass('disabled'); $scope.saving = false; }); } } $scope.selectFoodOptionDetail = function(id, range) { $scope.locationObj.foodOptionDetails[id] = {}; $scope.locationObj.foodOptionDetails[id].id = id; $scope.locationObj.foodOptionDetails[id].cost = range; } $scope.cleanFoodOptionDetails = function() { _.forEach($scope.locationObj.foodOptions, function(foodOption, key) { if (!foodOption) { $scope.locationObj.foodOptionDetails[key] = null; } else if (!$scope.locationObj.foodOptionDetails[key]) { $scope.locationObj.foodOptionDetails[key] = {}; $scope.locationObj.foodOptionDetails[key].id = key; $scope.locationObj.foodOptionDetails[key].cost = null; } }); } $scope.addSection = function() { $scope.sections.new = {title: '', body: '', previewOff: true}; } function populateEditables(location) { $http.get('api/get_attribute_options').then(function(data){ var respData = data.data $scope.accommodations = respData['accommodations']; $scope.climbingTypes = respData['climbing_types']; $scope.months = respData['months']; $scope.grades = respData['grades']; $scope.foodOptions = respData['food_options']; $scope.transportations = respData['transportations']; }).then(function() { _.forEach(location.accommodations, function(accommodation) { $scope.locationObj.accommodations[accommodation.id] = { id: accommodation.id, cost: accommodation.cost}; }) $scope.locationObj.accommodationNotes = location.accommodation_notes; $scope.locationObj.closestAccommodation = location.closest_accommodation; _.forEach(location.transportations, function(transportation) { $scope.locationObj.transportations[transportation.id] = true; }); location.best_transportation.id && $scope.selectBestTransportation(location.best_transportation.id); location.best_transportation.cost && $scope.selectBestTransportationCost(location.best_transportation.cost) $scope.locationObj.gettingInNotes = location.getting_in_notes; $scope.locationObj.walkingDistance = location.walking_distance; _.forEach(location.food_options, function(foodOption) { $scope.locationObj.foodOptions[foodOption.id] = true; foodOption.cost && $scope.selectFoodOptionDetail(foodOption.id, foodOption.cost); }); $scope.locationObj.commonExpensesNotes = location.common_expenses_notes $scope.locationObj.savingMoneyTips = location.saving_money_tip; }) } $scope.stopPropagation = function($event) { $event.stopPropagation(); }; }); home.controller('LocationsController',function($scope, $timeout,LocationsGetter, $location, $document, $http, helperService){ var locations = this; $scope.locationData = []; $scope.LocationsGetter = LocationsGetter; $scope.originAirport = "Denver International Airport"; $scope.originAirportCode = "DEN"; $scope.slugArray = []; $scope.helperService = helperService; LocationsGetter.locations = LocationsGetter.locations || []; // if we are returning to the front page we want to reset the locations and clear the filters if(LocationsGetter.locations.length > 0) { LocationsGetter.locations = []; LocationsGetter.clearFilters(); LocationsGetter.setFilterTimer(0); } $scope.getAirportPrices = function(item, model, label, event) { $scope.originAirportCode = item.iata; LocationsGetter.getFlightQuotes($scope.slugArray, item.iata); } $scope.$watch('LocationsGetter.flightQuotes', function(){ //set the lowest price and date for location _.forEach(LocationsGetter.flightQuotes, function(quote, key) { var splitKey = key.split('-'); var locationId = splitKey[splitKey.length - 1]; var location = _.find($scope.locationData, function(locationIter) { return locationIter.location.id == locationId; }); var lowestPrice = 9999999; var lowestPriceDate = ''; _.forEach(quote, function(monthArray, month) { _.forEach(monthArray, function(cost, day) { if (lowestPrice > cost) { lowestPrice = cost; lowestPriceDate = month + '/' + day; } }); }); location.lowestPrice = {}; location.lowestPrice.date = lowestPriceDate; location.lowestPrice.cost = lowestPrice; }); $timeout(function(){ setHighcharts(LocationsGetter.flightQuotes,$scope.originAirportCode); }); }); $scope.$watch('LocationsGetter.locations.length', function() { $scope.locationData = LocationsGetter.locations; $scope.slugArray = []; $.each($scope.locationData, function(key, promiseLocation){ $scope.slugArray.push(this['slug']); }); LocationsGetter.getFlightQuotes($scope.slugArray, $scope.originAirportCode); }) $scope.goToFilter = function() { var filter = angular.element(document.getElementById('filter')); $document.scrollToElement(filter, 0, 500); } }); home.controller('MapFilterController',function($rootScope,$scope,LocationsGetter, $timeout, $window){ var filterId; if ($window.innerWidth < 768) { filterId = 'mapFilterMobile'; } else { filterId = 'mapFilter'; } $scope.mapFilterEnabled = true; $rootScope.filterMap = createMap(filterId,70,-160,2); LocationsGetter.markerMap = {}; $rootScope.filterMap.addListener('dragend', function() { LocationsGetter.mapFilter['northeast']['longitude'] = $rootScope.filterMap.getBounds().getNorthEast().lng(); LocationsGetter.mapFilter['northeast']['latitude'] = $rootScope.filterMap.getBounds().getNorthEast().lat(); LocationsGetter.mapFilter['southwest']['longitude'] = $rootScope.filterMap.getBounds().getSouthWest().lng(); LocationsGetter.mapFilter['southwest']['latitude'] = $rootScope.filterMap.getBounds().getSouthWest().lat(); $scope.mapFilterEnabled && LocationsGetter.setFilterTimer(1.5); }); $rootScope.filterMap.addListener('zoom_changed', function() { if (!firstMapLoad) { LocationsGetter.mapFilter['northeast']['longitude'] = $rootScope.filterMap.getBounds().getNorthEast().lng(); LocationsGetter.mapFilter['northeast']['latitude'] = $rootScope.filterMap.getBounds().getNorthEast().lat(); LocationsGetter.mapFilter['southwest']['longitude'] = $rootScope.filterMap.getBounds().getSouthWest().lng(); LocationsGetter.mapFilter['southwest']['latitude'] = $rootScope.filterMap.getBounds().getSouthWest().lat(); $scope.mapFilterEnabled && LocationsGetter.setFilterTimer(1.5); } else { firstMapLoad = false; } }); function notDefaultBounds(bounds) { if (bounds.H.H <= -80 && bounds.H.j >= 80 && bounds.j.H >= 180 && bounds.j.j <= -180) { return false } else { return true; } } var firstMapLoad = true; $scope.$watch('LocationsGetter.unpaginatedLocations.length', function(){ if (LocationsGetter.unpaginatedLocations.length != 0) { $rootScope.filterMap.removeMarkers(); LocationsGetter.markerMap = {}; //redo map points $.each(LocationsGetter.unpaginatedLocations,function(){ LocationsGetter.markerMap[this['slug']] = addMarker($rootScope.filterMap, this['latitude'], this['longitude'], this['name'], '<p><a href="/location/'+this['slug']+'">'+this['name']+'</a></p>',true); LocationsGetter.markerMap[this['slug']].setOptions({opacity: .5}) }); // we set firstMapLoad to false when the zoom_changed watch catches the fitBounds call if (firstMapLoad && filterId == 'mapFilter') { var allowedBounds = new google.maps.LatLngBounds( new google.maps.LatLng(85, -180), // top left corner of map new google.maps.LatLng(-85, 180) // bottom right corner ); var k = 5; var n = allowedBounds.getNorthEast().lat() - k; var e = allowedBounds.getNorthEast().lng() - k; var s = allowedBounds.getSouthWest().lat() + k; var w = allowedBounds.getSouthWest().lng() + k; var neNew = new google.maps.LatLng( n, e ); var swNew = new google.maps.LatLng( s, w ); boundsNew = new google.maps.LatLngBounds(); boundsNew.extend(neNew); boundsNew.extend(swNew); $rootScope.filterMap.fitBounds(allowedBounds); } } }); }); home.factory("LocationsGetter",function($q,$http, $timeout){ var LocationsGetter = {}; LocationsGetter.flightQuotes = null; var filter = {}; LocationsGetter.locations = []; LocationsGetter.unpaginatedLocations = []; LocationsGetter.pageNum = 1; LocationsGetter.filterTimer = null; LocationsGetter.mapFilter = {}; LocationsGetter.markerMap = {}; LocationsGetter.filter = filter; LocationsGetter.scrollLock = false; filter['climbing_types'] = []; filter['accommodations'] = []; filter['continents'] = []; filter['price_max'] = []; filter['sort'] = []; filter['search'] = ''; filter['start_month'] = 1; filter['end_month'] = 12; LocationsGetter.mapFilter['northeast'] = {}; LocationsGetter.mapFilter['northeast']['longitude'] = null; LocationsGetter.mapFilter['northeast']['latitude'] = null; LocationsGetter.mapFilter['southwest'] = {}; LocationsGetter.mapFilter['southwest']['longitude'] = null; LocationsGetter.mapFilter['southwest']['latitude'] = null; LocationsGetter.loading = false; var sort = {}; sort['price'] = []; sort['grade'] = []; LocationsGetter.setFilterTimer = function(seconds) { LocationsGetter.cancelFilterTimer(); LocationsGetter.filterTimer = $timeout(function() { LocationsGetter.pageNum = 1; LocationsGetter.locations = []; LocationsGetter.getNextPage(); }, seconds*1000); } LocationsGetter.cancelFilterTimer = function() { LocationsGetter.filterTimer && $timeout.cancel(LocationsGetter.filterTimer); } LocationsGetter.clearFilters = function() { this.mapFilter = {}; this.markerMap = {}; this.pageNum = 1; filter['climbing_types'] = []; filter['accommodations'] = []; filter['continents'] = []; filter['price_max'] = []; filter['sort'] = []; filter['search'] = ''; filter['start_month'] = 1; filter['end_month'] = 12; this.mapFilter['northeast'] = {}; this.mapFilter['northeast']['longitude'] = null; this.mapFilter['northeast']['latitude'] = null; this.mapFilter['southwest'] = {}; this.mapFilter['southwest']['longitude'] = null; this.mapFilter['southwest']['latitude'] = null; this.loading = false; sort['price'] = []; sort['grade'] = []; }; LocationsGetter.toggleFilterButton = function(eventItem,filterArray,filterValue){ toggleButtonActive(angular.element(eventItem.currentTarget)); angular.element(eventItem.currentTarget).blur(); if(filterValue != 'sort' && $.inArray(filterValue,filter[filterArray]) != -1){ //remove item from filter filter[filterArray].splice($.inArray(filterValue,filter[filterArray]), 1); } else if( filterValue == 'All'){ filter[filterArray] = []; resetButtonsGroup(angular.element(eventItem.currentTarget).parent()); } else{ filter[filterArray].push(filterValue); inactivateGroupAll(angular.element(eventItem.currentTarget).parent()); //only one sorter can be active at a time so we have special cases for it if(filterArray == 'sort'){ resetButtonsGroup(angular.element(eventItem.currentTarget).parent()); toggleButtonActive(angular.element(eventItem.currentTarget)); inactivateGroupAll(angular.element(eventItem.currentTarget).parent()); } } LocationsGetter.setFilterTimer(1); }; LocationsGetter.filterByMonth = function(startMonth, endMonth) { filter['start_month'] = startMonth; filter['end_month'] = endMonth; LocationsGetter.setFilterTimer(1.5); } LocationsGetter.filterByQuery = function(eventItem){ filter['search'] = eventItem; LocationsGetter.setFilterTimer(0); } LocationsGetter.getFlightQuotes = function(slugs,originAirportCode){ return $http.post('/api/collect_locations_quotes', {slugs: slugs, origin_airport: originAirportCode}).then(function(response){ LocationsGetter.flightQuotes = response.data; return response.data; }); }; LocationsGetter.getNextPage = function() { LocationsGetter.scrollLock = true; return LocationsGetter.getLocations().then(function(locations) { LocationsGetter.pageNum++; LocationsGetter.scrollLock = false; return locations; }); }; LocationsGetter.setSorting = function(sortBy, asc) { if (sortBy == 'distance') { navigator.geolocation.getCurrentPosition( function(position) { LocationsGetter.myLat = position.coords.latitude; LocationsGetter.myLong = position.coords.longitude; filter.sort ={distance: {latitude: LocationsGetter.myLat, longitude: LocationsGetter.myLong}}; LocationsGetter.setFilterTimer(0); }, function() { console.error('error getting location(probably blocked)'); alert('Need location permission to sort by distance, ' + 'if you arent given the option to grant permission, ' + 'it is probably because your browser doesnt support non-ssl geolocation requests... the webmaster is a cheap bastard' + 'and doesnt want to spend $20/mo, go to https://climbcation.herokuapp.com and it should work just fine'); } ); } else { filter.sort = {}; filter.sort[sortBy] = {asc: asc}; LocationsGetter.setFilterTimer(0); } } LocationsGetter.getLocations = function(){ LocationsGetter.loading = true; return $http.post('/api/filter_locations', {filter: filter, mapFilter: LocationsGetter.mapFilter, page: LocationsGetter.pageNum}).then(function(response){ LocationsGetter.loading = false; if (response.data.unpaginated.length != LocationsGetter.unpaginatedLocations.length && response.data.unpaginated.length != 0) { LocationsGetter.unpaginatedLocations = response.data.unpaginated; } var promiseLocations = response.data.paginated; LocationsGetter.locations || (LocationsGetter.locations = []); $.each(promiseLocations, function(key, promiseLocation){ var exists = _.find(LocationsGetter.locations, function(locationIter) { return locationIter.id == promiseLocation.id; }); !exists && LocationsGetter.locations.push(promiseLocation); }); if (_.size(promiseLocations) == 0) { LocationsGetter.scrollEnded = true; } else { LocationsGetter.scrollEnded = false; } return response.data; }); }; return LocationsGetter; }); function toggleButtonActive(clickedButton){ if(clickedButton.hasClass('active')){ clickedButton.removeClass('active'); } else{ clickedButton.addClass('active'); } } function resetButtonsGroup(buttonGroup){ buttonGroup.children('button').each(function(){ $(this).removeClass('active'); if($(this).hasClass('all')){ $(this).addClass('active'); } }); } function inactivateGroupAll(buttonGroup){ buttonGroup.children('button').each(function(){ if($(this).hasClass('all')){ $(this).removeClass('active'); } }); } function createMap(mapId,latitude,longitude,zoom){ var map =new GMaps({ div: '#'+mapId, lat: latitude, lng: longitude, zoom: zoom, scrollwheel: false }); $('body').on('click', function(element) { map.setOptions({scrollwheel:false}); }); $('#'+mapId).on('click', function (e) { e.stopPropagation(); map.setOptions({scrollwheel:true}); return; }); return map; } function addCloseLocations(map,locationMap){ $.each(locationMap,function(){ addMarker(map,this['lat'],this['lng'],this['name'],'<p><a href="/location/'+this['slug']+'">'+this['name']+'</a></p>',true); }); } function addMarker(map,lat,lng,title,infowindow,isSecondary){ return map.addMarker({ lat: lat, lng: lng, title: title, icon: isSecondary?'':'https://s3-us-west-2.amazonaws.com/climbcation-front/assets/primary.png', infoWindow:{ content: infowindow } }); } function processTableContents(sectionMap){ var titleArray = []; var counter = 0; $.each(sectionMap,function(){ index = parseInt(counter/3) if(!(index in titleArray)){ titleArray[index] = []; } titleArray[index].push(this['title']); counter++; }); return titleArray; } function processSectionsByPair(sectionMap){ pairMap = {}; var counter = 0; var sectCounter = 0; $.each(sectionMap, function(){ counter = 0; if(this['data'] != null){ pairMap = {}; $.each(this['data'],function(key,value){ pairIndex = parseInt(counter/2); if(counter % 2 == 0){ pairMap[pairIndex] = {} } //pairMap[pairIndex][counter%2] = value; pairMap[pairIndex][key] = value; counter++; }); this['data'] = pairMap; } sectCounter++; }); } function setHighcharts(locationQuoteData, origin_airport){ $.each(locationQuoteData,function(slug,months){ destinationAirport = slug.split("-")[0] quote_array = []; var maxPrice = 0; $.each(this,function(monthKey,value){ $.each(value, function(dayKey,cost){ quote_array.push([monthKey+'/'+dayKey,cost]) if(cost > maxPrice) maxPrice = cost; }) }); $('#highchart'+slug).highcharts({ chart: { type: 'line', height: '100' }, title: { useHTML: true, text: 'One Way cost from '+origin_airport+' to '+destinationAirport + '<a href="http://skyscanner.net" target="_blank"><img src="/images/skyscannerinline.png"></a>', floating: false }, xAxis: { visible: false, type: 'category', title: { text: 'Date' }, labels: { rotation: -45, style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }, yAxis: { visible: false, min: 0, title: { text: 'Price(USD)' }, tickInterval: 50, max: maxPrice }, legend: { enabled: false }, tooltip: { pointFormat: 'Price: <b>${point.y:.1f} </b>' }, series: [{ name: 'Price', data: quote_array, dataLabels: { enabled: false, rotation: -90, color: '#FFFFFF', align: 'right', format: '{point.y:.1f}', // one decimal y: 10, // 10 pixels down from the top style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }] }); }); $('text:contains("Highcharts.com")').hide(); } function setLocationHighchart(locationQuoteData, origin_airport){ $.each(locationQuoteData,function(slug,months){ destinationAirport = slug.split("-")[0] quote_array = []; var maxPrice = 0; $.each(this,function(monthKey,value){ $.each(value, function(dayKey,cost){ quote_array.push([monthKey+'/'+dayKey,cost]) if(cost > maxPrice) maxPrice = cost; }) }); $('#highchart'+slug).highcharts({ chart: { type: 'line', height: '200' }, title: { useHTML: true, text: 'One Way cost from '+origin_airport+' to '+destinationAirport + '<a href="http://skyscanner.net" target="_blank"><img src="/images/skyscannerinline.png"></a>', floating: false }, xAxis: { visible: true, type: 'category', title: { text: 'Date' }, labels: { rotation: -45, style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }, yAxis: { visible: true, min: 0, title: { text: 'Price(USD)' }, tickInterval: 50, max: maxPrice }, legend: { enabled: false }, tooltip: { pointFormat: 'Price: <b>${point.y:.1f} </b>' }, series: [{ name: 'Price', data: quote_array, dataLabels: { enabled: false, rotation: -90, color: '#FFFFFF', align: 'right', format: '{point.y:.1f}', // one decimal y: 10, // 10 pixels down from the top style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }] }); }); }
skyscanner referral
app/js/app.js
skyscanner referral
<ide><path>pp/js/app.js <ide> quote_array = []; <ide> var maxPrice = 0; <ide> $.each(this,function(monthKey,value){ <del> $.each(value, function(dayKey,cost){ <del> quote_array.push([monthKey+'/'+dayKey,cost]) <del> if(cost > maxPrice) <del> maxPrice = cost; <del> }) <add> if (monthKey != 'referral') { <add> $.each(value, function(dayKey,cost){ <add> quote_array.push([monthKey+'/'+dayKey,cost]) <add> if(cost > maxPrice) { <add> maxPrice = cost; <add> } <add> }); <add> } <ide> <ide> }); <ide> $('#highchart'+slug).highcharts({ <ide> }, <ide> title: { <ide> useHTML: true, <del> text: 'One Way cost from '+origin_airport+' to '+destinationAirport + '<a href="http://skyscanner.net" target="_blank"><img src="/images/skyscannerinline.png"></a>', <add> text: 'One Way cost from '+origin_airport+' to '+destinationAirport + '<a href="' + this.referral + '" target="_blank"><img src="/images/skyscannerinline.png"></a>', <ide> floating: false <ide> }, <ide> xAxis: { <ide> } <ide> <ide> function setLocationHighchart(locationQuoteData, origin_airport){ <del> $.each(locationQuoteData,function(slug,months){ <add> $.each(locationQuoteData,function(slug, months){ <ide> destinationAirport = slug.split("-")[0] <ide> quote_array = []; <ide> var maxPrice = 0; <ide> $.each(this,function(monthKey,value){ <del> $.each(value, function(dayKey,cost){ <del> quote_array.push([monthKey+'/'+dayKey,cost]) <del> if(cost > maxPrice) <del> maxPrice = cost; <del> }) <del> <add> if (monthKey != 'referral') { <add> $.each(value, function(dayKey,cost){ <add> quote_array.push([monthKey+'/'+dayKey,cost]) <add> if(cost > maxPrice) { <add> maxPrice = cost; <add> } <add> }); <add> } <ide> }); <ide> $('#highchart'+slug).highcharts({ <ide> chart: { <ide> }, <ide> title: { <ide> useHTML: true, <del> text: 'One Way cost from '+origin_airport+' to '+destinationAirport + '<a href="http://skyscanner.net" target="_blank"><img src="/images/skyscannerinline.png"></a>', <add> text: 'One Way cost from '+origin_airport+' to '+destinationAirport + '<a href="' + this.referral + '" target="_blank"><img src="/images/skyscannerinline.png"></a>', <ide> floating: false <ide> }, <ide> xAxis: {
JavaScript
mit
39c6fcd678f66fdb2d46d28046d7b35bd4bbf679
0
erasme/erajs
Ui.CanvasElement.extend('Ui.Frame', { fill: undefined, radiusTopLeft: 0, radiusTopRight: 0, radiusBottomLeft: 0, radiusBottomRight: 0, frameWidth: 10, constructor: function(config) { this.fill = new Ui.Color({ r: 0, g: 0, b: 0 }); }, getFrameWidth: function() { return this.frameWidth; }, setFrameWidth: function(frameWidth) { if(frameWidth != this.frameWidth) { this.frameWidth = frameWidth; this.invalidateDraw(); } }, getFill: function() { return this.fill; }, setFill: function(fill) { if(this.fill != fill) { if(typeof(fill) === 'string') fill = Ui.Color.create(fill); this.fill = fill; this.invalidateDraw(); } }, setRadius: function(radius) { this.setRadiusTopLeft(radius); this.setRadiusTopRight(radius); this.setRadiusBottomLeft(radius); this.setRadiusBottomRight(radius); }, getRadiusTopLeft: function() { return this.radiusTopLeft; }, setRadiusTopLeft: function(radiusTopLeft) { if(this.radiusTopLeft != radiusTopLeft) { this.radiusTopLeft = radiusTopLeft; this.invalidateDraw(); } }, getRadiusTopRight: function() { return this.radiusTopRight; }, setRadiusTopRight: function(radiusTopRight) { if(this.radiusTopRight != radiusTopRight) { this.radiusTopRight = radiusTopRight; this.invalidateDraw(); } }, getRadiusBottomLeft: function() { return this.radiusBottomLeft; }, setRadiusBottomLeft: function(radiusBottomLeft) { if(this.radiusBottomLeft != radiusBottomLeft) { this.radiusBottomLeft = radiusBottomLeft; this.invalidateDraw(); } }, getRadiusBottomRight: function() { return this.radiusBottomRight; }, setRadiusBottomRight: function(radiusBottomRight) { if(this.radiusBottomRight != radiusBottomRight) { this.radiusBottomRight = radiusBottomRight; this.invalidateDraw(); } } }, { updateCanvas: function(ctx) { var w = this.getLayoutWidth(); var h = this.getLayoutHeight(); var topLeft = this.radiusTopLeft; var topRight = this.radiusTopRight; if(topLeft + topRight > w) { topLeft = w/2; topRight = w/2; } var bottomLeft = this.radiusBottomLeft; var bottomRight = this.radiusBottomRight; if(bottomLeft + bottomRight > w) { bottomLeft = w/2; bottomRight = w/2; } if(topLeft + bottomLeft > h) { topLeft = h/2; bottomLeft = h/2; } if(topRight + bottomRight > h) { topRight = h/2; bottomRight = h/2; } ctx.beginPath(); ctx.roundRect(0, 0, w, h, topLeft, topRight, bottomRight, bottomLeft); ctx.roundRect(this.frameWidth, this.frameWidth, w-(this.frameWidth*2), h-(this.frameWidth*2), Math.max(0, topLeft-this.frameWidth), Math.max(0, topRight-this.frameWidth), Math.max(0, bottomRight-this.frameWidth), Math.max(0, bottomLeft-this.frameWidth), true); ctx.closePath(); if(Ui.Color.hasInstance(this.fill)) ctx.fillStyle = this.fill.getCssRgba(); else if(Ui.LinearGradient.hasInstance(this.fill)) ctx.fillStyle = this.fill.getCanvasGradient(ctx, w, h); ctx.fill(); } });
era/ui/frame.js
Ui.CanvasElement.extend('Ui.Frame', { fill: undefined, radiusTopLeft: 0, radiusTopRight: 0, radiusBottomLeft: 0, radiusBottomRight: 0, frameWidth: 10, constructor: function(config) { this.fill = new Ui.Color({ r: 0, g: 0, b: 0 }); }, getFrameWidth: function() { return this.frameWidth; }, setFrameWidth: function(frameWidth) { if(frameWidth != this.frameWidth) { this.frameWidth = frameWidth; this.invalidateDraw(); } }, getFill: function() { return this.fill; }, setFill: function(fill) { if(this.fill != fill) { if(typeof(fill) === 'string') fill = Ui.Color.create(fill); this.fill = fill; this.invalidateDraw(); } }, setRadius: function(radius) { this.setRadiusTopLeft(radius); this.setRadiusTopRight(radius); this.setRadiusBottomLeft(radius); this.setRadiusBottomRight(radius); }, getRadiusTopLeft: function() { return this.radiusTopLeft; }, setRadiusTopLeft: function(radiusTopLeft) { if(this.radiusTopLeft != radiusTopLeft) { this.radiusTopLeft = radiusTopLeft; this.invalidateDraw(); } }, getRadiusTopRight: function() { return this.radiusTopRight; }, setRadiusTopRight: function(radiusTopRight) { if(this.radiusTopRight != radiusTopRight) { this.radiusTopRight = radiusTopRight; this.invalidateDraw(); } }, getRadiusBottomLeft: function() { return this.radiusBottomLeft; }, setRadiusBottomLeft: function(radiusBottomLeft) { if(this.radiusBottomLeft != radiusBottomLeft) { this.radiusBottomLeft = radiusBottomLeft; this.invalidateDraw(); } }, getRadiusBottomRight: function() { return this.radiusBottomRight; }, setRadiusBottomRight: function(radiusBottomRight) { if(this.radiusBottomRight != radiusBottomRight) { this.radiusBottomRight = radiusBottomRight; this.invalidateDraw(); } } }, { updateCanvas: function(ctx) { var w = this.getLayoutWidth(); var h = this.getLayoutHeight(); var topLeft = this.radiusTopLeft; var topRight = this.radiusTopRight; if(topLeft + topRight > w) { topLeft = w/2; topRight = w/2; } var bottomLeft = this.radiusBottomLeft; var bottomRight = this.radiusBottomRight; if(bottomLeft + bottomRight > w) { bottomLeft = w/2; bottomRight = w/2; } if(topLeft + bottomLeft > h) { topLeft = h/2; bottomLeft = h/2; } if(topRight + bottomRight > h) { topRight = h/2; bottomRight = h/2; } ctx.beginPath(); ctx.roundRect(0, 0, w, h, topLeft, topRight, bottomRight, bottomLeft); ctx.roundRect(this.frameWidth, this.frameWidth, w-(this.frameWidth*2), h-(this.frameWidth*2), topLeft, topRight, bottomRight, bottomLeft, true); ctx.closePath(); if(Ui.Color.hasInstance(this.fill)) ctx.fillStyle = this.fill.getCssRgba(); else if(Ui.LinearGradient.hasInstance(this.fill)) ctx.fillStyle = this.fill.getCanvasGradient(ctx, w, h); ctx.fill(); } });
avoid graphical problems with negative radius for Ui.Frame
era/ui/frame.js
avoid graphical problems with negative radius for Ui.Frame
<ide><path>ra/ui/frame.js <ide> <ide> ctx.beginPath(); <ide> ctx.roundRect(0, 0, w, h, topLeft, topRight, bottomRight, bottomLeft); <del> ctx.roundRect(this.frameWidth, this.frameWidth, w-(this.frameWidth*2), h-(this.frameWidth*2), topLeft, topRight, bottomRight, bottomLeft, true); <add> ctx.roundRect(this.frameWidth, this.frameWidth, w-(this.frameWidth*2), h-(this.frameWidth*2), Math.max(0, topLeft-this.frameWidth), Math.max(0, topRight-this.frameWidth), Math.max(0, bottomRight-this.frameWidth), Math.max(0, bottomLeft-this.frameWidth), true); <ide> ctx.closePath(); <ide> if(Ui.Color.hasInstance(this.fill)) <ide> ctx.fillStyle = this.fill.getCssRgba();
Java
apache-2.0
6c54bd77a5d87a84c5b466bd1976926cc0233e53
0
andrei-viaryshka/pentaho-hadoop-shims,SergeyTravin/pentaho-hadoop-shims,dkincade/pentaho-hadoop-shims,smaring/pentaho-hadoop-shims,pentaho/pentaho-hadoop-shims,mkambol/pentaho-hadoop-shims
/******************************************************************************* * * Pentaho Big Data * * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.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 org.pentaho.hadoop.shim; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import java.util.Map.Entry; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSelectInfo; import org.apache.commons.vfs2.FileSelector; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileType; import org.apache.commons.vfs2.impl.DefaultFileSystemManager; import org.apache.log4j.Logger; import org.pentaho.di.core.Const; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.hadoop.shim.api.ActiveHadoopConfigurationLocator; import org.pentaho.hadoop.shim.api.Required; import org.pentaho.hadoop.shim.api.ShimProperties; import org.pentaho.hadoop.shim.spi.HadoopConfigurationProvider; import org.pentaho.hadoop.shim.spi.HadoopShim; import org.pentaho.hadoop.shim.spi.PentahoHadoopShim; import org.pentaho.hadoop.shim.spi.PigShim; import org.pentaho.hadoop.shim.spi.SnappyShim; import org.pentaho.hadoop.shim.spi.SqoopShim; import org.pentaho.hbase.shim.spi.HBaseShim; import org.pentaho.oozie.shim.api.OozieClientFactory; /** * A file-based Hadoop configuration provider that knows how to load Hadoop configurations from a VFS file system. This * class is not thread-safe. */ public class HadoopConfigurationLocator implements HadoopConfigurationProvider { private static final String JAR_EXTENSION = ".jar"; private static final String CONFIG_PROPERTIES_FILE = "config.properties"; private static final String CONFIG_PROPERTY_IGNORE_CLASSES = "ignore.classes"; private static final String SHIM_CLASSPATH_IGNORE = "classpath.ignore"; private static final String CONFIG_PROPERTY_CLASSPATH = "classpath"; private static final String CONFIG_PROPERTY_LIBRARY_PATH = "library.path"; private static final String CONFIG_PROPERTY_NAME = "name"; private static final URL[] EMPTY_URL_ARRAY = new URL[ 0 ]; private static final Class<?> PKG = HadoopConfigurationLocator.class; private Logger logger = Logger.getLogger( getClass() ); /** * This is a set of shim classes to load from each Hadoop configuration. TODO Externalize this list so we may * configure it per installation */ @SuppressWarnings( "unchecked" ) private static final Class<? extends PentahoHadoopShim>[] SHIM_TYPES = new Class[] { HadoopShim.class, HBaseShim.class, PigShim.class, SnappyShim.class, SqoopShim.class, OozieClientFactory.class }; private static final PentahoHadoopShim[] EMPTY_SHIM_ARRAY = new PentahoHadoopShim[ 0 ]; /** * Currently known shim configurations */ private Map<String, HadoopConfiguration> configurations; /** * Flag indicating we've been initialized. We require initialization to know where to look for Hadoop configurations * on disk. */ private boolean initialized; /** * Used to determine the active Hadoop configuration at runtime */ private ActiveHadoopConfigurationLocator activeLocator; /** * The file system manager used to provide shims a way to register their {@link FileProvider} implementations. */ private HadoopConfigurationFileSystemManager fsm; private DefaultFileSystemManager defaultFsm; /** * Initialize this factory with a directory of where to look for cluster configurations. * * @param baseDir Directory to look for Hadoop configurations in * @param activeLocator A locator for resolving the current active Hadoop configuration * @param fsm A file system manager to inject VFS file providers into from any loaded Hadoop configuration */ public void init( FileObject baseDir, ActiveHadoopConfigurationLocator activeLocator, DefaultFileSystemManager fsm ) throws ConfigurationException { if ( baseDir == null ) { throw new NullPointerException( FileObject.class.getSimpleName() + " is required" ); } if ( activeLocator == null ) { throw new NullPointerException( ActiveHadoopConfigurationLocator.class.getSimpleName() + " is required" ); } if ( fsm == null ) { throw new NullPointerException( DefaultFileSystemManager.class.getSimpleName() + " is required" ); } this.defaultFsm = fsm; this.fsm = new HadoopConfigurationFileSystemManager( this, fsm ); findHadoopConfigurations( baseDir, activeLocator ); this.activeLocator = activeLocator; initialized = true; } /** * Attempt to find any Hadoop configuration as a direct descendant of the provided directory. * * @param baseDir Directory to look for Hadoop configurations in * @throws ConfigurationException */ private void findHadoopConfigurations( FileObject baseDir, ActiveHadoopConfigurationLocator activeLocator ) throws ConfigurationException { configurations = new HashMap<String, HadoopConfiguration>(); try { if ( !baseDir.exists() ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.HadoopConfigurationDirectoryDoesNotExist", baseDir.getURL() ) ); } for ( FileObject f : baseDir.findFiles( new FileSelector() { @Override public boolean includeFile( FileSelectInfo info ) throws Exception { return info.getDepth() == 1 && FileType.FOLDER.equals( info.getFile().getType() ); } @Override public boolean traverseDescendents( FileSelectInfo info ) throws Exception { return info.getDepth() == 0; } } ) ) { // Only load the specified configuration (ID should match the basename, we allow case-insensitivity) if ( f.getName().getBaseName().equalsIgnoreCase( activeLocator.getActiveConfigurationId() ) ) { HadoopConfiguration config = loadHadoopConfiguration( f ); if ( config != null ) { configurations.put( config.getIdentifier(), config ); } } } } catch ( FileSystemException ex ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.UnableToLoadConfigurations", baseDir.getName().getFriendlyURI() ), ex ); } } private List<URL> findJarsIn( FileObject path, final int maxdepth, final Set<String> paths ) throws FileSystemException { FileObject[] jars = path.findFiles( new FileSelector() { @Override public boolean includeFile( FileSelectInfo info ) throws Exception { for ( String path : paths ) { if ( info.getFile().getURL().toString().endsWith( path ) ) { return false; } } return info.getFile().getName().getBaseName().endsWith( JAR_EXTENSION ); } @Override public boolean traverseDescendents( FileSelectInfo info ) throws Exception { for ( String path : paths ) { if ( info.getFile().getURL().toString().endsWith( path ) ) { return false; } } return info.getDepth() <= maxdepth; } } ); List<URL> jarUrls = new ArrayList<URL>(); for ( FileObject jar : jars ) { jarUrls.add( jar.getURL() ); } return jarUrls; } /** * Find all jar files in the path provided. * * @param path Path to search for jar files within * @param maxdepth Maximum traversal depth (1-based) * @return All jars found within {@code path} in at most {@code maxdepth} subdirectories. * @throws FileSystemException */ private void checkInitialized() { if ( !initialized ) { throw new RuntimeException( BaseMessages.getString( PKG, "Error.LocatorNotInitialized" ) ); } } /** * Locates an implementation of {@code service} using the {@link ServiceLoader}. * * @param cl Class loader to look for implementations in * @return The first implementation found. */ protected <T> T locateServiceImpl( ClassLoader cl, Class<T> service ) { ServiceLoader<T> loader = ServiceLoader.load( service, cl ); Iterator<T> iter = loader.iterator(); if ( iter.hasNext() ) { return iter.next(); } return null; } /** * Create a ClassLoader to load resources for a {@code HadoopConfiguration}. * * @param root Configuration root directory * @param parent Parent class loader to delegate to if resources cannot be found in the configuration's * directory or provided classpath * @param classpathUrls Additional URLs to add to the class loader. These will be added before any internal * resources. * @param ignoredClasses Classes (or packages) that should not be loaded by the class loader * @return A class loader capable of loading a Hadoop configuration located at {@code root}. * @throws ConfigurationException Error creating a class loader for the Hadoop configuration located at {@code root} */ protected ClassLoader createConfigurationLoader( FileObject root, ClassLoader parent, List<URL> classpathUrls, ShimProperties configurationProperties, String... ignoredClasses ) throws ConfigurationException { try { if ( root == null || !FileType.FOLDER.equals( root.getType() ) ) { throw new IllegalArgumentException( "root must be a folder: " + root ); } // Find all jar files in the configuration, at most 2 folders deep List<URL> jars = findJarsIn( root, 3, configurationProperties.getConfigSet( SHIM_CLASSPATH_IGNORE ) ); // Add the root of the configuration jars.add( 0, new URL( root.getURL().toExternalForm() + "/" ) ); // Inject any overriding URLs before all other paths if ( classpathUrls != null ) { jars.addAll( 0, classpathUrls ); } return new HadoopConfigurationClassLoader( jars.toArray( EMPTY_URL_ARRAY ), parent, ignoredClasses ); } catch ( Exception ex ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.CreatingClassLoader" ), ex ); } } /** * Parse a set of URLs from a comma-separated list of URLs. If the URL points to a directory all jar files within that * directory will be returned as well. * * @param urlString Comma-separated list of URLs (relative or absolute) * @return List of URLs resolved from {@code urlString} */ protected List<URL> parseURLs( FileObject root, String urlString ) { if ( urlString == null || urlString.trim().isEmpty() ) { return Collections.emptyList(); } String[] paths = urlString.split( "," ); List<URL> urls = new ArrayList<URL>(); for ( String path : paths ) { try { FileObject file = root.resolveFile( path.trim() ); if ( !file.exists() ) { file = defaultFsm.resolveFile( path.trim() ); } if ( FileType.FOLDER.equals( file.getType() ) ) { // Add directories with a trailing / so the URL ClassLoader interprets // them as directories urls.add( new URL( file.getURL().toExternalForm() + "/" ) ); // Also add all jars within this directory urls.addAll( findJarsIn( file, 1, new HashSet<String>() ) ); } else { urls.add( file.getURL() ); } } catch ( Exception e ) { // Log invalid path logger.error( BaseMessages.getString( PKG, "Error.InvalidClasspathEntry", path ) ); } } return urls; } /** * Attempt to discover a valid Hadoop configuration from the provided folder. * * @param folder Folder that may represent a Hadoop configuration * @return A Hadoop configuration for the folder provided or null if none is found. * @throws ConfigurationException Error when loading the Hadoop configuration. */ protected HadoopConfiguration loadHadoopConfiguration( FileObject folder ) throws ConfigurationException { ShimProperties configurationProperties = new ShimProperties(); try { FileObject configFile = folder.getChild( CONFIG_PROPERTIES_FILE ); if ( configFile != null ) { configurationProperties.putAll( loadProperties( configFile ) ); } } catch ( Exception ex ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.UnableToLoadConfigurationProperties", CONFIG_PROPERTIES_FILE ) ); } for ( Entry<String, String> entry : configurationProperties.getPrefixedProperties( "java.system" ).entrySet() ) { System.setProperty( entry.getKey(), entry.getValue() ); } try { // Parse all URLs from an optional classpath from the configuration file List<URL> classpathElements = parseURLs( folder, configurationProperties.getProperty( CONFIG_PROPERTY_CLASSPATH ) ); // Allow external configuration of classes to ignore String ignoredClassesProperty = configurationProperties .getProperty( CONFIG_PROPERTY_IGNORE_CLASSES ); String[] ignoredClasses = null; if ( ignoredClassesProperty != null ) { ignoredClasses = ignoredClassesProperty.split( "," ); } // Pass our class loader in to the configurations' CL as its parent so it // can find the same // API classes we're using ClassLoader cl = createConfigurationLoader( folder, getClass() .getClassLoader(), classpathElements, configurationProperties, ignoredClasses ); verifyClasses( cl, configurationProperties.getProperty( "required.classes" ), configurationProperties.getProperty( "name" ) ); // Treat the Hadoop shim special. It is absolutely required for a Hadoop configuration. HadoopShim hadoopShim = null; List<PentahoHadoopShim> shims = new ArrayList<PentahoHadoopShim>(); // Attempt to locate a shim within this folder for ( Class<? extends PentahoHadoopShim> shimType : SHIM_TYPES ) { PentahoHadoopShim s = locateServiceImpl( cl, shimType ); if ( s == null && shimType.getAnnotation( Required.class ) != null ) { logger.warn( BaseMessages.getString( PKG, "Error.MissingRequiredShim", shimType.getSimpleName() ) ); // Do not continue to load the configuration if we are missing a required shim return null; } if ( HadoopShim.class.isAssignableFrom( shimType ) ) { hadoopShim = (HadoopShim) s; } else { shims.add( s ); } } String id = folder.getName().getBaseName(); String name = configurationProperties.getProperty( CONFIG_PROPERTY_NAME, id ); HadoopConfiguration config = new HadoopConfiguration( configurationProperties, folder, id, name, hadoopShim, shims.toArray( EMPTY_SHIM_ARRAY ) ); // Register native libraries after everything else has been loaded successfully registerNativeLibraryPaths( configurationProperties.getProperty( CONFIG_PROPERTY_LIBRARY_PATH ) ); hadoopShim.onLoad( config, fsm ); return config; } catch ( Throwable t ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.LoadingConfiguration" ) + " " + t.toString(), t ); } } protected void verifyClasses( ClassLoader classLoader, String requiredClasses, String shimName ) throws ConfigurationException { if ( !Const.isEmpty( requiredClasses ) ) { for ( String className : requiredClasses.split( "," ) ) { try { classLoader.loadClass( className ); } catch ( Throwable e ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.MissingRequiredClasses", className, shimName ) ); } } } } /** * Register a comma-separated list of native library paths. * * @param paths Comma-separated list of libraries */ protected void registerNativeLibraryPaths( String paths ) { if ( paths == null ) { return; } for ( String path : paths.split( "," ) ) { boolean successful = registerNativeLibraryPath( path ); if ( !successful ) { logger.error( BaseMessages.getString( PKG, "Error.RegisteringLibraryPath", path ) ); } } } /** * Dynamically register a native library path. This relies on a specific implementation detail of ClassLoader: it's * usr_paths property. * * @param path Library path to add * @return {@code true} if the library path could be added successfully */ protected boolean registerNativeLibraryPath( String path ) { if ( path == null ) { throw new NullPointerException(); } path = path.trim(); try { Field f = ClassLoader.class.getDeclaredField( "usr_paths" ); boolean accessible = f.isAccessible(); f.setAccessible( true ); try { String[] paths = (String[]) f.get( null ); // Make sure the path isn't already registered for ( String p : paths ) { if ( p.equals( path ) ) { return true; // Success, it's already there! } } String[] newPaths = new String[ paths.length + 1 ]; System.arraycopy( paths, 0, newPaths, 0, paths.length ); newPaths[ paths.length ] = path; f.set( null, newPaths ); // Success! return true; } finally { f.setAccessible( accessible ); } } catch ( Exception ex ) { // Something went wrong, definitely not successful return false; } } /** * Load the properties file located at {@code file} * * @param file Location of a properties file to load * @return Loaded properties file * @throws IOException Error loading properties from file * @throws FileSystemException Error locating input stream for file */ protected Properties loadProperties( FileObject file ) throws FileSystemException, IOException { Properties p = new Properties(); p.load( file.getContent().getInputStream() ); return p; } @Override public List<HadoopConfiguration> getConfigurations() { checkInitialized(); return new ArrayList<HadoopConfiguration>( configurations.values() ); } @Override public boolean hasConfiguration( String id ) { checkInitialized(); return configurations.containsKey( id ); } @Override public HadoopConfiguration getConfiguration( String id ) throws ConfigurationException { checkInitialized(); HadoopConfiguration config = configurations.get( id ); if ( config == null ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.UnknownHadoopConfiguration", id ) ); } return config; } @Override public HadoopConfiguration getActiveConfiguration() throws ConfigurationException { return getConfiguration( activeLocator.getActiveConfigurationId() ); } }
api/src/org/pentaho/hadoop/shim/HadoopConfigurationLocator.java
/******************************************************************************* * * Pentaho Big Data * * Copyright (C) 2002-2015 by Pentaho : http://www.pentaho.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 org.pentaho.hadoop.shim; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.ServiceLoader; import java.util.Set; import java.util.Map.Entry; import org.apache.commons.vfs2.FileObject; import org.apache.commons.vfs2.FileSelectInfo; import org.apache.commons.vfs2.FileSelector; import org.apache.commons.vfs2.FileSystemException; import org.apache.commons.vfs2.FileType; import org.apache.commons.vfs2.impl.DefaultFileSystemManager; import org.apache.log4j.Logger; import org.pentaho.di.core.Const; import org.pentaho.di.i18n.BaseMessages; import org.pentaho.hadoop.shim.api.ActiveHadoopConfigurationLocator; import org.pentaho.hadoop.shim.api.Required; import org.pentaho.hadoop.shim.api.ShimProperties; import org.pentaho.hadoop.shim.spi.HadoopConfigurationProvider; import org.pentaho.hadoop.shim.spi.HadoopShim; import org.pentaho.hadoop.shim.spi.PentahoHadoopShim; import org.pentaho.hadoop.shim.spi.PigShim; import org.pentaho.hadoop.shim.spi.SnappyShim; import org.pentaho.hadoop.shim.spi.SqoopShim; import org.pentaho.hbase.shim.spi.HBaseShim; import org.pentaho.oozie.shim.api.OozieClientFactory; /** * A file-based Hadoop configuration provider that knows how to load Hadoop configurations from a VFS file system. This * class is not thread-safe. */ public class HadoopConfigurationLocator implements HadoopConfigurationProvider { private static final String JAR_EXTENSION = ".jar"; private static final String CONFIG_PROPERTIES_FILE = "config.properties"; private static final String CONFIG_PROPERTY_IGNORE_CLASSES = "ignore.classes"; private static final String SHIM_CLASSPATH_IGNORE = "classpath.ignore"; private static final String CONFIG_PROPERTY_CLASSPATH = "classpath"; private static final String CONFIG_PROPERTY_LIBRARY_PATH = "library.path"; private static final String CONFIG_PROPERTY_NAME = "name"; private static final URL[] EMPTY_URL_ARRAY = new URL[ 0 ]; private static final Class<?> PKG = HadoopConfigurationLocator.class; private Logger logger = Logger.getLogger( getClass() ); /** * This is a set of shim classes to load from each Hadoop configuration. TODO Externalize this list so we may * configure it per installation */ @SuppressWarnings( "unchecked" ) private static final Class<? extends PentahoHadoopShim>[] SHIM_TYPES = new Class[] { HadoopShim.class, HBaseShim.class, PigShim.class, SnappyShim.class, SqoopShim.class, OozieClientFactory.class }; private static final PentahoHadoopShim[] EMPTY_SHIM_ARRAY = new PentahoHadoopShim[ 0 ]; /** * Currently known shim configurations */ private Map<String, HadoopConfiguration> configurations; /** * Flag indicating we've been initialized. We require initialization to know where to look for Hadoop configurations * on disk. */ private boolean initialized; /** * Used to determine the active Hadoop configuration at runtime */ private ActiveHadoopConfigurationLocator activeLocator; /** * The file system manager used to provide shims a way to register their {@link FileProvider} implementations. */ private HadoopConfigurationFileSystemManager fsm; private DefaultFileSystemManager defaultFsm; /** * Initialize this factory with a directory of where to look for cluster configurations. * * @param baseDir Directory to look for Hadoop configurations in * @param activeLocator A locator for resolving the current active Hadoop configuration * @param fsm A file system manager to inject VFS file providers into from any loaded Hadoop configuration */ public void init( FileObject baseDir, ActiveHadoopConfigurationLocator activeLocator, DefaultFileSystemManager fsm ) throws ConfigurationException { if ( baseDir == null ) { throw new NullPointerException( FileObject.class.getSimpleName() + " is required" ); } if ( activeLocator == null ) { throw new NullPointerException( ActiveHadoopConfigurationLocator.class.getSimpleName() + " is required" ); } if ( fsm == null ) { throw new NullPointerException( DefaultFileSystemManager.class.getSimpleName() + " is required" ); } this.defaultFsm = fsm; this.fsm = new HadoopConfigurationFileSystemManager( this, fsm ); findHadoopConfigurations( baseDir, activeLocator ); this.activeLocator = activeLocator; initialized = true; } /** * Attempt to find any Hadoop configuration as a direct descendant of the provided directory. * * @param baseDir Directory to look for Hadoop configurations in * @throws ConfigurationException */ private void findHadoopConfigurations( FileObject baseDir, ActiveHadoopConfigurationLocator activeLocator ) throws ConfigurationException { configurations = new HashMap<String, HadoopConfiguration>(); try { if ( !baseDir.exists() ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.HadoopConfigurationDirectoryDoesNotExist", baseDir.getURL() ) ); } for ( FileObject f : baseDir.findFiles( new FileSelector() { @Override public boolean includeFile( FileSelectInfo info ) throws Exception { return info.getDepth() == 1 && FileType.FOLDER.equals( info.getFile().getType() ); } @Override public boolean traverseDescendents( FileSelectInfo info ) throws Exception { return info.getDepth() == 0; } } ) ) { // Only load the specified configuration (ID should match the basename, we allow case-insensitivity) if ( f.getName().getBaseName().equalsIgnoreCase( activeLocator.getActiveConfigurationId() ) ) { HadoopConfiguration config = loadHadoopConfiguration( f ); if ( config != null ) { configurations.put( config.getIdentifier(), config ); } } } } catch ( FileSystemException ex ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.UnableToLoadConfigurations", baseDir.getName().getFriendlyURI() ), ex ); } } private List<URL> findJarsIn( FileObject path, final int maxdepth, final Set<String> paths ) throws FileSystemException { FileObject[] jars = path.findFiles( new FileSelector() { @Override public boolean includeFile( FileSelectInfo info ) throws Exception { for ( String path : paths ) { if ( info.getFile().getURL().toString().endsWith( path ) ) { return false; } } return info.getFile().getName().getBaseName().endsWith( JAR_EXTENSION ); } @Override public boolean traverseDescendents( FileSelectInfo info ) throws Exception { for ( String path : paths ) { if ( info.getFile().getURL().toString().endsWith( path ) ) { return false; } } return info.getDepth() <= maxdepth; } } ); List<URL> jarUrls = new ArrayList<URL>(); for ( FileObject jar : jars ) { jarUrls.add( jar.getURL() ); } return jarUrls; } /** * Find all jar files in the path provided. * * @param path Path to search for jar files within * @param maxdepth Maximum traversal depth (1-based) * @return All jars found within {@code path} in at most {@code maxdepth} subdirectories. * @throws FileSystemException */ private void checkInitialized() { if ( !initialized ) { throw new RuntimeException( BaseMessages.getString( PKG, "Error.LocatorNotInitialized" ) ); } } /** * Locates an implementation of {@code service} using the {@link ServiceLoader}. * * @param cl Class loader to look for implementations in * @return The first implementation found. */ protected <T> T locateServiceImpl( ClassLoader cl, Class<T> service ) { ServiceLoader<T> loader = ServiceLoader.load( service, cl ); Iterator<T> iter = loader.iterator(); if ( iter.hasNext() ) { return iter.next(); } return null; } /** * Create a ClassLoader to load resources for a {@code HadoopConfiguration}. * * @param root Configuration root directory * @param parent Parent class loader to delegate to if resources cannot be found in the configuration's * directory or provided classpath * @param classpathUrls Additional URLs to add to the class loader. These will be added before any internal * resources. * @param ignoredClasses Classes (or packages) that should not be loaded by the class loader * @return A class loader capable of loading a Hadoop configuration located at {@code root}. * @throws ConfigurationException Error creating a class loader for the Hadoop configuration located at {@code root} */ protected ClassLoader createConfigurationLoader( FileObject root, ClassLoader parent, List<URL> classpathUrls, ShimProperties configurationProperties, String... ignoredClasses ) throws ConfigurationException { try { if ( root == null || !FileType.FOLDER.equals( root.getType() ) ) { throw new IllegalArgumentException( "root must be a folder: " + root ); } // Find all jar files in the configuration, at most 2 folders deep List<URL> jars = findJarsIn( root, 3, configurationProperties.getConfigSet( SHIM_CLASSPATH_IGNORE ) ); // Add the root of the configuration jars.add( 0, new URL( root.getURL().toExternalForm() + "/" ) ); // Inject any overriding URLs before all other paths if ( classpathUrls != null ) { jars.addAll( 0, classpathUrls ); } return new HadoopConfigurationClassLoader( jars.toArray( EMPTY_URL_ARRAY ), parent, ignoredClasses ); } catch ( Exception ex ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.CreatingClassLoader" ), ex ); } } /** * Parse a set of URLs from a comma-separated list of URLs. If the URL points to a directory all jar files within that * directory will be returned as well. * * @param urlString Comma-separated list of URLs (relative or absolute) * @return List of URLs resolved from {@code urlString} */ protected List<URL> parseURLs( FileObject root, String urlString ) { if ( urlString == null || urlString.trim().isEmpty() ) { return Collections.emptyList(); } String[] paths = urlString.split( "," ); List<URL> urls = new ArrayList<URL>(); for ( String path : paths ) { try { FileObject file = root.resolveFile( path.trim() ); if ( !file.exists() ) { file = defaultFsm.resolveFile( path.trim() ); } if ( FileType.FOLDER.equals( file.getType() ) ) { // Add directories with a trailing / so the URL ClassLoader interprets // them as directories urls.add( new URL( file.getURL().toExternalForm() + "/" ) ); // Also add all jars within this directory urls.addAll( findJarsIn( file, 1, new HashSet<String>() ) ); } else { urls.add( file.getURL() ); } } catch ( Exception e ) { // Log invalid path logger.error( BaseMessages.getString( PKG, "Error.InvalidClasspathEntry", path ) ); } } return urls; } /** * Attempt to discover a valid Hadoop configuration from the provided folder. * * @param folder Folder that may represent a Hadoop configuration * @return A Hadoop configuration for the folder provided or null if none is found. * @throws ConfigurationException Error when loading the Hadoop configuration. */ protected HadoopConfiguration loadHadoopConfiguration( FileObject folder ) throws ConfigurationException { ShimProperties configurationProperties = new ShimProperties(); try { FileObject configFile = folder.getChild( CONFIG_PROPERTIES_FILE ); if ( configFile != null ) { configurationProperties.putAll( loadProperties( configFile ) ); } } catch ( Exception ex ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.UnableToLoadConfigurationProperties", CONFIG_PROPERTIES_FILE ) ); } for ( Entry<String, String> entry : configurationProperties.getPrefixedProperties( "java.system" ).entrySet() ) { System.setProperty( entry.getKey(), entry.getValue() ); } try { // Parse all URLs from an optional classpath from the configuration file List<URL> classpathElements = parseURLs( folder, configurationProperties.getProperty( CONFIG_PROPERTY_CLASSPATH ) ); // Allow external configuration of classes to ignore String ignoredClassesProperty = configurationProperties .getProperty( CONFIG_PROPERTY_IGNORE_CLASSES ); String[] ignoredClasses = null; if ( ignoredClassesProperty != null ) { ignoredClasses = ignoredClassesProperty.split( "," ); } // Pass our class loader in to the configurations' CL as its parent so it // can find the same // API classes we're using ClassLoader cl = createConfigurationLoader( folder, getClass() .getClassLoader(), classpathElements, configurationProperties, ignoredClasses ); verifyClasses( cl, configurationProperties.getProperty( "required.classes" ), configurationProperties.getProperty( "name" ) ); // Treat the Hadoop shim special. It is absolutely required for a Hadoop configuration. HadoopShim hadoopShim = null; List<PentahoHadoopShim> shims = new ArrayList<PentahoHadoopShim>(); // Attempt to locate a shim within this folder for ( Class<? extends PentahoHadoopShim> shimType : SHIM_TYPES ) { PentahoHadoopShim s = locateServiceImpl( cl, shimType ); if ( s == null && shimType.getAnnotation( Required.class ) != null ) { logger.warn( BaseMessages.getString( PKG, "Error.MissingRequiredShim", shimType.getSimpleName() ) ); // Do not continue to load the configuration if we are missing a required shim return null; } if ( HadoopShim.class.isAssignableFrom( shimType ) ) { hadoopShim = (HadoopShim) s; } else { shims.add( s ); } } String id = folder.getName().getBaseName(); String name = configurationProperties.getProperty( CONFIG_PROPERTY_NAME, id ); HadoopConfiguration config = new HadoopConfiguration( configurationProperties, folder, id, name, hadoopShim, shims.toArray( EMPTY_SHIM_ARRAY ) ); // Register native libraries after everything else has been loaded successfully registerNativeLibraryPaths( configurationProperties.getProperty( CONFIG_PROPERTY_LIBRARY_PATH ) ); hadoopShim.onLoad( config, fsm ); return config; } catch ( Throwable t ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.LoadingConfiguration" ), t ); } } protected void verifyClasses( ClassLoader classLoader, String requiredClasses, String shimName ) throws ConfigurationException { if ( !Const.isEmpty( requiredClasses ) ) { for ( String className : requiredClasses.split( "," ) ) { try { classLoader.loadClass( className ); } catch ( Throwable e ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.MissingRequiredClasses", className, shimName ) ); } } } } /** * Register a comma-separated list of native library paths. * * @param paths Comma-separated list of libraries */ protected void registerNativeLibraryPaths( String paths ) { if ( paths == null ) { return; } for ( String path : paths.split( "," ) ) { boolean successful = registerNativeLibraryPath( path ); if ( !successful ) { logger.error( BaseMessages.getString( PKG, "Error.RegisteringLibraryPath", path ) ); } } } /** * Dynamically register a native library path. This relies on a specific implementation detail of ClassLoader: it's * usr_paths property. * * @param path Library path to add * @return {@code true} if the library path could be added successfully */ protected boolean registerNativeLibraryPath( String path ) { if ( path == null ) { throw new NullPointerException(); } path = path.trim(); try { Field f = ClassLoader.class.getDeclaredField( "usr_paths" ); boolean accessible = f.isAccessible(); f.setAccessible( true ); try { String[] paths = (String[]) f.get( null ); // Make sure the path isn't already registered for ( String p : paths ) { if ( p.equals( path ) ) { return true; // Success, it's already there! } } String[] newPaths = new String[ paths.length + 1 ]; System.arraycopy( paths, 0, newPaths, 0, paths.length ); newPaths[ paths.length ] = path; f.set( null, newPaths ); // Success! return true; } finally { f.setAccessible( accessible ); } } catch ( Exception ex ) { // Something went wrong, definitely not successful return false; } } /** * Load the properties file located at {@code file} * * @param file Location of a properties file to load * @return Loaded properties file * @throws IOException Error loading properties from file * @throws FileSystemException Error locating input stream for file */ protected Properties loadProperties( FileObject file ) throws FileSystemException, IOException { Properties p = new Properties(); p.load( file.getContent().getInputStream() ); return p; } @Override public List<HadoopConfiguration> getConfigurations() { checkInitialized(); return new ArrayList<HadoopConfiguration>( configurations.values() ); } @Override public boolean hasConfiguration( String id ) { checkInitialized(); return configurations.containsKey( id ); } @Override public HadoopConfiguration getConfiguration( String id ) throws ConfigurationException { checkInitialized(); HadoopConfiguration config = configurations.get( id ); if ( config == null ) { throw new ConfigurationException( BaseMessages.getString( PKG, "Error.UnknownHadoopConfiguration", id ) ); } return config; } @Override public HadoopConfiguration getActiveConfiguration() throws ConfigurationException { return getConfiguration( activeLocator.getActiveConfigurationId() ); } }
[BAD-531] - Need more detailed message on failing HadoopConfigurationLocator loadHadoopConfiguration method invoke
api/src/org/pentaho/hadoop/shim/HadoopConfigurationLocator.java
[BAD-531] - Need more detailed message on failing HadoopConfigurationLocator loadHadoopConfiguration method invoke
<ide><path>pi/src/org/pentaho/hadoop/shim/HadoopConfigurationLocator.java <ide> * <ide> * Pentaho Big Data <ide> * <del> * Copyright (C) 2002-2015 by Pentaho : http://www.pentaho.com <add> * Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com <ide> * <ide> ******************************************************************************* <ide> * <ide> hadoopShim.onLoad( config, fsm ); <ide> return config; <ide> } catch ( Throwable t ) { <del> throw new ConfigurationException( BaseMessages.getString( PKG, "Error.LoadingConfiguration" ), t ); <add> throw new ConfigurationException( BaseMessages.getString( PKG, "Error.LoadingConfiguration" ) + " " + t.toString(), t ); <ide> } <ide> } <ide>
Java
bsd-2-clause
9335417085a6c257b4dd6801f930a15eac189c35
0
nvdb-vegdata/nvdb-api-client,nvdb-vegdata/nvdb-api-client
package no.vegvesen.nvdbapi.client.model; import java.util.Objects; public class Coordinates { private final Projection projection; private final double lat_easting; private final double long_northing; private Coordinates(Projection projection, double lat_easting, double long_northing) { this.projection = projection; this.lat_easting = lat_easting; this.long_northing = long_northing; } public static Coordinates wgs84(double lat, double lng) { return new Coordinates(Projection.WGS84, lat, lng); } public static Coordinates utm33(double easting, double northing) { return new Coordinates(Projection.UTM33, easting, northing); } public Projection getProjection() { return projection; } public double getLatEasting() { return lat_easting; } public double getLongNorthing() { return long_northing; } @Override public String toString() { return lat_easting + "," + long_northing; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Coordinates that = (Coordinates) o; return Double.compare(that.lat_easting, lat_easting) == 0 && Double.compare(that.long_northing, long_northing) == 0 && Objects.equals(projection, that.projection); } @Override public int hashCode() { return Objects.hash(projection, lat_easting, long_northing); } }
src/main/java/no/vegvesen/nvdbapi/client/model/Coordinates.java
package no.vegvesen.nvdbapi.client.model; import java.util.Objects; public class Coordinates { private final Projection projection; private final double lat_easting; private final double long_northing; private Coordinates(Projection projection, double lat_easting, double long_northing) { this.projection = projection; this.lat_easting = lat_easting; this.long_northing = long_northing; } public static Coordinates wgs84(double lat, double lng) { return new Coordinates(Projection.WGS84, lat, lng); } public static Coordinates utm33(double easting, double northing) { return new Coordinates(Projection.WGS84, easting, northing); } public Projection getProjection() { return projection; } public double getLatEasting() { return lat_easting; } public double getLongNorthing() { return long_northing; } @Override public String toString() { return lat_easting + "," + long_northing; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Coordinates that = (Coordinates) o; return Double.compare(that.lat_easting, lat_easting) == 0 && Double.compare(that.long_northing, long_northing) == 0 && Objects.equals(projection, that.projection); } @Override public int hashCode() { return Objects.hash(projection, lat_easting, long_northing); } }
NVDB-4762: Fix for Coordinates.utm33
src/main/java/no/vegvesen/nvdbapi/client/model/Coordinates.java
NVDB-4762: Fix for Coordinates.utm33
<ide><path>rc/main/java/no/vegvesen/nvdbapi/client/model/Coordinates.java <ide> } <ide> <ide> public static Coordinates utm33(double easting, double northing) { <del> return new Coordinates(Projection.WGS84, easting, northing); <add> return new Coordinates(Projection.UTM33, easting, northing); <ide> } <ide> <ide> public Projection getProjection() {
Java
bsd-2-clause
b28bc1e62b8aad1613783ff9dde20b4b5746ccdf
0
RCRS-ADF/sample,RCRS-ADF/sample
package adf.sample.module.complex; import adf.agent.communication.MessageManager; import adf.agent.communication.standard.bundle.MessageUtil; import adf.agent.communication.standard.bundle.information.*; import adf.agent.develop.DevelopData; import adf.agent.info.AgentInfo; import adf.agent.info.ScenarioInfo; import adf.agent.info.WorldInfo; import adf.agent.module.ModuleManager; import adf.agent.precompute.PrecomputeData; import adf.component.communication.CommunicationMessage; import adf.component.module.algorithm.Clustering; import adf.component.module.algorithm.PathPlanning; import adf.component.module.complex.Search; import rescuecore2.standard.entities.*; import rescuecore2.worldmodel.EntityID; import java.util.*; import static rescuecore2.standard.entities.StandardEntityURN.*; public class SampleSearch extends Search { private PathPlanning pathPlanning; private Clustering clustering; private EntityID result; private Collection<EntityID> unsearchedBuildingIDs; private boolean isSendBuildingMessage; private boolean isSendCivilianMessage; private boolean isSendRoadMessage; private Collection<EntityID> agentPositions; private Map<EntityID, Integer> sentTimeMap; private int receivedEntityInterval; private int sentEntityInterval; public SampleSearch(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { super(ai, wi, si, moduleManager, developData); StandardEntityURN agentURN = ai.me().getStandardURN(); switch (si.getMode()) { case PRECOMPUTATION_PHASE: if(agentURN == AMBULANCE_TEAM) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Ambulance", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Ambulance", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == FIRE_BRIGADE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Fire", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Fire", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == POLICE_FORCE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Police", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Police", "adf.sample.module.algorithm.SampleKMeans"); } break; case PRECOMPUTED: if(agentURN == AMBULANCE_TEAM) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Ambulance", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Ambulance", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == FIRE_BRIGADE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Fire", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Fire", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == POLICE_FORCE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Police", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Police", "adf.sample.module.algorithm.SampleKMeans"); } break; case NON_PRECOMPUTE: if(agentURN == AMBULANCE_TEAM) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Ambulance", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Ambulance", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == FIRE_BRIGADE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Fire", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Fire", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == POLICE_FORCE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Police", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Police", "adf.sample.module.algorithm.SampleKMeans"); } break; } this.unsearchedBuildingIDs = new HashSet<>(); this.isSendBuildingMessage = true; this.isSendCivilianMessage = true; this.isSendRoadMessage = true; this.agentPositions = new HashSet<>(); this.sentTimeMap = new HashMap<>(); this.receivedEntityInterval = developData.getInteger("SampleSearch.receivedEntityInterval", 3); this.sentEntityInterval = developData.getInteger("SampleSearch.sentEntityInterval", 5); } @Override public Search calc() { this.result = null; if(this.pathPlanning == null) { return this; } this.pathPlanning.setFrom(this.agentInfo.getPosition()); this.pathPlanning.setDestination(this.unsearchedBuildingIDs); List<EntityID> path = this.pathPlanning.calc().getResult(); if(path != null && path.size() > 0) { this.result = path.get(path.size() - 1); } return this; } @Override public Search updateInfo(MessageManager messageManager) { super.updateInfo(messageManager); if(this.getCountUpdateInfo() >= 2) { return this; } this.pathPlanning.updateInfo(messageManager); this.clustering.updateInfo(messageManager); this.reflectMessage(messageManager); this.checkSendFlags(); this.sendMessage(messageManager); if(this.unsearchedBuildingIDs.isEmpty()) { this.reset(); } this.unsearchedBuildingIDs.removeAll(this.worldInfo.getChanged().getChangedEntities()); if(this.unsearchedBuildingIDs.isEmpty()) { this.reset(); this.unsearchedBuildingIDs.removeAll(this.worldInfo.getChanged().getChangedEntities()); } return this; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void reset() { this.unsearchedBuildingIDs.clear(); boolean useClustering = true; Collection<StandardEntity> clusterEntities = null; if(this.clustering == null) { useClustering = false; } else { int clusterIndex = this.clustering.getClusterIndex(this.agentInfo.getID()); clusterEntities = this.clustering.getClusterEntities(clusterIndex); if(clusterEntities == null || clusterEntities.isEmpty()) { useClustering = false; } } if(useClustering) { for(StandardEntity entity : clusterEntities) { if(entity instanceof Building && entity.getStandardURN() != REFUGE) { this.unsearchedBuildingIDs.add(entity.getID()); } } } else { this.unsearchedBuildingIDs.addAll(this.worldInfo.getEntityIDsOfType( BUILDING, GAS_STATION, AMBULANCE_CENTRE, FIRE_STATION, POLICE_OFFICE )); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void reflectMessage(MessageManager messageManager) { Set<EntityID> changedEntities = this.worldInfo.getChanged().getChangedEntities(); changedEntities.add(this.agentInfo.getID()); int time = this.agentInfo.getTime(); for(CommunicationMessage message : messageManager.getReceivedMessageList()) { Class<? extends CommunicationMessage> messageClass = message.getClass(); if(messageClass == MessageBuilding.class) { MessageBuilding mb = (MessageBuilding)message; if(!changedEntities.contains(mb.getBuildingID())) { MessageUtil.reflectMessage(this.worldInfo, mb); } this.sentTimeMap.put(mb.getBuildingID(), time + this.receivedEntityInterval); } else if(messageClass == MessageRoad.class) { MessageRoad mr = (MessageRoad)message; if(mr.isBlockadeDefined() && !changedEntities.contains(mr.getBlockadeID())) { MessageUtil.reflectMessage(this.worldInfo, mr); this.sentTimeMap.put(mr.getBlockadeID(), time + this.receivedEntityInterval); } this.sentTimeMap.put(mr.getRoadID(), time + this.receivedEntityInterval); } else if(messageClass == MessageCivilian.class) { MessageCivilian mc = (MessageCivilian) message; if(!changedEntities.contains(mc.getAgentID())){ MessageUtil.reflectMessage(this.worldInfo, mc); } this.sentTimeMap.put(mc.getAgentID(), time + this.receivedEntityInterval); } else if(messageClass == MessageAmbulanceTeam.class) { MessageAmbulanceTeam mat = (MessageAmbulanceTeam)message; if(!changedEntities.contains(mat.getAgentID())) { MessageUtil.reflectMessage(this.worldInfo, mat); } this.sentTimeMap.put(mat.getAgentID(), time + this.receivedEntityInterval); } else if(messageClass == MessageFireBrigade.class) { MessageFireBrigade mfb = (MessageFireBrigade) message; if(!changedEntities.contains(mfb.getAgentID())) { MessageUtil.reflectMessage(this.worldInfo, mfb); } this.sentTimeMap.put(mfb.getAgentID(), time + this.receivedEntityInterval); } else if(messageClass == MessagePoliceForce.class) { MessagePoliceForce mpf = (MessagePoliceForce) message; if(!changedEntities.contains(mpf.getAgentID())) { MessageUtil.reflectMessage(this.worldInfo, mpf); } this.sentTimeMap.put(mpf.getAgentID(), time + this.receivedEntityInterval); } } } private void checkSendFlags(){ this.isSendBuildingMessage = true; this.isSendCivilianMessage = true; this.isSendRoadMessage = true; Human agent = (Human)this.agentInfo.me(); EntityID agentID = agent.getID(); EntityID position = agent.getPosition(); StandardEntityURN agentURN = agent.getStandardURN(); EnumSet<StandardEntityURN> agentTypes = EnumSet.of(AMBULANCE_TEAM, FIRE_BRIGADE, POLICE_FORCE); agentTypes.remove(agentURN); this.agentPositions.clear(); for(StandardEntity entity : this.worldInfo.getEntitiesOfType(agentURN)) { Human other = (Human)entity; if(other.getPosition().getValue() == position.getValue()) { if(other.getID().getValue() > agentID.getValue()) { this.isSendBuildingMessage = false; this.isSendCivilianMessage = false; this.isSendRoadMessage = false; } } this.agentPositions.add(other.getPosition()); } for(StandardEntityURN urn : agentTypes) { for(StandardEntity entity : this.worldInfo.getEntitiesOfType(urn)) { Human other = (Human)entity; if(other.getPosition().getValue() == position.getValue()) { if(urn == AMBULANCE_TEAM) { this.isSendCivilianMessage = false; if(other.getID().getValue() > agentID.getValue()) { if (agentURN == FIRE_BRIGADE) { this.isSendRoadMessage = false; } else if(agentURN == POLICE_FORCE) { this.isSendBuildingMessage = false; } } } else if(urn == FIRE_BRIGADE) { this.isSendBuildingMessage = false; if(other.getID().getValue() > agentID.getValue()) { if (agentURN == AMBULANCE_TEAM) { this.isSendRoadMessage = false; } else if(agentURN == POLICE_FORCE) { this.isSendCivilianMessage = false; } } } else if(urn == POLICE_FORCE) { this.isSendRoadMessage = false; if(other.getID().getValue() > agentID.getValue()) { if (agentURN == AMBULANCE_TEAM) { this.isSendBuildingMessage = false; } else if(agentURN == FIRE_BRIGADE) { this.isSendCivilianMessage = false; } } } } this.agentPositions.add(other.getPosition()); } } } private void sendMessage(MessageManager messageManager) { Building building = null; Civilian civilian = null; Road road = null; int currentTime = this.agentInfo.getTime(); Human agent = (Human) this.agentInfo.me(); for(EntityID id : this.worldInfo.getChanged().getChangedEntities()) { Integer time = this.sentTimeMap.get(id); if(time != null && time > currentTime) { continue; } StandardEntity entity = this.worldInfo.getEntity(id); if(entity instanceof Building && this.isSendBuildingMessage) { Building target = (Building) entity; if(!this.agentPositions.contains(target.getID())) { building = this.selectBuilding(building, target); } else if(target.getID().getValue() == agent.getPosition().getValue()) { building = this.selectBuilding(building, target); } } else if(entity instanceof Road && this.isSendRoadMessage) { Road target = (Road) entity; if(!this.agentPositions.contains(target.getID())) { road = this.selectRoad(road, target); } else if(target.getID().getValue() == agent.getPosition().getValue()) { road = this.selectRoad(road, target); } } else if(entity.getStandardURN() == CIVILIAN && this.isSendCivilianMessage) { Civilian target = (Civilian) entity; if(!this.agentPositions.contains(target.getPosition())) { civilian = this.selectCivilian(civilian, target); } else if(target.getPosition().getValue() == agent.getPosition().getValue()) { civilian = this.selectCivilian(civilian, target); } } else if(entity.getStandardURN() == BLOCKADE && this.isSendRoadMessage) { Blockade blockade = (Blockade) entity; if(blockade.isPositionDefined()) { Road target = (Road) this.worldInfo.getEntity(blockade.getPosition()); if (!this.agentPositions.contains(target.getID())) { road = this.selectRoad(road, target); } else if (target.getID().getValue() == agent.getPosition().getValue()) { road = this.selectRoad(road, target); } } } } if(this.isSendBuildingMessage && building != null) { messageManager.addMessage(new MessageBuilding(true, building)); this.sentTimeMap.put(building.getID(), currentTime + this.sentEntityInterval); } if(this.isSendCivilianMessage && civilian != null) { messageManager.addMessage(new MessageCivilian(true, civilian)); this.sentTimeMap.put(civilian.getID(), currentTime + this.sentEntityInterval); } if(this.isSendRoadMessage && road != null) { if(road.isBlockadesDefined() && road.getBlockades().size() > 0) { Blockade blockade = (Blockade) this.worldInfo.getEntity(road.getBlockades().get(0)); messageManager.addMessage(new MessageRoad(true, road, blockade, false)); this.sentTimeMap.put(road.getID(), currentTime + this.sentEntityInterval); } } } private Building selectBuilding(Building building1, Building building2) { if(building1 != null) { if(building2 != null) { if(building1.isOnFire() && building2.isOnFire()) { if (building1.getFieryness() < building2.getFieryness()) { return building2; } else if (building1.getFieryness() > building2.getFieryness()) { return building1; } if(building1.isTemperatureDefined() && building2.isTemperatureDefined()) { return (building1.getTemperature() < building2.getTemperature()) ? building2 : building1; } } else if (!building1.isOnFire() && building2.isOnFire()) { return building2; } } return building1; } return (building2 != null) ? building2 : null; } private Civilian selectCivilian(Civilian civilian1, Civilian civilian2) { if(this.checkCivilian(civilian1, true)) { if(this.checkCivilian(civilian2, true)) { if(civilian1.getHP() > civilian2.getHP()) { return civilian1; } else if(civilian1.getHP() < civilian2.getHP()) { return civilian2; }else { if(civilian1.isBuriednessDefined()) { if(civilian2.isBuriednessDefined()) { if (civilian1.getBuriedness() < civilian2.getBuriedness()) { return civilian1; } else if (civilian1.getBuriedness() > civilian2.getBuriedness()) { return civilian2; } } else { return civilian1; } } else if(civilian2.isBuriednessDefined()) { return civilian2; } if(civilian1.isDamageDefined()) { if(civilian2.isDamageDefined()) { if(civilian1.getDamage() < civilian2.getDamage()) { return civilian1; } else if(civilian1.getDamage() > civilian2.getDamage()) { return civilian2; } } else { return civilian1; } } else if(civilian2.isDamageDefined()) { return civilian2; } } } return civilian1; } if(this.checkCivilian(civilian2, true)) { return civilian2; } else if(this.checkCivilian(civilian1, false)) { return civilian1; } else if(this.checkCivilian(civilian2, false)) { return civilian2; } return null; } private boolean checkCivilian(Civilian c, boolean checkOtherValues) { if(c != null && c.isHPDefined() && c.isPositionDefined()) { if(checkOtherValues && (!c.isDamageDefined() && !c.isBuriednessDefined())) { return false; } return true; } return false; } private Road selectRoad(Road road1, Road road2) { if(road1 != null && road1.isBlockadesDefined()) { if(road2 != null && road2.isBlockadesDefined()) { if(road1.getID().getValue() == road2.getID().getValue()) { return road1; } int cost1 = this.getRepairCost(road1); int cost2 = this.getRepairCost(road2); if(cost1 > cost2) { return road1; } else if(cost1 < cost2) { return road2; } else { // cost1 == cost2 if((cost1 + cost2) > 0) { if (road1.getNeighbours().size() > road2.getNeighbours().size()) { return road1; } else if (road1.getNeighbours().size() < road2.getNeighbours().size()) { return road2; } } } } if(road1.getBlockades().size() > 0) { return road1; } } if(road2 != null && road2.isBlockadesDefined() && road2.getBlockades().size() > 0) { return road2; } return null; } private int getRepairCost(Road road) { int cost = 0; if(road.isBlockadesDefined()) { for(EntityID id : road.getBlockades()) { Blockade blockade = (Blockade) this.worldInfo.getEntity(id); if(blockade.isRepairCostDefined()) { cost += blockade.getRepairCost(); } } } return cost; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override public EntityID getTarget() { return this.result; } @Override public Search precompute(PrecomputeData precomputeData) { super.precompute(precomputeData); if(this.getCountPrecompute() >= 2) { return this; } this.pathPlanning.precompute(precomputeData); this.clustering.precompute(precomputeData); return this; } @Override public Search resume(PrecomputeData precomputeData) { super.resume(precomputeData); if(this.getCountResume() >= 2) { return this; } this.worldInfo.requestRollback(); this.pathPlanning.resume(precomputeData); this.clustering.resume(precomputeData); return this; } @Override public Search preparate() { super.preparate(); if(this.getCountPreparate() >= 2) { return this; } this.worldInfo.requestRollback(); this.pathPlanning.preparate(); this.clustering.preparate(); return this; } }
src/adf/sample/module/complex/SampleSearch.java
package adf.sample.module.complex; import adf.agent.communication.MessageManager; import adf.agent.communication.standard.bundle.MessageUtil; import adf.agent.communication.standard.bundle.information.*; import adf.agent.develop.DevelopData; import adf.agent.info.AgentInfo; import adf.agent.info.ScenarioInfo; import adf.agent.info.WorldInfo; import adf.agent.module.ModuleManager; import adf.agent.precompute.PrecomputeData; import adf.component.communication.CommunicationMessage; import adf.component.module.algorithm.Clustering; import adf.component.module.algorithm.PathPlanning; import adf.component.module.complex.Search; import rescuecore2.standard.entities.*; import rescuecore2.worldmodel.EntityID; import java.util.*; import static rescuecore2.standard.entities.StandardEntityURN.*; public class SampleSearch extends Search { private PathPlanning pathPlanning; private Clustering clustering; private EntityID result; private Collection<EntityID> unsearchedBuildingIDs; private boolean isSendBuildingMessage; private boolean isSendCivilianMessage; private boolean isSendRoadMessage; private Collection<EntityID> agentPositions; private Map<EntityID, Integer> sentTimeMap; private int receivedEntityInterval; private int sentEntityInterval; public SampleSearch(AgentInfo ai, WorldInfo wi, ScenarioInfo si, ModuleManager moduleManager, DevelopData developData) { super(ai, wi, si, moduleManager, developData); StandardEntityURN agentURN = ai.me().getStandardURN(); switch (si.getMode()) { case PRECOMPUTATION_PHASE: if(agentURN == AMBULANCE_TEAM) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Ambulance", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Ambulance", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == FIRE_BRIGADE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Fire", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Fire", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == POLICE_FORCE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Police", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Police", "adf.sample.module.algorithm.SampleKMeans"); } break; case PRECOMPUTED: if(agentURN == AMBULANCE_TEAM) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Ambulance", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Ambulance", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == FIRE_BRIGADE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Fire", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Fire", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == POLICE_FORCE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Police", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Police", "adf.sample.module.algorithm.SampleKMeans"); } break; case NON_PRECOMPUTE: if(agentURN == AMBULANCE_TEAM) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Ambulance", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Ambulance", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == FIRE_BRIGADE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Fire", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Fire", "adf.sample.module.algorithm.SampleKMeans"); } else if(agentURN == POLICE_FORCE) { this.pathPlanning = moduleManager.getModule("SampleSearch.PathPlanning.Police", "adf.sample.module.algorithm.SamplePathPlanning"); this.clustering = moduleManager.getModule("SampleSearch.Clustering.Police", "adf.sample.module.algorithm.SampleKMeans"); } break; } this.unsearchedBuildingIDs = new HashSet<>(); this.isSendBuildingMessage = true; this.isSendCivilianMessage = true; this.isSendRoadMessage = true; this.agentPositions = new HashSet<>(); this.sentTimeMap = new HashMap<>(); this.receivedEntityInterval = developData.getInteger("SampleSearch.receivedEntityInterval", 3); this.sentEntityInterval = developData.getInteger("SampleSearch.sentEntityInterval", 5); } @Override public Search calc() { this.result = null; if(this.pathPlanning == null) { return this; } this.pathPlanning.setFrom(this.agentInfo.getPosition()); this.pathPlanning.setDestination(this.unsearchedBuildingIDs); List<EntityID> path = this.pathPlanning.calc().getResult(); if(path != null && path.size() > 0) { this.result = path.get(path.size() - 1); } return this; } @Override public Search updateInfo(MessageManager messageManager) { super.updateInfo(messageManager); if(this.getCountUpdateInfo() >= 2) { return this; } this.pathPlanning.updateInfo(messageManager); this.clustering.updateInfo(messageManager); this.reflectMessage(messageManager); this.checkSendFlags(); this.sendMessage(messageManager); if(this.unsearchedBuildingIDs.isEmpty()) { this.reset(); } this.unsearchedBuildingIDs.removeAll(this.worldInfo.getChanged().getChangedEntities()); if(this.unsearchedBuildingIDs.isEmpty()) { this.reset(); this.unsearchedBuildingIDs.removeAll(this.worldInfo.getChanged().getChangedEntities()); } return this; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void reset() { this.unsearchedBuildingIDs.clear(); boolean useClustering = true; Collection<StandardEntity> clusterEntities = null; if(this.clustering == null) { useClustering = false; } else { int clusterIndex = this.clustering.getClusterIndex(this.agentInfo.getID()); clusterEntities = this.clustering.getClusterEntities(clusterIndex); if(clusterEntities == null || clusterEntities.isEmpty()) { useClustering = false; } } if(useClustering) { for(StandardEntity entity : clusterEntities) { if(entity instanceof Building && entity.getStandardURN() != REFUGE) { this.unsearchedBuildingIDs.add(entity.getID()); } } } else { this.unsearchedBuildingIDs.addAll(this.worldInfo.getEntityIDsOfType( BUILDING, GAS_STATION, AMBULANCE_CENTRE, FIRE_STATION, POLICE_OFFICE )); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// private void reflectMessage(MessageManager messageManager) { Set<EntityID> changedEntities = this.worldInfo.getChanged().getChangedEntities(); changedEntities.add(this.agentInfo.getID()); int time = this.agentInfo.getTime(); for(CommunicationMessage message : messageManager.getReceivedMessageList()) { Class<? extends CommunicationMessage> messageClass = message.getClass(); if(messageClass == MessageBuilding.class) { MessageBuilding mb = (MessageBuilding)message; if(!changedEntities.contains(mb.getBuildingID())) { MessageUtil.reflectMessage(this.worldInfo, mb); } this.sentTimeMap.put(mb.getBuildingID(), time + this.receivedEntityInterval); } else if(messageClass == MessageRoad.class) { MessageRoad mr = (MessageRoad)message; if(mr.isBlockadeDefined() && !changedEntities.contains(mr.getBlockadeID())) { MessageUtil.reflectMessage(this.worldInfo, mr); this.sentTimeMap.put(mr.getBlockadeID(), time + this.receivedEntityInterval); } this.sentTimeMap.put(mr.getRoadID(), time + this.receivedEntityInterval); } else if(messageClass == MessageCivilian.class) { MessageCivilian mc = (MessageCivilian) message; if(!changedEntities.contains(mc.getAgentID())){ MessageUtil.reflectMessage(this.worldInfo, mc); } this.sentTimeMap.put(mc.getAgentID(), time + this.receivedEntityInterval); } else if(messageClass == MessageAmbulanceTeam.class) { MessageAmbulanceTeam mat = (MessageAmbulanceTeam)message; if(!changedEntities.contains(mat.getAgentID())) { MessageUtil.reflectMessage(this.worldInfo, mat); } this.sentTimeMap.put(mat.getAgentID(), time + this.receivedEntityInterval); } else if(messageClass == MessageFireBrigade.class) { MessageFireBrigade mfb = (MessageFireBrigade) message; if(!changedEntities.contains(mfb.getAgentID())) { MessageUtil.reflectMessage(this.worldInfo, mfb); } this.sentTimeMap.put(mfb.getAgentID(), time + this.receivedEntityInterval); } else if(messageClass == MessagePoliceForce.class) { MessagePoliceForce mpf = (MessagePoliceForce) message; if(!changedEntities.contains(mpf.getAgentID())) { MessageUtil.reflectMessage(this.worldInfo, mpf); } this.sentTimeMap.put(mpf.getAgentID(), time + this.receivedEntityInterval); } } } private void checkSendFlags(){ this.isSendBuildingMessage = true; this.isSendCivilianMessage = true; this.isSendRoadMessage = true; Human agent = (Human)this.agentInfo.me(); EntityID agentID = agent.getID(); EntityID position = agent.getPosition(); StandardEntityURN agentURN = agent.getStandardURN(); EnumSet<StandardEntityURN> agentTypes = EnumSet.of(AMBULANCE_TEAM, FIRE_BRIGADE, POLICE_FORCE); agentTypes.remove(agentURN); this.agentPositions.clear(); for(StandardEntity entity : this.worldInfo.getEntitiesOfType(agentURN)) { Human other = (Human)entity; if(other.getPosition().getValue() == position.getValue()) { if(other.getID().getValue() > agentID.getValue()) { this.isSendBuildingMessage = false; this.isSendCivilianMessage = false; this.isSendRoadMessage = false; } } this.agentPositions.add(other.getPosition()); } for(StandardEntityURN urn : agentTypes) { for(StandardEntity entity : this.worldInfo.getEntitiesOfType(urn)) { Human other = (Human)entity; if(other.getPosition().getValue() == position.getValue()) { if(urn == AMBULANCE_TEAM) { this.isSendCivilianMessage = false; if(other.getID().getValue() > agentID.getValue()) { if (agentURN == FIRE_BRIGADE) { this.isSendRoadMessage = false; } else if(agentURN == POLICE_FORCE) { this.isSendBuildingMessage = false; } } } else if(urn == FIRE_BRIGADE) { this.isSendBuildingMessage = false; if(other.getID().getValue() > agentID.getValue()) { if (agentURN == AMBULANCE_TEAM) { this.isSendRoadMessage = false; } else if(agentURN == POLICE_FORCE) { this.isSendCivilianMessage = false; } } } else if(urn == POLICE_FORCE) { this.isSendRoadMessage = false; if(other.getID().getValue() > agentID.getValue()) { if (agentURN == AMBULANCE_TEAM) { this.isSendBuildingMessage = false; } else if(agentURN == FIRE_BRIGADE) { this.isSendCivilianMessage = false; } } } } this.agentPositions.add(other.getPosition()); } } } private void sendMessage(MessageManager messageManager) { Building building = null; Civilian civilian = null; Road road = null; int currentTime = this.agentInfo.getTime(); Human agent = (Human) this.agentInfo.me(); for(EntityID id : this.worldInfo.getChanged().getChangedEntities()) { Integer time = this.sentTimeMap.get(id); if(time != null && time > currentTime) { continue; } StandardEntity entity = this.worldInfo.getEntity(id); if(entity instanceof Building && this.isSendBuildingMessage) { Building target = (Building) entity; if(!this.agentPositions.contains(target.getID())) { building = this.selectBuilding(building, target); } else if(target.getID().getValue() == agent.getPosition().getValue()) { building = this.selectBuilding(building, target); } } else if(entity instanceof Road && this.isSendRoadMessage) { Road target = (Road) entity; if(!this.agentPositions.contains(target.getID())) { road = this.selectRoad(road, target); } else if(target.getID().getValue() == agent.getPosition().getValue()) { road = this.selectRoad(road, target); } } else if(entity.getStandardURN() == CIVILIAN && this.isSendCivilianMessage) { Civilian target = (Civilian) entity; if(!this.agentPositions.contains(target.getPosition())) { civilian = this.selectCivilian(civilian, target); } else if(target.getPosition().getValue() == agent.getPosition().getValue()) { civilian = this.selectCivilian(civilian, target); } } else if(entity.getStandardURN() == BLOCKADE && this.isSendRoadMessage) { Blockade blockade = (Blockade) entity; if(blockade.isPositionDefined()) { Road target = (Road) this.worldInfo.getEntity(blockade.getPosition()); if (!this.agentPositions.contains(target.getID())) { road = this.selectRoad(road, target); } else if (target.getID().getValue() == agent.getPosition().getValue()) { road = this.selectRoad(road, target); } } } } if(this.isSendBuildingMessage && building != null) { messageManager.addMessage(new MessageBuilding(true, building)); this.sentTimeMap.put(building.getID(), currentTime + this.sentEntityInterval); } if(this.isSendCivilianMessage && civilian != null) { messageManager.addMessage(new MessageCivilian(true, civilian)); this.sentTimeMap.put(civilian.getID(), currentTime + this.sentEntityInterval); } if(this.isSendRoadMessage && road != null) { if(road.isBlockadesDefined() && road.getBlockades().size() > 0) { Blockade blockade = (Blockade) this.worldInfo.getEntity(road.getBlockades().get(0)); messageManager.addMessage(new MessageRoad(true, road, blockade, false)); this.sentTimeMap.put(road.getID(), currentTime + this.sentEntityInterval); } } } private Building selectBuilding(Building building1, Building building2) { if(building1 != null) { if(building2 != null) { if(building1.isOnFire() && building2.isOnFire()) { if (building1.getFieryness() < building2.getFieryness()) { return building2; } else if (building1.getFieryness() > building2.getFieryness()) { return building1; } if(building1.isTemperatureDefined() && building2.isTemperatureDefined()) { return building1.getTemperature() < building2.getTemperature() ? building2 : building1; } } else if (!building1.isOnFire() && building2.isOnFire()) { return building2; } } return building1; } return building2 != null ? building2 : null; } private Civilian selectCivilian(Civilian civilian1, Civilian civilian2) { if(this.checkCivilian(civilian1, true)) { if(this.checkCivilian(civilian2, true)) { if(civilian1.getHP() > civilian2.getHP()) { return civilian1; } else if(civilian1.getHP() < civilian2.getHP()) { return civilian2; }else { if(civilian1.isBuriednessDefined() && civilian2.isBuriednessDefined()) { if(civilian1.getBuriedness() > 0 && civilian2.getBuriedness() == 0) { return civilian1; }else if(civilian1.getBuriedness() == 0 && civilian2.getBuriedness() > 0) { return civilian2; } else { if (civilian1.getBuriedness() < civilian2.getBuriedness()) { return civilian1; } else if (civilian1.getBuriedness() > civilian2.getBuriedness()) { return civilian2; } } } if(civilian1.isDamageDefined() && civilian2.isDamageDefined()) { if(civilian1.getDamage() < civilian2.getDamage()) { return civilian1; } else if(civilian1.getDamage() > civilian2.getDamage()) { return civilian2; } } } } return civilian1; } if(this.checkCivilian(civilian2, true)) { return civilian2; } else if(this.checkCivilian(civilian1, false)) { return civilian1; } else if(this.checkCivilian(civilian2, false)) { return civilian2; } return null; } private boolean checkCivilian(Civilian c, boolean checkOtherValues) { if(c != null && c.isHPDefined() && c.isPositionDefined()) { if(checkOtherValues && (!c.isDamageDefined() && !c.isBuriednessDefined())) { return false; } return true; } return false; } private Road selectRoad(Road road1, Road road2) { if(road1 != null && road1.isBlockadesDefined()) { if(road2 != null && road2.isBlockadesDefined()) { if(road1.getID().getValue() == road2.getID().getValue()) { return road1; } int cost1 = this.getRepairCost(road1); int cost2 = this.getRepairCost(road2); if(cost1 > cost2) { return road1; } else if(cost1 < cost2) { return road2; } else { if((cost1 + cost2) > 0) { if (road1.getNeighbours().size() > road2.getNeighbours().size()) { return road1; } else if (road1.getNeighbours().size() < road2.getNeighbours().size()) { return road2; } } } } if(road1.getBlockades().size() > 0) { return road1; } } if(road2 != null && road2.isBlockadesDefined() && road2.getBlockades().size() > 0) { return road2; } return null; } private int getRepairCost(Road road) { int cost = 0; if(road.isBlockadesDefined()) { for(EntityID id : road.getBlockades()) { Blockade blockade = (Blockade) this.worldInfo.getEntity(id); if(blockade.isRepairCostDefined()) { cost += blockade.getRepairCost(); } } } return cost; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @Override public EntityID getTarget() { return this.result; } @Override public Search precompute(PrecomputeData precomputeData) { super.precompute(precomputeData); if(this.getCountPrecompute() >= 2) { return this; } this.pathPlanning.precompute(precomputeData); this.clustering.precompute(precomputeData); return this; } @Override public Search resume(PrecomputeData precomputeData) { super.resume(precomputeData); if(this.getCountResume() >= 2) { return this; } this.worldInfo.requestRollback(); this.pathPlanning.resume(precomputeData); this.clustering.resume(precomputeData); return this; } @Override public Search preparate() { super.preparate(); if(this.getCountPreparate() >= 2) { return this; } this.worldInfo.requestRollback(); this.pathPlanning.preparate(); this.clustering.preparate(); return this; } }
update
src/adf/sample/module/complex/SampleSearch.java
update
<ide><path>rc/adf/sample/module/complex/SampleSearch.java <ide> return building1; <ide> } <ide> if(building1.isTemperatureDefined() && building2.isTemperatureDefined()) { <del> return building1.getTemperature() < building2.getTemperature() ? building2 : building1; <add> return (building1.getTemperature() < building2.getTemperature()) ? building2 : building1; <ide> } <ide> } else if (!building1.isOnFire() && building2.isOnFire()) { <ide> return building2; <ide> } <ide> return building1; <ide> } <del> return building2 != null ? building2 : null; <add> return (building2 != null) ? building2 : null; <ide> } <ide> <ide> private Civilian selectCivilian(Civilian civilian1, Civilian civilian2) { <ide> } else if(civilian1.getHP() < civilian2.getHP()) { <ide> return civilian2; <ide> }else { <del> if(civilian1.isBuriednessDefined() && civilian2.isBuriednessDefined()) { <del> if(civilian1.getBuriedness() > 0 && civilian2.getBuriedness() == 0) { <del> return civilian1; <del> }else if(civilian1.getBuriedness() == 0 && civilian2.getBuriedness() > 0) { <del> return civilian2; <del> } else { <add> if(civilian1.isBuriednessDefined()) { <add> if(civilian2.isBuriednessDefined()) { <ide> if (civilian1.getBuriedness() < civilian2.getBuriedness()) { <ide> return civilian1; <ide> } else if (civilian1.getBuriedness() > civilian2.getBuriedness()) { <ide> return civilian2; <ide> } <add> } else { <add> return civilian1; <ide> } <del> } <del> if(civilian1.isDamageDefined() && civilian2.isDamageDefined()) { <del> if(civilian1.getDamage() < civilian2.getDamage()) { <add> } else if(civilian2.isBuriednessDefined()) { <add> return civilian2; <add> } <add> if(civilian1.isDamageDefined()) { <add> if(civilian2.isDamageDefined()) { <add> if(civilian1.getDamage() < civilian2.getDamage()) { <add> return civilian1; <add> } else if(civilian1.getDamage() > civilian2.getDamage()) { <add> return civilian2; <add> } <add> } else { <ide> return civilian1; <del> } else if(civilian1.getDamage() > civilian2.getDamage()) { <del> return civilian2; <ide> } <add> } else if(civilian2.isDamageDefined()) { <add> return civilian2; <ide> } <ide> } <ide> } <ide> return road1; <ide> } else if(cost1 < cost2) { <ide> return road2; <del> } else { <add> } else { // cost1 == cost2 <ide> if((cost1 + cost2) > 0) { <ide> if (road1.getNeighbours().size() > road2.getNeighbours().size()) { <ide> return road1;
JavaScript
mit
5ee031da009df266ea2178917f5922425eaaf7dd
0
alexfernandez/deployment
'use strict'; /** * Deploy a software package. * (C) 2013 Alex Fernández. */ // requires var childProcess = require('child_process'); var util = require('util'); var async = require('async'); var testing = require('testing'); var Log = require('log'); // globals var log = new Log('info'); var originalLog = log; // constants var DEFAULT_TIMEOUT_SECONDS = 60; /** * A deployment of a software package, using the same options as exports.run(). */ var Deployment = function(options, log) { // self-reference var self = this; // init if (options.quiet) { log.level = 'notice'; } if (!options.testDirectory && !options.directory) { log.warning('No directories given; no deployment done'); } /** * Run the deployment. */ self.run = function(callback) { var tasks = []; if (options.testDirectory) { tasks.push(self.updateTestDirectory); tasks.push(getRunnerIn('npm test', options.testDirectory)); } if (options.directory) { tasks.push(self.updateDeploymentDirectory); } if (options.deploymentCommand) { var directory = options.directory || process.cwd(); tasks.push(getRunnerIn(options.deploymentCommand, directory)); } async.waterfall(tasks, callback); }; /** * Update the test directory. */ self.updateTestDirectory = function(callback) { update(options.testDirectory, callback); }; /** * Update the deployment directory. */ self.updateDeploymentDirectory = function(callback) { update(options.directory, callback); }; /** * Update the given directory. */ function update(directory, callback) { log.info('Updating %s', directory); var tasks = []; if (options.detail) { tasks.push(getRunnerIn('git fetch', directory)); tasks.push(getRunnerIn('git log HEAD..@{u} --format=oneline', directory)); tasks.push(getRunnerIn('git diff HEAD..@{u}', directory)); tasks.push(getRunnerIn('git merge @{u}', directory)); } else { tasks.push(getRunnerIn('git pull', directory)); } tasks.push(getRunnerIn('npm install', directory)); async.waterfall(tasks, callback); } /** * Get a function to exec the command in the directory. */ function getRunnerIn(command, directory) { return function(callback) { var params = { cwd: directory, timeout: 1000 * (options.timeout || DEFAULT_TIMEOUT_SECONDS), }; childProcess.exec(command, params, function(error, stdout, stderr) { if (error) { return callback(command + ': ' + stdout + '\n' + error + ', ' + stderr); } log.info(command + ': ' + stdout); if (stderr) { log.error(command + ': ' + stderr); } return callback(null); }); }; } }; /** * Run a test deployment. */ function testDeployment(callback) { var options = { directory: '.', deploymentCommand: 'ls .', }; var deployment = new Deployment(options, new Log('error')); deployment.run(callback); } /** * Run a deployment. Options has these attributes: * - directory: the directory where the package currently resides. * - testDirectory: the directory where the test version of the package resides. * - deploymentCommand: a command to run after a successful deployment, * e.g. "sudo restart myService". * - packageName: the name of the package to show in logs. * - timeout: seconds to wait for all comands, default 60 seconds. * - detail: show full log and diff of code to deploy. * An optional log object is used to send messages. * An optional callback will be called after the deployment finishes. */ exports.run = function(options, log, callback) { if (typeof log == 'function') { callback = log; log = null; } if (!log) { log = originalLog; } var start = Date.now(); if (options.packageName) { log.notice('Starting deployment for %s', options.packageName); } var deployment = new Deployment(options, log); deployment.run(function(error) { var message; var elapsed = Math.round((Date.now() - start) / 10) / 100; if (error) { log.error(error); message = util.format('Error running deployment after %s seconds; finishing', elapsed); if (callback) { return callback(message); } log.error(message); return; } message = util.format('Deployment success! in %s seconds', elapsed); if (callback) { return callback(null, message); } log.notice(message); }); }; /** * Run all tests. */ exports.test = function(callback) { testing.run([ testDeployment, ], 10000, callback); }; // start if invoked directly if (__filename == process.argv[1]) { exports.test(testing.show); }
lib/deployment.js
'use strict'; /** * Deploy a software package. * (C) 2013 Alex Fernández. */ // requires var childProcess = require('child_process'); var util = require('util'); var async = require('async'); var testing = require('testing'); var Log = require('log'); // globals var log = new Log('info'); var originalLog = log; // constants var DEFAULT_TIMEOUT_SECONDS = 60; /** * A deployment of a software package, using the same options as exports.run(). */ var Deployment = function(options, log) { // self-reference var self = this; // init if (options.quiet) { log.level = 'notice'; } if (!options.testDirectory && !options.directory) { log.warning('No directories given; no deployment done'); } /** * Run the deployment. */ self.run = function(callback) { var tasks = []; if (options.testDirectory) { tasks.push(self.updateTestDirectory); tasks.push(getRunnerIn('npm test', options.testDirectory)); } if (options.directory) { tasks.push(self.updateDeploymentDirectory); } if (options.deploymentCommand) { var directory = options.directory || process.cwd(); tasks.push(getRunnerIn(options.deploymentCommand, directory)); } async.waterfall(tasks, callback); }; /** * Update the test directory. */ self.updateTestDirectory = function(callback) { update(options.testDirectory, callback); }; /** * Update the deployment directory. */ self.updateDeploymentDirectory = function(callback) { update(options.directory, callback); }; /** * Update the given directory. */ function update(directory, callback) { log.info('Updating %s', directory); var tasks = []; if (options.detail) { tasks.push(getRunnerIn('git fetch', directory)); tasks.push(getRunnerIn('git log HEAD..@{u} --format=oneline', directory)); tasks.push(getRunnerIn('git diff HEAD..@{u}', directory)); tasks.push(getRunnerIn('git merge', directory)); } else { tasks.push(getRunnerIn('git pull', directory)); } tasks.push(getRunnerIn('npm install', directory)); async.waterfall(tasks, callback); } /** * Get a function to exec the command in the directory. */ function getRunnerIn(command, directory) { return function(callback) { var params = { cwd: directory, timeout: 1000 * (options.timeout || DEFAULT_TIMEOUT_SECONDS), }; childProcess.exec(command, params, function(error, stdout, stderr) { if (error) { return callback(command + ': ' + stdout + '\n' + error + ', ' + stderr); } log.info(command + ': ' + stdout); if (stderr) { log.error(command + ': ' + stderr); } return callback(null); }); }; } }; /** * Run a test deployment. */ function testDeployment(callback) { var options = { directory: '.', deploymentCommand: 'ls .', }; var deployment = new Deployment(options, new Log('error')); deployment.run(callback); } /** * Run a deployment. Options has these attributes: * - directory: the directory where the package currently resides. * - testDirectory: the directory where the test version of the package resides. * - deploymentCommand: a command to run after a successful deployment, * e.g. "sudo restart myService". * - packageName: the name of the package to show in logs. * - timeout: seconds to wait for all comands, default 60 seconds. * - detail: show full log and diff of code to deploy. * An optional log object is used to send messages. * An optional callback will be called after the deployment finishes. */ exports.run = function(options, log, callback) { if (typeof log == 'function') { callback = log; log = null; } if (!log) { log = originalLog; } var start = Date.now(); if (options.packageName) { log.notice('Starting deployment for %s', options.packageName); } var deployment = new Deployment(options, log); deployment.run(function(error) { var message; var elapsed = Math.round((Date.now() - start) / 10) / 100; if (error) { log.error(error); message = util.format('Error running deployment after %s seconds; finishing', elapsed); if (callback) { return callback(message); } log.error(message); return; } message = util.format('Deployment success! in %s seconds', elapsed); if (callback) { return callback(null, message); } log.notice(message); }); }; /** * Run all tests. */ exports.test = function(callback) { testing.run([ testDeployment, ], 10000, callback); }; // start if invoked directly if (__filename == process.argv[1]) { exports.test(testing.show); }
Correct merge for --detail.
lib/deployment.js
Correct merge for --detail.
<ide><path>ib/deployment.js <ide> tasks.push(getRunnerIn('git fetch', directory)); <ide> tasks.push(getRunnerIn('git log HEAD..@{u} --format=oneline', directory)); <ide> tasks.push(getRunnerIn('git diff HEAD..@{u}', directory)); <del> tasks.push(getRunnerIn('git merge', directory)); <add> tasks.push(getRunnerIn('git merge @{u}', directory)); <ide> } <ide> else <ide> {
Java
apache-2.0
48e172fb6cd0a9f086455f1ef758258c711c4395
0
JetBrains/jetpad-mapper,belarusian/jetpad-mapper,timzam/jetpad-mapper
/* * Copyright 2012-2015 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 jetbrains.jetpad.base; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Supplier; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @GwtCompatible public class Asyncs { public static boolean isSucceeded(Async<?> async) { final Value<Boolean> succeeded = new Value<>(false); async.onSuccess(new Handler<Object>() { @Override public void handle(Object item) { succeeded.set(true); } }).remove(); return succeeded.get(); } public static boolean isFinished(Async<?> async) { final Value<Boolean> finished = new Value<>(false); async.onResult(new Handler<Object>() { @Override public void handle(Object item) { finished.set(true); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { finished.set(true); } }).remove(); return finished.get(); } public static <ValueT> Async<ValueT> constant(final ValueT val) { return new Async<ValueT>() { @Override public Registration onSuccess(Handler<? super ValueT> successHandler) { successHandler.handle(val); return Registration.EMPTY; } @Override public Registration onResult(Handler<? super ValueT> successHandler, Handler<Throwable> failureHandler) { return onSuccess(successHandler); } @Override public Registration onFailure(Handler<Throwable> failureHandler) { return Registration.EMPTY; } }; } public static <ValueT> Async<ValueT> failure(final Throwable t) { return new Async<ValueT>() { @Override public Registration onSuccess(Handler<? super ValueT> successHandler) { return Registration.EMPTY; } @Override public Registration onResult(Handler<? super ValueT> successHandler, Handler<Throwable> failureHandler) { return onFailure(failureHandler); } @Override public Registration onFailure(Handler<Throwable> failureHandler) { failureHandler.handle(t); return Registration.EMPTY; } }; } public static <ResultT> Async<Void> toVoid(Async<ResultT> a) { return map(a, new Function<ResultT, Void>() { @Override public Void apply(ResultT input) { return null; } }); } public static <SourceT, TargetT, AsyncResultT extends SourceT> Async<TargetT> map(Async<AsyncResultT> async, final Function<SourceT, TargetT> f) { final SimpleAsync<TargetT> result = new SimpleAsync<>(); async.onResult(new Handler<SourceT>() { @Override public void handle(SourceT item) { try { result.success(f.apply(item)); } catch (Exception e) { result.failure(e); } } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { result.failure(item); } }); return result; } public static <SourceT, TargetT> Async<TargetT> select(Async<SourceT> async, final Function<SourceT, Async<TargetT>> f) { final SimpleAsync<TargetT> result = new SimpleAsync<>(); async.onResult(new Handler<SourceT>() { @Override public void handle(SourceT item) { Async<TargetT> async; try { async = f.apply(item); } catch (Exception e) { result.failure(e); return; } if (async == null) { result.success(null); } else { delegate(async, result); } } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { result.failure(item); } }); return result; } public static <FirstT, SecondT> Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second) { return select(first, new Function<FirstT, Async<SecondT>>() { @Override public Async<SecondT> apply(FirstT input) { return second; } }); } public static Async<Void> parallel(final Async<?>... asyncs) { return parallel(Arrays.asList(asyncs)); } public static Async<Void> parallel(final Collection<? extends Async<?>> asyncs) { return parallel(asyncs, false); } public static Async<Void> parallel(Collection<? extends Async<?>> asyncs, final boolean alwaysSucceed) { final SimpleAsync<Void> result = new SimpleAsync<>(); final Value<Integer> inProgress = new Value<>(asyncs.size()); final List<Throwable> exceptions = new ArrayList<>(); final Runnable checkTermination = new Runnable() { @Override public void run() { if (inProgress.get() == 0) { if (!exceptions.isEmpty() && !alwaysSucceed) { result.failure(new ThrowableCollectionException(exceptions)); } else { result.success(null); } } } }; for (Async<?> a : asyncs) { a.onResult(new Handler<Object>() { @Override public void handle(Object item) { inProgress.set(inProgress.get() - 1); checkTermination.run(); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { exceptions.add(item); inProgress.set(inProgress.get() - 1); checkTermination.run(); } }); } if (asyncs.isEmpty()) { checkTermination.run(); } return result; } public static <ItemT> Async<List<ItemT>> composite(List<Async<ItemT>> asyncs) { final SimpleAsync<List<ItemT>> result = new SimpleAsync<>(); final SortedMap<Integer, ItemT> succeeded = new TreeMap<>(); final List<Throwable> exceptions = new ArrayList<>(0); final Value<Integer> inProgress = new Value<>(asyncs.size()); final Runnable checkTermination = new Runnable() { @Override public void run() { if (inProgress.get() == 0) { if (exceptions.isEmpty()) { result.success(new ArrayList<>(succeeded.values())); } else { if (exceptions.size() == 1) { result.failure(exceptions.get(0)); } else { result.failure(new ThrowableCollectionException(exceptions)); } } } } }; int i = 0; for (Async<ItemT> async : asyncs) { final int counter = i++; async.onResult(new Handler<ItemT>() { @Override public void handle(ItemT item) { succeeded.put(counter, item); inProgress.set(inProgress.get() - 1); checkTermination.run(); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { exceptions.add(item); inProgress.set(inProgress.get() - 1); checkTermination.run(); } }); } if (asyncs.isEmpty()) { checkTermination.run(); } return result; } public static <ResultT> Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s) { final SimpleAsync<ResultT> result = new SimpleAsync<>(); Async<ResultT> async; try { async = s.get(); } catch (Exception e) { result.failure(e); return result; } async.onResult(new Handler<ResultT>() { @Override public void handle(ResultT item) { result.success(item); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { untilSuccess(s).onSuccess(new Handler<ResultT>() { @Override public void handle(ResultT item) { result.success(item); } }); } }); return result; } public static <ValueT> Registration delegate(Async<ValueT> from, final SimpleAsync<ValueT> to) { return from.onResult(new Handler<ValueT>() { @Override public void handle(ValueT item) { to.success(item); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { to.failure(item); } }); } @GwtIncompatible("Uses threading primitives") public static <ResultT> ResultT get(Async<ResultT> async) { return get(async, new Awaiter() { @Override public void await(CountDownLatch latch) throws InterruptedException { latch.await(); } }); } @GwtIncompatible("Uses threading primitives") public static <ResultT> ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit) { return get(async, new Awaiter() { @Override public void await(CountDownLatch latch) throws InterruptedException { if (!latch.await(timeout, timeUnit)) { throw new RuntimeException("timeout " + timeout + " " + timeUnit + " exceeded"); } } }); } @GwtIncompatible("Uses threading primitives") private static <ResultT> ResultT get(Async<ResultT> async, Awaiter awaiter) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<ResultT> result = new AtomicReference<>(null); final AtomicReference<Throwable> error = new AtomicReference<>(null); async.onResult(new Handler<ResultT>() { @Override public void handle(ResultT item) { result.set(item); latch.countDown(); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { error.set(item); latch.countDown(); } }); try { awaiter.await(latch); } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (error.get() == null) { error.set(e); } } if (error.get() != null) { throw new RuntimeException(error.get()); } else { return result.get(); } } @GwtIncompatible("Uses threading primitives") private interface Awaiter { void await(CountDownLatch latch) throws InterruptedException; } }
util/base/src/main/java/jetbrains/jetpad/base/Asyncs.java
/* * Copyright 2012-2015 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 jetbrains.jetpad.base; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Supplier; import java.util.*; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; @GwtCompatible public class Asyncs { public static boolean isSucceeded(Async<?> async) { final Value<Boolean> succeeded = new Value<>(false); async.onSuccess(new Handler<Object>() { @Override public void handle(Object item) { succeeded.set(true); } }).remove(); return succeeded.get(); } public static boolean isFinished(Async<?> async) { final Value<Boolean> finished = new Value<>(false); async.onResult(new Handler<Object>() { @Override public void handle(Object item) { finished.set(true); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { finished.set(true); } }).remove(); return finished.get(); } public static <ValueT> Async<ValueT> constant(final ValueT val) { return new Async<ValueT>() { @Override public Registration onSuccess(Handler<? super ValueT> successHandler) { successHandler.handle(val); return Registration.EMPTY; } @Override public Registration onResult(Handler<? super ValueT> successHandler, Handler<Throwable> failureHandler) { return onSuccess(successHandler); } @Override public Registration onFailure(Handler<Throwable> failureHandler) { return Registration.EMPTY; } }; } public static <ValueT> Async<ValueT> failure(final Throwable t) { return new Async<ValueT>() { @Override public Registration onSuccess(Handler<? super ValueT> successHandler) { return Registration.EMPTY; } @Override public Registration onResult(Handler<? super ValueT> successHandler, Handler<Throwable> failureHandler) { return onFailure(failureHandler); } @Override public Registration onFailure(Handler<Throwable> failureHandler) { failureHandler.handle(t); return Registration.EMPTY; } }; } public static <ResultT> Async<Void> toVoid(Async<ResultT> a) { return map(a, new Function<ResultT, Void>() { @Override public Void apply(ResultT input) { return null; } }); } public static <SourceT, TargetT, AsyncResultT extends SourceT> Async<TargetT> map(Async<AsyncResultT> async, final Function<SourceT, TargetT> f) { final SimpleAsync<TargetT> result = new SimpleAsync<>(); async.onResult(new Handler<SourceT>() { @Override public void handle(SourceT item) { result.success(f.apply(item)); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { result.failure(item); } }); return result; } public static <SourceT, TargetT> Async<TargetT> select(Async<SourceT> async, final Function<SourceT, Async<TargetT>> f) { final SimpleAsync<TargetT> result = new SimpleAsync<>(); async.onResult(new Handler<SourceT>() { @Override public void handle(SourceT item) { Async<TargetT> async = f.apply(item); if (async == null) { result.success(null); } else { delegate(async, result); } } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { result.failure(item); } }); return result; } public static <FirstT, SecondT> Async<SecondT> seq(Async<FirstT> first, final Async<SecondT> second) { return select(first, new Function<FirstT, Async<SecondT>>() { @Override public Async<SecondT> apply(FirstT input) { return second; } }); } public static Async<Void> parallel(final Async<?>... asyncs) { return parallel(Arrays.asList(asyncs)); } public static Async<Void> parallel(final Collection<? extends Async<?>> asyncs) { return parallel(asyncs, false); } public static Async<Void> parallel(Collection<? extends Async<?>> asyncs, final boolean alwaysSucceed) { final SimpleAsync<Void> result = new SimpleAsync<>(); final Value<Integer> inProgress = new Value<>(asyncs.size()); final List<Throwable> exceptions = new ArrayList<>(); final Runnable checkTermination = new Runnable() { @Override public void run() { if (inProgress.get() == 0) { if (!exceptions.isEmpty() && !alwaysSucceed) { result.failure(new ThrowableCollectionException(exceptions)); } else { result.success(null); } } } }; for (Async<?> a : asyncs) { a.onResult(new Handler<Object>() { @Override public void handle(Object item) { inProgress.set(inProgress.get() - 1); checkTermination.run(); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { exceptions.add(item); inProgress.set(inProgress.get() - 1); checkTermination.run(); } }); } if (asyncs.isEmpty()) { checkTermination.run(); } return result; } public static <ItemT> Async<List<ItemT>> composite(List<Async<ItemT>> asyncs) { final SimpleAsync<List<ItemT>> result = new SimpleAsync<>(); final SortedMap<Integer, ItemT> succeeded = new TreeMap<>(); final List<Throwable> exceptions = new ArrayList<>(0); final Value<Integer> inProgress = new Value<>(asyncs.size()); final Runnable checkTermination = new Runnable() { @Override public void run() { if (inProgress.get() == 0) { if (exceptions.isEmpty()) { result.success(new ArrayList<>(succeeded.values())); } else { if (exceptions.size() == 1) { result.failure(exceptions.get(0)); } else { result.failure(new ThrowableCollectionException(exceptions)); } } } } }; int i = 0; for (Async<ItemT> async : asyncs) { final int counter = i++; async.onResult(new Handler<ItemT>() { @Override public void handle(ItemT item) { succeeded.put(counter, item); inProgress.set(inProgress.get() - 1); checkTermination.run(); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { exceptions.add(item); inProgress.set(inProgress.get() - 1); checkTermination.run(); } }); } if (asyncs.isEmpty()) { checkTermination.run(); } return result; } public static <ResultT> Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s) { final SimpleAsync<ResultT> result = new SimpleAsync<>(); Async<ResultT> async = s.get(); async.onResult(new Handler<ResultT>() { @Override public void handle(ResultT item) { result.success(item); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { untilSuccess(s).onSuccess(new Handler<ResultT>() { @Override public void handle(ResultT item) { result.success(item); } }); } }); return result; } public static <ValueT> Registration delegate(Async<ValueT> from, final SimpleAsync<ValueT> to) { return from.onResult(new Handler<ValueT>() { @Override public void handle(ValueT item) { to.success(item); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { to.failure(item); } }); } @GwtIncompatible("Uses threading primitives") public static <ResultT> ResultT get(Async<ResultT> async) { return get(async, new Awaiter() { @Override public void await(CountDownLatch latch) throws InterruptedException { latch.await(); } }); } @GwtIncompatible("Uses threading primitives") public static <ResultT> ResultT get(Async<ResultT> async, final long timeout, final TimeUnit timeUnit) { return get(async, new Awaiter() { @Override public void await(CountDownLatch latch) throws InterruptedException { if (!latch.await(timeout, timeUnit)) { throw new RuntimeException("timeout " + timeout + " " + timeUnit + " exceeded"); } } }); } @GwtIncompatible("Uses threading primitives") private static <ResultT> ResultT get(Async<ResultT> async, Awaiter awaiter) { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<ResultT> result = new AtomicReference<>(null); final AtomicReference<Throwable> error = new AtomicReference<>(null); async.onResult(new Handler<ResultT>() { @Override public void handle(ResultT item) { result.set(item); latch.countDown(); } }, new Handler<Throwable>() { @Override public void handle(Throwable item) { error.set(item); latch.countDown(); } }); try { awaiter.await(latch); } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (error.get() == null) { error.set(e); } } if (error.get() != null) { throw new RuntimeException(error.get()); } else { return result.get(); } } @GwtIncompatible("Uses threading primitives") private interface Awaiter { void await(CountDownLatch latch) throws InterruptedException; } }
Asycs handle exceptions thrown from argument functions
util/base/src/main/java/jetbrains/jetpad/base/Asyncs.java
Asycs handle exceptions thrown from argument functions
<ide><path>til/base/src/main/java/jetbrains/jetpad/base/Asyncs.java <ide> async.onResult(new Handler<SourceT>() { <ide> @Override <ide> public void handle(SourceT item) { <del> result.success(f.apply(item)); <add> try { <add> result.success(f.apply(item)); <add> } catch (Exception e) { <add> result.failure(e); <add> } <ide> } <ide> }, new Handler<Throwable>() { <ide> @Override <ide> async.onResult(new Handler<SourceT>() { <ide> @Override <ide> public void handle(SourceT item) { <del> Async<TargetT> async = f.apply(item); <add> Async<TargetT> async; <add> try { <add> async = f.apply(item); <add> } catch (Exception e) { <add> result.failure(e); <add> return; <add> } <ide> if (async == null) { <ide> result.success(null); <ide> } else { <ide> <ide> public static <ResultT> Async<ResultT> untilSuccess(final Supplier<Async<ResultT>> s) { <ide> final SimpleAsync<ResultT> result = new SimpleAsync<>(); <del> Async<ResultT> async = s.get(); <add> Async<ResultT> async; <add> try { <add> async = s.get(); <add> } catch (Exception e) { <add> result.failure(e); <add> return result; <add> } <add> <ide> async.onResult(new Handler<ResultT>() { <ide> @Override <ide> public void handle(ResultT item) {
Java
apache-2.0
a2233dfc6a03359745385bc38384b60a4cdb2431
0
wcm-io-qa/wcm-io-qa-galenium,wcm-io-qa/wcm-io-qa-galenium,wcm-io-qa/wcm-io-qa-galenium
/* * #%L * wcm.io * %% * Copyright (C) 2020 wcm.io * %% * 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 io.wcm.qa.glnm.junit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.seljup.Arguments; import io.github.bonigarcia.seljup.SeleniumExtension; import io.wcm.qa.glnm.context.GaleniumContext; import io.wcm.qa.glnm.reporting.GaleniumReportUtil; /** * <p>UsesChrome interface.</p> * * @since 5.0.0 */ @ExtendWith(SeleniumExtension.class) public interface UsesChrome { /** * Initializes headless driver. * * @param driver is injected by Selenium Jupiter extension * @since 5.0.0 */ @BeforeEach default void initBrowser(@Arguments("--headless") ChromeDriver driver) { GaleniumContext.getContext().setDriver(driver); } /** * Frees driver to be cleaned up. * * @since 5.0.0 */ @AfterEach default void dropBrowser() { finalScreenshot(); GaleniumContext.getContext().setDriver(null); } /** * Override to change screenshot after test. */ default void finalScreenshot() { GaleniumReportUtil.takeScreenshot(); } }
modules/icing/src/main/java/io/wcm/qa/glnm/junit/UsesChrome.java
/* * #%L * wcm.io * %% * Copyright (C) 2020 wcm.io * %% * 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 io.wcm.qa.glnm.junit; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.openqa.selenium.chrome.ChromeDriver; import io.github.bonigarcia.seljup.Arguments; import io.github.bonigarcia.seljup.SeleniumExtension; import io.wcm.qa.glnm.context.GaleniumContext; /** * <p>UsesChrome interface.</p> * * @since 5.0.0 */ @ExtendWith(SeleniumExtension.class) public interface UsesChrome { /** * Initializes headless driver. * * @param driver is injected by Selenium Jupiter extension * @since 5.0.0 */ @BeforeEach default void initBrowser(@Arguments("--headless") ChromeDriver driver) { GaleniumContext.getContext().setDriver(driver); } /** * Frees driver to be cleaned up. * * @since 5.0.0 */ @AfterEach default void dropBrowser() { GaleniumContext.getContext().setDriver(null); } }
fix(reporting): add screenshot after test to browser interface When doing it from AllureContainerListener the driver was already gone. Behavior can be changed by overriding method in test class or interface.
modules/icing/src/main/java/io/wcm/qa/glnm/junit/UsesChrome.java
fix(reporting): add screenshot after test to browser interface
<ide><path>odules/icing/src/main/java/io/wcm/qa/glnm/junit/UsesChrome.java <ide> import io.github.bonigarcia.seljup.Arguments; <ide> import io.github.bonigarcia.seljup.SeleniumExtension; <ide> import io.wcm.qa.glnm.context.GaleniumContext; <add>import io.wcm.qa.glnm.reporting.GaleniumReportUtil; <ide> <ide> /** <ide> * <p>UsesChrome interface.</p> <ide> */ <ide> @AfterEach <ide> default void dropBrowser() { <add> finalScreenshot(); <ide> GaleniumContext.getContext().setDriver(null); <ide> } <ide> <add> /** <add> * Override to change screenshot after test. <add> */ <add> default void finalScreenshot() { <add> GaleniumReportUtil.takeScreenshot(); <add> } <add> <ide> }
Java
apache-2.0
18a370430c349b5412123badc0ec8eafc4147b16
0
mpujari/ohcount4j,mpujari/ohcount4j,mpujari/ohcount4j,blackducksoftware/ohcount4j,blackducksoftware/ohcount4j,blackducksoftware/ohcount4j,mpujari/ohcount4j,blackducksoftware/ohcount4j,mpujari/ohcount4j,blackducksoftware/ohcount4j,mpujari/ohcount4j
package net.ohloh.ohcount4j; import java.util.ArrayList; import java.util.List; import net.ohloh.ohcount4j.scan.*; public enum Language { /* All languages must be defined here. * * Each language must declare two mandatory properties: * * - The language's official display name (niceName) * - A Scanner subclass capable of parsing this language */ ACTIONSCRIPT("ActionScript", ActionScriptScanner.class), ADA("Ada", AdaScanner.class), ASPX_CSHARP("ASP.NET (C#)", GenericCodeScanner.class), // TODO. ASPX_VB("ASP.NET (VB)", GenericCodeScanner.class), // TODO. ASSEMBLY("Assembly", AssemblyScanner.class), BINARY("Binary", null), // Place holder for binary files. This "Language" will not trigger a scan. BOO("Boo", BooScanner.class), C("C", CStyleScanner.class), COBOL("COBOL", CobolScanner.class), COLDFUSION("ColdFusion", ColdFusionScanner.class), CPP("C++", CStyleScanner.class), CSHARP("C#", CStyleScanner.class), CSS("CSS", CStyleScanner.class), ECMASCRIPT("ECMAScript", CStyleScanner.class), EIFFEL("Eiffel", EiffelScanner.class), ERLANG("Erlang", ErlangScanner.class), FORTRANFIXED("FortranFixed", FortranFixedScanner.class), FORTRANFREE("FortranFree", FortranFreeScanner.class), FSHARP("F#", FSharpScanner.class), GROOVY("Groovy", CStyleScanner.class), HTML("HTML", HTMLScanner.class), HASKELL("Haskell", HaskellScanner.class), JAVA("Java", CStyleScanner.class), JAVASCRIPT("JavaScript", CStyleScanner.class), LIMBO("Limbo", CStyleScanner.class), JSP("JSP", JspScanner.class), LISP("Lisp", LispScanner.class), LUA("Lua", LuaScanner.class), MAKE("Make", MakeScanner.class), MATHEMATICA("Mathematica", MathematicaScanner.class), MATLAB("Matlab", MatlabScanner.class), MODULA2("Modula 2", ModulaScanner.class), MODULA3("Modula 3", ModulaScanner.class), OBJECTIVE_C("Objective-C", CStyleScanner.class), OCAML("OCaml", OCamlScanner.class), OCTAVE("Octave", MatlabScanner.class), // TODO. Octave also supports # comments PASCAL("Pascal", PascalScanner.class), PERL("Perl", PerlScanner.class), PHP("Php", PhpScanner.class), PUPPET("Puppet", GenericCodeScanner.class), // TODO. PVWAVE("IDL/PV-WAVE/GDL", GenericCodeScanner.class), // TODO. PROLOG("Prolog", PrologScanner.class), PYTHON("Python", PythonScanner.class), R("R", GenericCodeScanner.class), // TODO. REBOL("REBOL", RebolScanner.class), REXX("Rexx", RexxScanner.class), RUBY("Ruby", RubyScanner.class), SCHEME("Scheme", SchemeScanner.class), SHELL("Shell", ShellScanner.class), SMALLTALK("Smalltalk", SmalltalkScanner.class), SQL("SQL", SqlScanner.class), TCL("Tcl", TclScanner.class), VB("VisualBasic", VisualBasicScanner.class), VBSCRIPT("VBScript", VisualBasicScanner.class), XML("XML", XmlScanner.class), XMLSCHEMA("XML Schema", XmlScanner.class), XSLT("XSL Transformation", XmlScanner.class); /* Optional properties of languages are declared here. * * At a minimum, a language should define one or more file * extensions or filenames associated with the language. * * You may also declare additional names (beyond the uname * and niceName) by which the language might be known. * These aliases can be matched against things like Emacs * mode headers or shebang directives. */ static { ACTIONSCRIPT.extension("as"); ADA.extensions("ada", "adb"); ASPX_CSHARP.extension("aspx"); ASPX_VB.extension("aspx"); ASSEMBLY.extensions("as8", "asm", "asx", "S", "z80"); BINARY.extension("inc"); BOO.extension("boo"); C.extensions("c", "h"); COBOL.extension("cbl"); COLDFUSION.extensions("cfc", "cfm"); CPP.extensions("C", "c++", "cc", "cpp", "cxx", "H", "h", "h++", "hh", "hpp", "hxx"); CSHARP.aliases("C#", "cs").extension("cs"); CSS.extension("css"); ECMASCRIPT.extension("es"); EIFFEL.extension("e"); ERLANG.extension("erl"); FORTRANFIXED.extensions("f", "for", "ftn", "i", "fpp"); FORTRANFREE.extensions("f90", "f95", "f03", "i90"); FSHARP.extension("fs"); GROOVY.extension("groovy"); HTML.extensions("htm", "html"); HASKELL.extensions("hs", "lhs"); JAVA.extension("java"); JAVASCRIPT.alias("js").extension("js"); JSP.extension("jsp"); LIMBO.extensions("b", "m"); LUA.extension("lua"); MAKE.filename("Makefile").extensions("mk", "pro"); MATHEMATICA.extensions("nb", "nbs"); MODULA2.extensions("mod", "m2"); MODULA3.extensions("m3", "i3"); OBJECTIVE_C.extensions("m", "h"); OCAML.extensions("ml", "mli"); OCTAVE.extensions("m", "octave"); PASCAL.extensions("pas", "pp"); PERL.extensions("pl", "pm"); PHP.extensions("inc", "php", "phtml", "php4", "php3", "php5", "phps"); PVWAVE.extension("pro"); PROLOG.extension("pl"); PUPPET.extension("pp"); PYTHON.extension("py"); R.extension("r"); REBOL.extensions("r", "r3", "reb", "rebol"); REXX.extensions("cmd", "exec", "rexx"); RUBY.alias("jruby").extensions("rb", "ru").filenames("Rakefile", "Gemfile"); SCHEME.extensions("scm", "ss"); SHELL.extensions("bash", "sh"); SMALLTALK.extension("st"); SQL.extension("sql"); TCL.extension("tcl"); VB.extension("vb"); VBSCRIPT.extensions("vbs", "vbe"); XML.extensions("asx", "csproj", "xml", "mxml"); XMLSCHEMA.extension("xsd"); XSLT.extensions("xsl", "xslt"); } private final String niceName; private final Class<? extends Scanner> scannerClass; private List<String> extensions; private List<String> filenames; private List<String> aliases; Language(String niceName, Class<? extends Scanner> scannerClass) { this.niceName = niceName; this.scannerClass = scannerClass; this.extensions = new ArrayList<String>(); this.filenames = new ArrayList<String>(); this.aliases = new ArrayList<String>(); } public String uname() { return this.toString().toLowerCase(); } public String niceName() { return niceName; } public Class<? extends Scanner> scannerClass() { return scannerClass; } public Scanner makeScanner() { try { Scanner scanner = this.scannerClass.newInstance(); scanner.setDefaultLanguage(this); return scanner; } catch (InstantiationException e) { throw new OhcountException(e); } catch (IllegalAccessException e) { throw new OhcountException(e); } } public Language extension(String ext) { extensions.add(ext); return this; } public Language extensions(String... exts) { for (String ext : exts) { extension(ext); } return this; } public List<String> getExtensions() { return extensions; } public Language filename(String filename) { filenames.add(filename); return this; } public Language filenames(String... filenames) { for (String filename : filenames) { filename(filename); } return this; } public List<String> getFilenames() { return filenames; } public Language alias(String alias) { aliases.add(alias); return this; } public Language aliases(String... aliases) { for (String alias : aliases) { alias(alias); } return this; } public List<String> getAliases() { return aliases; } }
src/net/ohloh/ohcount4j/Language.java
package net.ohloh.ohcount4j; import java.util.ArrayList; import java.util.List; import net.ohloh.ohcount4j.scan.*; public enum Language { /* All languages must be defined here. * * Each language must declare two mandatory properties: * * - The language's official display name (niceName) * - A Scanner subclass capable of parsing this language */ ACTIONSCRIPT("ActionScript", ActionScriptScanner.class), ADA("Ada", AdaScanner.class), ASPX_CSHARP("ASP.NET (C#)", GenericCodeScanner.class), // TODO. ASPX_VB("ASP.NET (VB)", GenericCodeScanner.class), // TODO. ASSEMBLY("Assembly", AssemblyScanner.class), BINARY("Binary", null), // Place holder for binary files. This "Language" will not trigger a scan. BOO("Boo", BooScanner.class), C("C", CStyleScanner.class), COBOL("COBOL", CobolScanner.class), COLDFUSION("ColdFusion", ColdFusionScanner.class), CPP("C++", CStyleScanner.class), CSHARP("C#", CStyleScanner.class), CSS("CSS", CStyleScanner.class), ECMASCRIPT("ECMAScript", CStyleScanner.class), EIFFEL("Eiffel", EiffelScanner.class), ERLANG("Erlang", ErlangScanner.class), FORTRANFIXED("FortranFixed", FortranFixedScanner.class), FORTRANFREE("FortranFree", FortranFreeScanner.class), FSHARP("F#", FSharpScanner.class), GROOVY("Groovy", CStyleScanner.class), HTML("HTML", HTMLScanner.class), HASKELL("Haskell", HaskellScanner.class), JAVA("Java", CStyleScanner.class), JAVASCRIPT("JavaScript", CStyleScanner.class), LIMBO("Limbo", CStyleScanner.class), JSP("JSP", JspScanner.class), LISP("Lisp", LispScanner.class), LUA("Lua", LuaScanner.class), MAKE("Make", MakeScanner.class), MATHEMATICA("Mathematica", MathematicaScanner.class), MATLAB("Matlab", MatlabScanner.class), MODULA2("Modula 2", ModulaScanner.class), MODULA3("Modula 3", ModulaScanner.class), OBJECTIVE_C("Objective-C", CStyleScanner.class), OCAML("OCaml", OCamlScanner.class), OCTAVE("Octave", MatlabScanner.class), // TODO. Octave also supports # comments PASCAL("Pascal", PascalScanner.class), PERL("Perl", PerlScanner.class), PHP("Php", PhpScanner.class), PUPPET("Puppet", GenericCodeScanner.class), // TODO. PVWAVE("IDL/PV-WAVE/GDL", GenericCodeScanner.class), // TODO. PROLOG("Prolog", PrologScanner.class), PYTHON("Python", PythonScanner.class), R("R", GenericCodeScanner.class), // TODO. REBOL("REBOL", RebolScanner.class), REXX("Rexx", RexxScanner.class), RUBY("Ruby", RubyScanner.class), SCHEME("Scheme", SchemeScanner.class), SHELL("Shell", ShellScanner.class), SMALLTALK("Smalltalk", SmalltalkScanner.class), SQL("SQL", SqlScanner.class), TCL("Tcl", TclScanner.class), VB("VisualBasic", VisualBasicScanner.class), VBSCRIPT("VBScript", VisualBasicScanner.class), XML("XML", XmlScanner.class), XMLSCHEMA("XmlSchema", XmlScanner.class); /* Optional properties of languages are declared here. * * At a minimum, a language should define one or more file * extensions or filenames associated with the language. * * You may also declare additional names (beyond the uname * and niceName) by which the language might be known. * These aliases can be matched against things like Emacs * mode headers or shebang directives. */ static { ACTIONSCRIPT.extension("as"); ADA.extensions("ada", "adb"); ASPX_CSHARP.extension("aspx"); ASPX_VB.extension("aspx"); ASSEMBLY.extensions("as8", "asm", "asx", "S", "z80"); BINARY.extension("inc"); BOO.extension("boo"); C.extensions("c", "h"); COBOL.extension("cbl"); COLDFUSION.extensions("cfc", "cfm"); CPP.extensions("C", "c++", "cc", "cpp", "cxx", "H", "h", "h++", "hh", "hpp", "hxx"); CSHARP.aliases("C#", "cs").extension("cs"); CSS.extension("css"); ECMASCRIPT.extension("es"); EIFFEL.extension("e"); ERLANG.extension("erl"); FORTRANFIXED.extensions("f", "for", "ftn", "i", "fpp"); FORTRANFREE.extensions("f90", "f95", "f03", "i90"); FSHARP.extension("fs"); GROOVY.extension("groovy"); HTML.extensions("htm", "html"); HASKELL.extensions("hs", "lhs"); JAVA.extension("java"); JAVASCRIPT.alias("js").extension("js"); JSP.extension("jsp"); LIMBO.extensions("b", "m"); LUA.extension("lua"); MAKE.filename("Makefile").extensions("mk", "pro"); MATHEMATICA.extensions("nb", "nbs"); MODULA2.extensions("mod", "m2"); MODULA3.extensions("m3", "i3"); OBJECTIVE_C.extensions("m", "h"); OCAML.extensions("ml", "mli"); OCTAVE.extensions("m", "octave"); PASCAL.extensions("pas", "pp"); PERL.extensions("pl", "pm"); PHP.extensions("inc", "php", "phtml", "php4", "php3", "php5", "phps"); PVWAVE.extension("pro"); PROLOG.extension("pl"); PUPPET.extension("pp"); PYTHON.extension("py"); R.extension("r"); REBOL.extensions("r", "r3", "reb", "rebol"); REXX.extensions("cmd", "exec", "rexx"); RUBY.alias("jruby").extensions("rb", "ru").filenames("Rakefile", "Gemfile"); SCHEME.extensions("scm", "ss"); SHELL.extensions("bash", "sh"); SMALLTALK.extension("st"); SQL.extension("sql"); TCL.extension("tcl"); VB.extension("vb"); VBSCRIPT.extensions("vbs", "vbe"); XML.extensions("asx", "csproj", "xml", "mxml"); XMLSCHEMA.extension("xsd"); } private final String niceName; private final Class<? extends Scanner> scannerClass; private List<String> extensions; private List<String> filenames; private List<String> aliases; Language(String niceName, Class<? extends Scanner> scannerClass) { this.niceName = niceName; this.scannerClass = scannerClass; this.extensions = new ArrayList<String>(); this.filenames = new ArrayList<String>(); this.aliases = new ArrayList<String>(); } public String uname() { return this.toString().toLowerCase(); } public String niceName() { return niceName; } public Class<? extends Scanner> scannerClass() { return scannerClass; } public Scanner makeScanner() { try { Scanner scanner = this.scannerClass.newInstance(); scanner.setDefaultLanguage(this); return scanner; } catch (InstantiationException e) { throw new OhcountException(e); } catch (IllegalAccessException e) { throw new OhcountException(e); } } public Language extension(String ext) { extensions.add(ext); return this; } public Language extensions(String... exts) { for (String ext : exts) { extension(ext); } return this; } public List<String> getExtensions() { return extensions; } public Language filename(String filename) { filenames.add(filename); return this; } public Language filenames(String... filenames) { for (String filename : filenames) { filename(filename); } return this; } public List<String> getFilenames() { return filenames; } public Language alias(String alias) { aliases.add(alias); return this; } public Language aliases(String... aliases) { for (String alias : aliases) { alias(alias); } return this; } public List<String> getAliases() { return aliases; } }
Added XSL Transformation as a Language that uses XMLScanner
src/net/ohloh/ohcount4j/Language.java
Added XSL Transformation as a Language that uses XMLScanner
<ide><path>rc/net/ohloh/ohcount4j/Language.java <ide> VB("VisualBasic", VisualBasicScanner.class), <ide> VBSCRIPT("VBScript", VisualBasicScanner.class), <ide> XML("XML", XmlScanner.class), <del> XMLSCHEMA("XmlSchema", XmlScanner.class); <add> XMLSCHEMA("XML Schema", XmlScanner.class), <add> XSLT("XSL Transformation", XmlScanner.class); <ide> <ide> /* Optional properties of languages are declared here. <ide> * <ide> VBSCRIPT.extensions("vbs", "vbe"); <ide> XML.extensions("asx", "csproj", "xml", "mxml"); <ide> XMLSCHEMA.extension("xsd"); <add> XSLT.extensions("xsl", "xslt"); <ide> } <ide> <ide> private final String niceName;
Java
lgpl-2.1
3cbec03fb7c87e286fdee4019630540c21d7a1e4
0
samskivert/samskivert,samskivert/samskivert
// // $Id: Label.java,v 1.35 2003/12/09 04:07:16 mdb Exp $ // // samskivert library - useful routines for java programs // Copyright (C) 2002 Michael Bayne // // This library 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.1 of the License, or // (at your option) any later version. // // This library 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 library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.font.TextLayout; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.text.AttributedString; import java.text.AttributedCharacterIterator; import java.util.ArrayList; import java.util.HashMap; import javax.swing.SwingConstants; import com.samskivert.Log; import com.samskivert.util.StringUtil; import com.samskivert.util.Tuple; /** * The label is a multipurpose text display mechanism that can display * small amounts of text wrapped to fit into a variety of constrained * spaces. It can be requested to conform to a particular width or height * and will expand into the other dimension in order to accomodate the * text at hand. It is not a component, but is intended for use by * components and other more heavyweight entities. */ public class Label implements SwingConstants, LabelStyleConstants { /** * Constructs a blank label. */ public Label () { this(""); } /** * Constructs a label with the supplied text. */ public Label (String text) { this(text, null, null); } /** * Constructs a label with the supplied text and configuration * parameters. */ public Label (String text, Color textColor, Font font) { this(text, NORMAL, textColor, null, font); } /** * Constructs a label with the supplied text and configuration * parameters. */ public Label ( String text, int style, Color textColor, Color altColor, Font font) { setText(text); setStyle(style); setTextColor(textColor); setAlternateColor(altColor); setFont(font); } /** * Returns the text displayed by this label. */ public String getText () { return _text; } /** * Sets the text to be displayed by this label. This should be * followed eventually by a call to {@link #layout} and ultimately * {@link #render} to render the text. Simply setting the text does * not cause any layout to occur. * * @return true if the text changed as a result of being set, false if * the label was already displaying the requested text. */ public boolean setText (String text) { // the Java text stuff freaks out in a variety of ways if it is // asked to deal with the empty string, so we fake blank labels by // just using a space if (StringUtil.blank(text)) { _text = " "; } else if (!text.equals(_text)) { _text = text; } else { return false; } return true; } /** * Sets the font to be used by this label. If the font is not set, the * current font of the graphics context will be used. */ public void setFont (Font font) { _font = font; } /** * Sets the color used to render the text. Setting the text color to * <code>null</code> will render the label in the graphics context * color (which is the default). */ public void setTextColor (Color color) { _textColor = color; } /** * Instructs the label to render the text with the specified alternate * color when rendering. The text itself will be rendered in whatever * color is currently set in the graphics context, but the outline or * shadow (if any) will always be in the specified color. */ public void setAlternateColor (Color color) { _alternateColor = color; } /** * Returns the alignment of the text within the label. */ public int getAlignment () { return _align; } /** * Sets the alignment of the text within the label to either {@link * SwingConstants#LEFT}, {@link SwingConstants#RIGHT}, or {@link * SwingConstants#CENTER}. The default alignment is selected to be * appropriate for the locale of the text being rendered. */ public void setAlignment (int align) { _align = align; } /** * Sets the style of the text within the label to one of the styles * defined in {@link LabelStyleConstants}. Some styles can be combined * together into a mask, ie. <code>BOLD|UNDERLINE</code>. */ public void setStyle (int style) { _style = style; } /** * Instructs the label to attempt to achieve a balance between width * and height that approximates the golden ratio (width ~1.618 times * height). */ public void setGoldenLayout () { // use -1 as an indicator that we should be golden _constraints.width = -1; _constraints.height = -1; } /** * Sets the target width for this label. Text will be wrapped to fit * into this width, forcibly breaking words on character boundaries if * a single word is too long to fit into the target width. Calling * this method will annul any previously established target height as * we must have one degree of freedom in which to maneuver. */ public void setTargetWidth (int targetWidth) { if (targetWidth <= 0) { throw new IllegalArgumentException( "Invalid target width '" + targetWidth + "'"); } _constraints.width = targetWidth; _constraints.height = 0; } /** * Sets the target height for this label. A simple algorithm will be * used to balance the width of the text in order that there are only * as many lines of text as fit into the target height. If rendering * the label as a single line of text causes it to be taller than the * target height, we simply render ourselves anyway. Calling this * method will annul any previously established target width as we * must have one degree of freedom in which to maneuver. */ public void setTargetHeight (int targetHeight) { if (targetHeight <= 0) { throw new IllegalArgumentException( "Invalid target height '" + targetHeight + "'"); } _constraints.width = 0; _constraints.height = targetHeight; } /** * Clears out previously configured target dimensions for this label. */ public void clearTargetDimens () { _constraints.width = 0; _constraints.height = 0; } /** * Returns the number of lines used by this label. */ public int getLineCount () { return _layouts.length; } /** * Returns our computed dimensions. Only valid after a call to {@link * #layout}. */ public Dimension getSize () { return _size; } /** * Calls {@link #layout(Graphics2D)} with the graphics context for the * given component. */ public void layout (Component comp) { Graphics2D gfx = (Graphics2D)comp.getGraphics(); if (gfx != null) { layout(gfx); gfx.dispose(); } } /** * Requests that this label lay out its text, obtaining information * from the supplied graphics context to do so. It is expected that * the label will be subsequently rendered in the same graphics * context or at least one that is configured very similarly. If not, * wackiness may ensue. */ public void layout (Graphics2D gfx) { FontRenderContext frc = gfx.getFontRenderContext(); ArrayList layouts = null; // if we have a target height, do some processing and convert that // into a target width if (_constraints.height > 0 || _constraints.width == -1) { int targetHeight = _constraints.height; // if we're approximating the golden ratio, target a height // that gets us near that ratio, then we can err on the side // of being a bit wider which is generally nicer than being // taller (for those of us that don't speak verticall written // languages, anyway) if (_constraints.width == -1) { TextLayout layout = new TextLayout(textIterator(gfx), frc); Rectangle2D bounds = layout.getBounds(); int lines = 1; double width = getWidth(bounds)/lines; double height = getHeight(layout)*lines; double delta = Math.abs(width/height - GOLDEN_RATIO); do { width = getWidth(bounds) / (lines+1); double nheight = getHeight(layout) * (lines+1); double ndelta = Math.abs(width/nheight - GOLDEN_RATIO); if (delta <= ndelta) { break; } delta = ndelta; height = nheight; } while (++lines < 200); // cap ourselves at 200 lines targetHeight = (int)Math.ceil(height); } TextLayout layout = new TextLayout(textIterator(gfx), frc); Rectangle2D bounds = layout.getBounds(); int lines = Math.round(targetHeight / getHeight(layout)); if (lines > 1) { int targetWidth = (int)Math.round(getWidth(bounds) / lines); // attempt to lay the text out in the specified width, // incrementing by 10% each time; limit our attempts to 10 // expansions to avoid infinite loops if something is fucked for (int i = 0; i < 10; i++) { LineBreakMeasurer measurer = new LineBreakMeasurer(textIterator(gfx), frc); layouts = computeLines(measurer, targetWidth, _size, true); if ((layouts != null) && (layouts.size() <= lines)) { break; } targetWidth = (int)Math.round(targetWidth * 1.1); } } } else if (_constraints.width > 0) { LineBreakMeasurer measurer = new LineBreakMeasurer(textIterator(gfx), frc); layouts = computeLines(measurer, _constraints.width, _size, false); } // if no constraint, or our constraining height puts us on one line // then layout on one line and call it good if (layouts == null) { TextLayout layout = new TextLayout(textIterator(gfx), frc); Rectangle2D bounds = layout.getBounds(); // for some reason JDK1.3 on Linux chokes on setSize(double,double) _size.setSize(Math.ceil(getWidth(bounds)), Math.ceil(getHeight(layout))); layouts = new ArrayList(); layouts.add(new Tuple(layout, bounds)); } // create our layouts array int lcount = layouts.size(); _layouts = new TextLayout[lcount]; _lbounds = new Rectangle2D[lcount]; _leaders = new float[lcount]; for (int ii = 0; ii < lcount; ii++) { Tuple tup = (Tuple)layouts.get(ii); _layouts[ii] = (TextLayout)tup.left; _lbounds[ii] = (Rectangle2D)tup.right; // account for potential leaders if (_lbounds[ii].getX() < 0) { _leaders[ii] = (float)-_lbounds[ii].getX(); } } } /** * Computes the lines of text for this label given the specified * target width. The overall size of the computed lines is stored into * the <code>size</code> parameter. * * @return an {@link ArrayList} or null if <code>keepWordsWhole</code> * was true and the lines could not be layed out in the target width. */ protected ArrayList computeLines ( LineBreakMeasurer measurer, int targetWidth, Dimension size, boolean keepWordsWhole) { // start with a size of zero double width = 0, height = 0; ArrayList layouts = new ArrayList(); try { // obtain our new dimensions by using a line break iterator to // lay out our text one line at a time TextLayout layout; int lastposition = _text.length(); while (true) { int nextret = _text.indexOf('\n', measurer.getPosition() + 1); if (nextret == -1) { nextret = lastposition; } layout = measurer.nextLayout( targetWidth, nextret, keepWordsWhole); if (layout == null) { break; } Rectangle2D bounds = layout.getBounds(); width = Math.max(width, getWidth(bounds)); height += getHeight(layout); layouts.add(new Tuple(layout, bounds)); } // fill in the computed size; for some reason JDK1.3 on Linux // chokes on setSize(double,double) size.setSize(Math.ceil(width), Math.ceil(height)); // this can only happen if keepWordsWhole is true if (measurer.getPosition() < lastposition) { return null; } } catch (Throwable t) { Log.warning("Label layout failed [text=" + _text + ", t=" + t + "]."); Log.logStackTrace(t); } return layouts; } /** * Renders the layout at the specified position in the supplied * graphics context. */ public void render (Graphics2D gfx, float x, float y) { // nothing to do if we haven't been laid out if (_layouts == null) { Log.warning("Label requested to render prior to a call " + "to layout() [text=" + _text + "]."); return; } Color old = gfx.getColor(); if (_textColor != null) { gfx.setColor(_textColor); } // render our text for (int i = 0; i < _layouts.length; i++) { TextLayout layout = _layouts[i]; Rectangle2D lbounds = _lbounds[i]; y += layout.getAscent(); float extra = (float)Math.floor(_size.width - getWidth(lbounds)); float rx; switch (_align) { case -1: rx = x + (layout.isLeftToRight() ? 0 : extra); break; default: case LEFT: rx = x; break; case RIGHT: rx = x + extra; break; case CENTER: rx = x + extra/2; break; } // shift over any lines that start with a font that extends // into negative x-land rx += _leaders[i]; // System.out.println("line " + i + " x: " + x + " y: " + y + // " rx: " + rx + " width: " + _size.width + // " lx: " + lbounds.getX() + // " lwidth: " + getWidth(lbounds) + // " extra: " + extra); Color textColor; if ((_style & OUTLINE) != 0) { // render the outline using the hacky, but much nicer than // using "real" outlines (via TextLayout.getOutline), method textColor = gfx.getColor(); gfx.setColor(_alternateColor); layout.draw(gfx, rx, y); layout.draw(gfx, rx, y + 1); layout.draw(gfx, rx, y + 2); layout.draw(gfx, rx + 1, y); layout.draw(gfx, rx + 1, y + 2); layout.draw(gfx, rx + 2, y); layout.draw(gfx, rx + 2, y + 1); layout.draw(gfx, rx + 2, y + 2); gfx.setColor(textColor); layout.draw(gfx, rx + 1, y + 1); } else if ((_style & SHADOW) != 0) { textColor = gfx.getColor(); gfx.setColor(_alternateColor); layout.draw(gfx, rx, y + 1); gfx.setColor(textColor); layout.draw(gfx, rx + 1, y); } else if ((_style & BOLD) != 0) { layout.draw(gfx, rx, y); layout.draw(gfx, rx + 1, y); } else { layout.draw(gfx, rx, y); } y += layout.getDescent() + layout.getLeading(); } gfx.setColor(old); } /** * Constructs an attributed character iterator with our text and the * appropriate font. */ protected AttributedCharacterIterator textIterator (Graphics2D gfx) { Font font = (_font == null) ? gfx.getFont() : _font; HashMap map = new HashMap(); map.put(TextAttribute.FONT, font); if ((_style & UNDERLINE) != 0) { map.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL); } AttributedString text = new AttributedString(_text, map); return text.getIterator(); } /** * Computes the total width of a {@link TextLayout} given bounds * returned from a call to {@link TextLayout#getBounds}. */ protected double getWidth (Rectangle2D laybounds) { double width = Math.max(laybounds.getX(), 0) + laybounds.getWidth(); if ((_style & OUTLINE) != 0) { width += 2; } else if ((_style & SHADOW) != 0) { width += 1; } else if ((_style & BOLD) != 0) { width += 1; } return width; } /** * Computes the height based on the leading, ascent and descent rather * than what the layout reports via <code>getBounds()</code> which * rarely seems to have any bearing on reality. */ protected float getHeight (TextLayout layout) { float height = layout.getLeading() + layout.getAscent() + layout.getDescent(); if ((_style & OUTLINE) != 0) { height += 2; } else if ((_style & SHADOW) != 0) { height += 1; } return height; } /** The text of the label. */ protected String _text; /** The text style. */ protected int _style; /** The text alignment. */ protected int _align = -1; // -1 means default according to locale /** Our size constraints in either the x or y direction. */ protected Dimension _constraints = new Dimension(); /** Our calculated size. */ protected Dimension _size = new Dimension(); /** Some fonts (God bless 'em) extend to the left of the position at * which you request that they be rendered. We opt to push such lines * to the right sufficiently that they line up with the rest of the * lines (perhaps not the typographically ideal thing to do, but we're * in computer land and when we say our bounds are (0, 0, width, * height) we damned well better not render outside those bounds, * which these wonderful fonts are choosing to do). */ protected float[] _leaders; /** The font we use when laying out and rendering out text, or null if * we're to use the default font. */ protected Font _font; /** Formatted text layout instances that contain each line of text. */ protected TextLayout[] _layouts; /** Formatted text layout instances that contain each line of text. */ protected Rectangle2D[] _lbounds; /** The color in which to render the text outline or shadow if we're * rendering in outline or shadow mode. */ protected Color _alternateColor = null; /** The color in which to render the text or null if the text should * be rendered with the graphics context color. */ protected Color _textColor = null; /** An approximation of the golden ratio. */ protected static final double GOLDEN_RATIO = 1.618034; }
projects/samskivert/src/java/com/samskivert/swing/Label.java
// // $Id: Label.java,v 1.34 2003/11/15 03:05:15 mdb Exp $ // // samskivert library - useful routines for java programs // Copyright (C) 2002 Michael Bayne // // This library 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.1 of the License, or // (at your option) any later version. // // This library 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 library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA package com.samskivert.swing; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics2D; import java.awt.Shape; import java.awt.font.TextLayout; import java.awt.font.FontRenderContext; import java.awt.font.LineBreakMeasurer; import java.awt.font.TextAttribute; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.text.AttributedString; import java.text.AttributedCharacterIterator; import java.util.ArrayList; import java.util.HashMap; import javax.swing.SwingConstants; import com.samskivert.Log; import com.samskivert.util.StringUtil; import com.samskivert.util.Tuple; /** * The label is a multipurpose text display mechanism that can display * small amounts of text wrapped to fit into a variety of constrained * spaces. It can be requested to conform to a particular width or height * and will expand into the other dimension in order to accomodate the * text at hand. It is not a component, but is intended for use by * components and other more heavyweight entities. */ public class Label implements SwingConstants, LabelStyleConstants { /** * Constructs a blank label. */ public Label () { this(""); } /** * Constructs a label with the supplied text. */ public Label (String text) { this(text, null, null); } /** * Constructs a label with the supplied text and configuration * parameters. */ public Label (String text, Color textColor, Font font) { this(text, NORMAL, textColor, null, font); } /** * Constructs a label with the supplied text and configuration * parameters. */ public Label ( String text, int style, Color textColor, Color altColor, Font font) { setText(text); setStyle(style); setTextColor(textColor); setAlternateColor(altColor); setFont(font); } /** * Returns the text displayed by this label. */ public String getText () { return _text; } /** * Sets the text to be displayed by this label. This should be * followed eventually by a call to {@link #layout} and ultimately * {@link #render} to render the text. Simply setting the text does * not cause any layout to occur. * * @return true if the text changed as a result of being set, false if * the label was already displaying the requested text. */ public boolean setText (String text) { // the Java text stuff freaks out in a variety of ways if it is // asked to deal with the empty string, so we fake blank labels by // just using a space if (StringUtil.blank(text)) { _text = " "; } else if (!text.equals(_text)) { _text = text; } else { return false; } return true; } /** * Sets the font to be used by this label. If the font is not set, the * current font of the graphics context will be used. */ public void setFont (Font font) { _font = font; } /** * Sets the color used to render the text. Setting the text color to * <code>null</code> will render the label in the graphics context * color (which is the default). */ public void setTextColor (Color color) { _textColor = color; } /** * Instructs the label to render the text with the specified alternate * color when rendering. The text itself will be rendered in whatever * color is currently set in the graphics context, but the outline or * shadow (if any) will always be in the specified color. */ public void setAlternateColor (Color color) { _alternateColor = color; } /** * Returns the alignment of the text within the label. */ public int getAlignment () { return _align; } /** * Sets the alignment of the text within the label to either {@link * SwingConstants#LEFT}, {@link SwingConstants#RIGHT}, or {@link * SwingConstants#CENTER}. The default alignment is selected to be * appropriate for the locale of the text being rendered. */ public void setAlignment (int align) { _align = align; } /** * Sets the style of the text within the label to one of the styles * defined in {@link LabelStyleConstants}. Some styles can be combined * together into a mask, ie. <code>BOLD|UNDERLINE</code>. */ public void setStyle (int style) { _style = style; } /** * Instructs the label to attempt to achieve a balance between width * and height that approximates the golden ratio (width ~1.618 times * height). */ public void setGoldenLayout () { // use -1 as an indicator that we should be golden _constraints.width = -1; _constraints.height = -1; } /** * Sets the target width for this label. Text will be wrapped to fit * into this width, forcibly breaking words on character boundaries if * a single word is too long to fit into the target width. Calling * this method will annul any previously established target height as * we must have one degree of freedom in which to maneuver. */ public void setTargetWidth (int targetWidth) { if (targetWidth <= 0) { throw new IllegalArgumentException( "Invalid target width '" + targetWidth + "'"); } _constraints.width = targetWidth; _constraints.height = 0; } /** * Sets the target height for this label. A simple algorithm will be * used to balance the width of the text in order that there are only * as many lines of text as fit into the target height. If rendering * the label as a single line of text causes it to be taller than the * target height, we simply render ourselves anyway. Calling this * method will annul any previously established target width as we * must have one degree of freedom in which to maneuver. */ public void setTargetHeight (int targetHeight) { if (targetHeight <= 0) { throw new IllegalArgumentException( "Invalid target height '" + targetHeight + "'"); } _constraints.width = 0; _constraints.height = targetHeight; } /** * Clears out previously configured target dimensions for this label. */ public void clearTargetDimens () { _constraints.width = 0; _constraints.height = 0; } /** * Returns the number of lines used by this label. */ public int getLineCount () { return _layouts.length; } /** * Returns our computed dimensions. Only valid after a call to {@link * #layout}. */ public Dimension getSize () { return _size; } /** * Calls {@link #layout(Graphics2D)} with the graphics context for the * given component. */ public void layout (Component comp) { Graphics2D gfx = (Graphics2D)comp.getGraphics(); if (gfx != null) { layout(gfx); gfx.dispose(); } } /** * Requests that this label lay out its text, obtaining information * from the supplied graphics context to do so. It is expected that * the label will be subsequently rendered in the same graphics * context or at least one that is configured very similarly. If not, * wackiness may ensue. */ public void layout (Graphics2D gfx) { FontRenderContext frc = gfx.getFontRenderContext(); ArrayList layouts = null; // if we have a target height, do some processing and convert that // into a target width if (_constraints.height > 0 || _constraints.width == -1) { int targetHeight = _constraints.height; // if we're approximating the golden ratio, target a height // that gets us near that ratio, then we can err on the side // of being a bit wider which is generally nicer than being // taller (for those of us that don't speak verticall written // languages, anyway) if (_constraints.width == -1) { TextLayout layout = new TextLayout(textIterator(gfx), frc); Rectangle2D bounds = layout.getBounds(); int lines = 1; double width = getWidth(bounds)/lines; double height = getHeight(layout)*lines; double delta = Math.abs(width/height - GOLDEN_RATIO); do { width = getWidth(bounds) / (lines+1); double nheight = getHeight(layout) * (lines+1); double ndelta = Math.abs(width/nheight - GOLDEN_RATIO); if (delta <= ndelta) { break; } delta = ndelta; height = nheight; } while (++lines < 200); // cap ourselves at 200 lines targetHeight = (int)Math.ceil(height); } TextLayout layout = new TextLayout(textIterator(gfx), frc); Rectangle2D bounds = layout.getBounds(); int lines = Math.round(targetHeight / getHeight(layout)); if (lines > 1) { int targetWidth = (int)Math.round(getWidth(bounds) / lines); // attempt to lay the text out in the specified width, // incrementing by 10% each time; limit our attempts to 10 // expansions to avoid infinite loops if something is fucked for (int i = 0; i < 10; i++) { LineBreakMeasurer measurer = new LineBreakMeasurer(textIterator(gfx), frc); layouts = computeLines(measurer, targetWidth, _size, true); if ((layouts != null) && (layouts.size() <= lines)) { break; } targetWidth = (int)Math.round(targetWidth * 1.1); } } } else if (_constraints.width > 0) { LineBreakMeasurer measurer = new LineBreakMeasurer(textIterator(gfx), frc); layouts = computeLines(measurer, _constraints.width, _size, false); } // if no constraint, or our constraining height puts us on one line // then layout on one line and call it good if (layouts == null) { TextLayout layout = new TextLayout(textIterator(gfx), frc); Rectangle2D bounds = layout.getBounds(); // for some reason JDK1.3 on Linux chokes on setSize(double,double) _size.setSize(Math.ceil(getWidth(bounds)), Math.ceil(getHeight(layout))); layouts = new ArrayList(); layouts.add(new Tuple(layout, bounds)); } // create our layouts array int lcount = layouts.size(); _layouts = new TextLayout[lcount]; _lbounds = new Rectangle2D[lcount]; for (int ii = 0; ii < lcount; ii++) { Tuple tup = (Tuple)layouts.get(ii); _layouts[ii] = (TextLayout)tup.left; _lbounds[ii] = (Rectangle2D)tup.right; } } /** * Computes the lines of text for this label given the specified * target width. The overall size of the computed lines is stored into * the <code>size</code> parameter. * * @return an {@link ArrayList} or null if <code>keepWordsWhole</code> * was true and the lines could not be layed out in the target width. */ protected ArrayList computeLines ( LineBreakMeasurer measurer, int targetWidth, Dimension size, boolean keepWordsWhole) { // start with a size of zero double width = 0, height = 0; ArrayList layouts = new ArrayList(); try { // obtain our new dimensions by using a line break iterator to // lay out our text one line at a time TextLayout layout; int lastposition = _text.length(); while (true) { int nextret = _text.indexOf('\n', measurer.getPosition() + 1); if (nextret == -1) { nextret = lastposition; } layout = measurer.nextLayout( targetWidth, nextret, keepWordsWhole); if (layout == null) { break; } Rectangle2D bounds = layout.getBounds(); width = Math.max(width, getWidth(bounds)); height += getHeight(layout); layouts.add(new Tuple(layout, bounds)); } // fill in the computed size; for some reason JDK1.3 on Linux // chokes on setSize(double,double) size.setSize(Math.ceil(width), Math.ceil(height)); // this can only happen if keepWordsWhole is true if (measurer.getPosition() < lastposition) { return null; } } catch (Throwable t) { Log.warning("Label layout failed [text=" + _text + ", t=" + t + "]."); Log.logStackTrace(t); } return layouts; } /** * Renders the layout at the specified position in the supplied * graphics context. */ public void render (Graphics2D gfx, float x, float y) { // nothing to do if we haven't been laid out if (_layouts == null) { Log.warning("Label requested to render prior to a call " + "to layout() [text=" + _text + "]."); return; } Color old = gfx.getColor(); if (_textColor != null) { gfx.setColor(_textColor); } // render our text for (int i = 0; i < _layouts.length; i++) { TextLayout layout = _layouts[i]; Rectangle2D lbounds = _lbounds[i]; y += layout.getAscent(); float extra = (float)Math.floor(_size.width - getWidth(lbounds)); float rx = x; switch (_align) { case -1: rx = x + (layout.isLeftToRight() ? 0 : extra); break; case LEFT: break; case RIGHT: rx = x + extra; break; case CENTER: rx = x + extra/2; break; } // System.out.println("line " + i + " x: " + x + " y: " + y + // " rx: " + rx + " width: " + _size.width + // " lwidth: " + getWidth(lbounds) + // " extra: " + extra); Color textColor; if ((_style & OUTLINE) != 0) { // render the outline using the hacky, but much nicer than // using "real" outlines (via TextLayout.getOutline), method textColor = gfx.getColor(); gfx.setColor(_alternateColor); layout.draw(gfx, rx, y); layout.draw(gfx, rx, y + 1); layout.draw(gfx, rx, y + 2); layout.draw(gfx, rx + 1, y); layout.draw(gfx, rx + 1, y + 2); layout.draw(gfx, rx + 2, y); layout.draw(gfx, rx + 2, y + 1); layout.draw(gfx, rx + 2, y + 2); gfx.setColor(textColor); layout.draw(gfx, rx + 1, y + 1); } else if ((_style & SHADOW) != 0) { textColor = gfx.getColor(); gfx.setColor(_alternateColor); layout.draw(gfx, rx, y + 1); gfx.setColor(textColor); layout.draw(gfx, rx + 1, y); } else if ((_style & BOLD) != 0) { layout.draw(gfx, rx, y); layout.draw(gfx, rx + 1, y); } else { layout.draw(gfx, rx, y); } y += layout.getDescent() + layout.getLeading(); } gfx.setColor(old); } /** * Constructs an attributed character iterator with our text and the * appropriate font. */ protected AttributedCharacterIterator textIterator (Graphics2D gfx) { Font font = (_font == null) ? gfx.getFont() : _font; HashMap map = new HashMap(); map.put(TextAttribute.FONT, font); if ((_style & UNDERLINE) != 0) { map.put(TextAttribute.UNDERLINE, TextAttribute.UNDERLINE_LOW_ONE_PIXEL); } AttributedString text = new AttributedString(_text, map); return text.getIterator(); } /** * Computes the total width of a {@link TextLayout} given bounds * returned from a call to {@link TextLayout#getBounds}. */ protected double getWidth (Rectangle2D laybounds) { double width = laybounds.getX() + laybounds.getWidth(); if ((_style & OUTLINE) != 0) { width += 2; } else if ((_style & SHADOW) != 0) { width += 1; } else if ((_style & BOLD) != 0) { width += 1; } return width; } /** * Computes the height based on the leading, ascent and descent rather * than what the layout reports via <code>getBounds()</code> which * rarely seems to have any bearing on reality. */ protected float getHeight (TextLayout layout) { float height = layout.getLeading() + layout.getAscent() + layout.getDescent(); if ((_style & OUTLINE) != 0) { height += 2; } else if ((_style & SHADOW) != 0) { height += 1; } return height; } /** The text of the label. */ protected String _text; /** The text style. */ protected int _style; /** The text alignment. */ protected int _align = -1; // -1 means default according to locale /** Our size constraints in either the x or y direction. */ protected Dimension _constraints = new Dimension(); /** Our calculated size. */ protected Dimension _size = new Dimension(); /** The font we use when laying out and rendering out text, or null if * we're to use the default font. */ protected Font _font; /** Formatted text layout instances that contain each line of text. */ protected TextLayout[] _layouts; /** Formatted text layout instances that contain each line of text. */ protected Rectangle2D[] _lbounds; /** The color in which to render the text outline or shadow if we're * rendering in outline or shadow mode. */ protected Color _alternateColor = null; /** The color in which to render the text or null if the text should * be rendered with the graphics context color. */ protected Color _textColor = null; /** An approximation of the golden ratio. */ protected static final double GOLDEN_RATIO = 1.618034; }
Oh the never-ending tragedy of this Sisyphean effort to get text to render within the bounds in which it claims it will render. It appears that some fonts just render into the negative x direction a bit (for characters like J which apparently sassily stick out to the left of every other goddamned character in the alphabet). Now we slap such saucy characters into position, against the will of the God of Typesetting, but appeasing the third commandment of the God of Graphics, namely, "Thou shalt render within your published bounds." git-svn-id: 64ebf368729f38804935acb7146e017e0f909c6b@1335 6335cc39-0255-0410-8fd6-9bcaacd3b74c
projects/samskivert/src/java/com/samskivert/swing/Label.java
Oh the never-ending tragedy of this Sisyphean effort to get text to render within the bounds in which it claims it will render. It appears that some fonts just render into the negative x direction a bit (for characters like J which apparently sassily stick out to the left of every other goddamned character in the alphabet). Now we slap such saucy characters into position, against the will of the God of Typesetting, but appeasing the third commandment of the God of Graphics, namely, "Thou shalt render within your published bounds."
<ide><path>rojects/samskivert/src/java/com/samskivert/swing/Label.java <ide> // <del>// $Id: Label.java,v 1.34 2003/11/15 03:05:15 mdb Exp $ <add>// $Id: Label.java,v 1.35 2003/12/09 04:07:16 mdb Exp $ <ide> // <ide> // samskivert library - useful routines for java programs <ide> // Copyright (C) 2002 Michael Bayne <ide> int lcount = layouts.size(); <ide> _layouts = new TextLayout[lcount]; <ide> _lbounds = new Rectangle2D[lcount]; <add> _leaders = new float[lcount]; <ide> for (int ii = 0; ii < lcount; ii++) { <ide> Tuple tup = (Tuple)layouts.get(ii); <ide> _layouts[ii] = (TextLayout)tup.left; <ide> _lbounds[ii] = (Rectangle2D)tup.right; <add> // account for potential leaders <add> if (_lbounds[ii].getX() < 0) { <add> _leaders[ii] = (float)-_lbounds[ii].getX(); <add> } <ide> } <ide> } <ide> <ide> y += layout.getAscent(); <ide> <ide> float extra = (float)Math.floor(_size.width - getWidth(lbounds)); <del> float rx = x; <add> float rx; <ide> switch (_align) { <ide> case -1: rx = x + (layout.isLeftToRight() ? 0 : extra); break; <del> case LEFT: break; <add> default: <add> case LEFT: rx = x; break; <ide> case RIGHT: rx = x + extra; break; <ide> case CENTER: rx = x + extra/2; break; <ide> } <ide> <add> // shift over any lines that start with a font that extends <add> // into negative x-land <add> rx += _leaders[i]; <add> <ide> // System.out.println("line " + i + " x: " + x + " y: " + y + <ide> // " rx: " + rx + " width: " + _size.width + <add>// " lx: " + lbounds.getX() + <ide> // " lwidth: " + getWidth(lbounds) + <ide> // " extra: " + extra); <ide> <ide> */ <ide> protected double getWidth (Rectangle2D laybounds) <ide> { <del> double width = laybounds.getX() + laybounds.getWidth(); <add> double width = Math.max(laybounds.getX(), 0) + laybounds.getWidth(); <ide> if ((_style & OUTLINE) != 0) { <ide> width += 2; <ide> } else if ((_style & SHADOW) != 0) { <ide> /** Our calculated size. */ <ide> protected Dimension _size = new Dimension(); <ide> <add> /** Some fonts (God bless 'em) extend to the left of the position at <add> * which you request that they be rendered. We opt to push such lines <add> * to the right sufficiently that they line up with the rest of the <add> * lines (perhaps not the typographically ideal thing to do, but we're <add> * in computer land and when we say our bounds are (0, 0, width, <add> * height) we damned well better not render outside those bounds, <add> * which these wonderful fonts are choosing to do). */ <add> protected float[] _leaders; <add> <ide> /** The font we use when laying out and rendering out text, or null if <ide> * we're to use the default font. */ <ide> protected Font _font;
JavaScript
mit
14d3c88095ce662e987d8049c4c05c0fd1daa6ce
0
reactjs/reselect,chromakode/reselect,chentsulin/reselect,rackt/reselect,SpainTrain/reselect,reactjs/reselect,faassen/reselect
function defaultValuesEqual(a, b) { return a === b; } // TODO: Reintroduce comment, slightly rewritten export function defaultMemoize(func, valuesEqual = defaultValuesEqual) { let lastArgs = null; let lastResult = null; return (...args) => { if (lastArgs !== null && args.every((value, index) => valuesEqual(value, lastArgs[index]))) { return lastResult; } lastArgs = args; lastResult = func(...args); return lastResult; }; } export function createSelectorCreator(memoize, ...memoizeOptions) { return (...selectors) => { const memoizedResultFunc = memoize(selectors.pop(), ...memoizeOptions); const dependencies = Array.isArray(selectors[0]) ? selectors[0] : selectors; return (state, props) => { const params = dependencies.map(dependency => dependency(state, props)); return memoizedResultFunc(...params); }; }; } export function createSelector(...args) { return createSelectorCreator(defaultMemoize)(...args); }
src/index.js
function defaultValuesEqual(a, b) { return a === b; } // TODO: Reintroduce comment, slightly rewritten export function defaultMemoize(func, valuesEqual = defaultValuesEqual) { let lastArgs = null; let lastResult = null; return (...args) => { if (lastArgs !== null && args.every((value, index) => valuesEqual(value, lastArgs[index]))) { return lastResult; } lastArgs = args; lastResult = func(...args); return lastResult; }; } export function createSelectorCreator(memoize, ...memoizeOptions) { return (...selectors) => { const memoizedResultFunc = memoize(selectors.pop(), ...memoizeOptions); const dependencies = Array.isArray(selectors[0]) ? selectors[0] : selectors; return (...args) => { const params = dependencies.map(dependency => dependency(...args)); return memoizedResultFunc(...params); }; }; } export function createSelector(...args) { return createSelectorCreator(defaultMemoize)(...args); }
Reverts last commit. It's necessary to have at least two parameters in the returning function definition in order to play nice with `react-redux`'s `connect` function.
src/index.js
Reverts last commit.
<ide><path>rc/index.js <ide> const memoizedResultFunc = memoize(selectors.pop(), ...memoizeOptions); <ide> const dependencies = Array.isArray(selectors[0]) ? <ide> selectors[0] : selectors; <del> return (...args) => { <del> const params = dependencies.map(dependency => dependency(...args)); <add> return (state, props) => { <add> const params = dependencies.map(dependency => dependency(state, props)); <ide> return memoizedResultFunc(...params); <ide> }; <ide> };
Java
apache-2.0
b9bfe560e718d4e7b560822f92bc4f6fc4567397
0
sprater/fcrepo4,barmintor/fcrepo4,nianma/fcrepo4,whikloj/fcrepo4,peichman-umd/fcrepo4,peichman-umd/fcrepo4,yinlinchen/fcrepo4,escowles/fcrepo4,sprater/fcrepo4,ruebot/fcrepo4,yinlinchen/fcrepo4,medusa-project/fcrepo4,ychouloute/fcrepo4,mohideen/fcrepo4,mohideen/fcrepo4,ychouloute/fcrepo4,fcrepo4/fcrepo4,whikloj/fcrepo4,emetsger/fcrepo4,peichman-umd/fcrepo4,awoods/fcrepo4,dbernstein/fcrepo4,robyj/fcrepo4,ruebot/fcrepo4,robyj/fcrepo4,nianma/fcrepo4,barmintor/fcrepo4,bseeger/fcrepo4,emetsger/fcrepo4,dbernstein/fcrepo4,awoods/fcrepo4,lsitu/fcrepo4,bbranan/fcrepo4,escowles/fcrepo4,medusa-project/fcrepo4,ajs6f/fcrepo4,emetsger/fcrepo4,mohideen/fcrepo4,bseeger/fcrepo4,medusa-project/fcrepo4,whikloj/fcrepo4,escowles/fcrepo4,fcrepo4/fcrepo4,bbranan/fcrepo4,yinlinchen/fcrepo4,robyj/fcrepo4,bbranan/fcrepo4,mikedurbin/fcrepo4,sprater/fcrepo4,dbernstein/fcrepo4,ruebot/fcrepo4,mikedurbin/fcrepo4,ychouloute/fcrepo4,ajs6f/fcrepo4,bseeger/fcrepo4,nianma/fcrepo4,awoods/fcrepo4,lsitu/fcrepo4,lsitu/fcrepo4,fcrepo4/fcrepo4,robyj/fcrepo4,whikloj/fcrepo4
package org.fcrepo.generator; import static javax.ws.rs.core.MediaType.TEXT_PLAIN; import static javax.ws.rs.core.MediaType.TEXT_XML; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import javax.inject.Inject; import javax.jcr.NamespaceRegistry; import javax.jcr.RepositoryException; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.apache.any23.extractor.ExtractionContext; import org.apache.any23.writer.TripleHandler; import org.apache.any23.writer.TripleHandlerException; import org.fcrepo.AbstractResource; import org.fcrepo.Datastream; import org.fcrepo.generator.rdf.TripleSource; import org.fcrepo.generator.rdf.TripleSource.Triple; import org.fcrepo.generator.rdf.Utils; import org.fcrepo.services.DatastreamService; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.sail.memory.model.MemValueFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path("/objects/{pid}/datastreams/{dsid}/rdf") @Produces({TEXT_XML, "text/turtle", TEXT_PLAIN}) public class DatastreamRdfGenerator extends AbstractResource { List<TripleSource<Datastream>> dsGenerators; final private static ValueFactory valFactory = new MemValueFactory(); final private Logger logger = LoggerFactory .getLogger(DatastreamRdfGenerator.class); @Inject DatastreamService datastreamService; @GET @Path("/") @Produces({TEXT_XML, "text/turtle", TEXT_PLAIN}) public String getRdfXml(@PathParam("pid") final String pid, @PathParam("dsid") final String dsId, @HeaderParam("Accept") @DefaultValue(TEXT_XML) final String mimeType) throws IOException, RepositoryException, TripleHandlerException { final Datastream ds = datastreamService.getDatastream(pid, dsId); final URI docURI = valFactory.createURI("info:" + pid + "/" + dsId); logger.debug("Using ValueFactory: " + valFactory.toString()); final ExtractionContext context = new ExtractionContext("Fedora Serialization Context", docURI); logger.debug("Using ExtractionContext: " + context.toString()); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { // possible serializations final TripleHandler writer = Utils.selectWriter(mimeType, out); logger.trace("Created RDF Writer: " + writer.getClass().getName()); writer.openContext(context); writer.startDocument(docURI); // add JCR-managed namespaces final NamespaceRegistry nReg = ds.getNode().getSession().getWorkspace() .getNamespaceRegistry(); for (final String prefix : nReg.getPrefixes()) { String nsURI = nReg.getURI(prefix); if ( nsURI != null && !nsURI.equals("") && !prefix.equals("xmlns") ) { writer.receiveNamespace(prefix, nsURI, context); } } // add triples from each TripleSource for (final TripleSource<Datastream> tripleSource : dsGenerators) { logger.trace("Using TripleSource: " + tripleSource.getClass().getName()); for (final Triple t : tripleSource.getTriples(ds, uriInfo)) { writer.receiveTriple(valFactory.createURI(t.subject), valFactory.createURI(t.predicate), valFactory .createLiteral(t.object), null, context); } } writer.endDocument(docURI); writer.close(); logger.debug("Generated RDF: " + out.toString()); return out.toString(); } } public void setDsGenerators(List<TripleSource<Datastream>> dsGenerators) { this.dsGenerators = dsGenerators; } }
fcrepo-generator-rdf/src/main/java/org/fcrepo/generator/DatastreamRdfGenerator.java
package org.fcrepo.generator; import static javax.ws.rs.core.MediaType.TEXT_PLAIN; import static javax.ws.rs.core.MediaType.TEXT_XML; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.List; import javax.inject.Inject; import javax.jcr.NamespaceRegistry; import javax.jcr.RepositoryException; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.HeaderParam; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import org.apache.any23.extractor.ExtractionContext; import org.apache.any23.writer.TripleHandler; import org.apache.any23.writer.TripleHandlerException; import org.fcrepo.AbstractResource; import org.fcrepo.Datastream; import org.fcrepo.generator.rdf.TripleSource; import org.fcrepo.generator.rdf.TripleSource.Triple; import org.fcrepo.generator.rdf.Utils; import org.fcrepo.services.DatastreamService; import org.openrdf.model.URI; import org.openrdf.model.ValueFactory; import org.openrdf.sail.memory.model.MemValueFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @Path("/objects/{pid}/datastreams/{dsid}/rdf") @Produces({TEXT_XML, "text/turtle", TEXT_PLAIN}) public class DatastreamRdfGenerator extends AbstractResource { List<TripleSource<Datastream>> dsGenerators; final private static ValueFactory valFactory = new MemValueFactory(); final private Logger logger = LoggerFactory .getLogger(DatastreamRdfGenerator.class); @Inject DatastreamService datastreamService; @GET @Path("/") @Produces({TEXT_XML, "text/turtle", TEXT_PLAIN}) public String getRdfXml(@PathParam("pid") final String pid, @PathParam("dsid") final String dsId, @HeaderParam("Accept") @DefaultValue(TEXT_XML) final String mimeType) throws IOException, RepositoryException, TripleHandlerException { final Datastream ds = datastreamService.getDatastream(pid, dsId); final URI docURI = valFactory.createURI("info:" + pid + "/" + dsId); logger.debug("Using ValueFactory: " + valFactory.toString()); final ExtractionContext context = new ExtractionContext("Fedora Serialization Context", docURI); logger.debug("Using ExtractionContext: " + context.toString()); try (ByteArrayOutputStream out = new ByteArrayOutputStream()) { // possible serializations final TripleHandler writer = Utils.selectWriter(mimeType, out); logger.trace("Created RDF Writer: " + writer.getClass().getName()); writer.openContext(context); writer.startDocument(docURI); // add JCR-managed namespaces final NamespaceRegistry nReg = ds.getNode().getSession().getWorkspace() .getNamespaceRegistry(); for (final String prefix : nReg.getPrefixes()) { writer.receiveNamespace(prefix, nReg.getURI(prefix), context); } // add triples from each TripleSource for (final TripleSource<Datastream> tripleSource : dsGenerators) { logger.trace("Using TripleSource: " + tripleSource.getClass().getName()); for (final Triple t : tripleSource.getTriples(ds, uriInfo)) { writer.receiveTriple(valFactory.createURI(t.subject), valFactory.createURI(t.predicate), valFactory .createLiteral(t.object), null, context); } } writer.endDocument(docURI); writer.close(); logger.debug("Generated RDF: " + out.toString()); return out.toString(); } } public void setDsGenerators(List<TripleSource<Datastream>> dsGenerators) { this.dsGenerators = dsGenerators; } }
Suppressing invalid namespaces
fcrepo-generator-rdf/src/main/java/org/fcrepo/generator/DatastreamRdfGenerator.java
Suppressing invalid namespaces
<ide><path>crepo-generator-rdf/src/main/java/org/fcrepo/generator/DatastreamRdfGenerator.java <ide> ds.getNode().getSession().getWorkspace() <ide> .getNamespaceRegistry(); <ide> for (final String prefix : nReg.getPrefixes()) { <del> writer.receiveNamespace(prefix, nReg.getURI(prefix), context); <add> String nsURI = nReg.getURI(prefix); <add> if ( nsURI != null && !nsURI.equals("") <add> && !prefix.equals("xmlns") ) { <add> writer.receiveNamespace(prefix, nsURI, context); <add> } <ide> } <ide> <ide> // add triples from each TripleSource
JavaScript
mit
0488492dc166c3c47e2a3e8a4f3f39c0115f6353
0
fczbkk/css-selector-generator,fczbkk/css-selector-generator,fczbkk/css-selector-generator,fczbkk/css-selector-generator
import {assert} from 'chai'; import {getNthOfTypeSelector} from '../src/selector-nth-of-type'; import {getCssSelector} from '../src'; import {constructSelector} from '../src/utilities-selectors.js'; describe('selector - nth-of-type', function () { let root; beforeEach(function () { root = document.body.appendChild(document.createElement('div')); }); afterEach(function () { root.parentNode.removeChild(root); }); it('should generate nth-child selector', function () { root.innerHTML = '<div></div><p></p><p></p>'; const result = getNthOfTypeSelector(root.lastChild); assert.equal(result.length, 1); assert.equal(result[0], 'p:nth-of-type(2)'); }); it('should not include tag if nthoftype is used', function () { const result = constructSelector({ tag: ['div'], nthoftype: ['div:nth-of-type(1)'] }); assert.equal(result, 'div:nth-of-type(1)'); }); it('should not collide with tag selector', function () { root.innerHTML = '<div></div><p></p><p></p>'; const result = getCssSelector(root.lastChild, { selectors: ['tag', 'nthoftype'], root, }); assert.equal(result, 'p:nth-of-type(2)'); }); it('should not collide with `includeTag` option', function () { root.innerHTML = '<div></div><p></p><p></p>'; const result = getCssSelector(root.lastChild, { selectors: ['nthoftype'], includeTag: true, root, }); assert.equal(result, 'p:nth-of-type(2)'); }); it('should not throw for element without parent', function () { const element = document.createElement('div'); const fn = function () { getCssSelector(element, { selectors: ['nthoftype'], root, }); }; assert.doesNotThrow(fn); }); it('should not throw for element directly in document', function () { const element = document.querySelector('html'); const fn = function () { getCssSelector(element, { selectors: ['nthoftype'], root, }); }; assert.doesNotThrow(fn); }); });
test/selector-nth-of-type.spec.js
import {assert} from 'chai'; import {getNthOfTypeSelector} from '../src/selector-nth-of-type'; import {getCssSelector} from '../src'; describe('selector - nth-of-type', function () { let root; beforeEach(function () { root = document.body.appendChild(document.createElement('div')); }); afterEach(function () { root.parentNode.removeChild(root); }); it('should generate nth-child selector', function () { root.innerHTML = '<div></div><p></p><p></p>'; const result = getNthOfTypeSelector(root.lastChild); assert.equal(result.length, 1); assert.equal(result[0], 'p:nth-of-type(2)'); }); it('should not include tag if nthoftype is used', function () { root.innerHTML = ` <ul> <li> <a></a> </li> <li> <a></a> <ul> <li></li> <li></li> </ul> </li> </ul> `; const result = getCssSelector(root.querySelector('a'), { selectors: ['tag', 'nthoftype'], root, }); assert.equal(result, ':nth-child(1) > :nth-child(1) > :nth-child(1)'); }); it('should not collide with tag selector', function () { root.innerHTML = '<div></div><p></p><p></p>'; const result = getCssSelector(root.lastChild, { selectors: ['tag', 'nthoftype'], root, }); assert.equal(result, 'p:nth-of-type(2)'); }); it('should not collide with `includeTag` option', function () { root.innerHTML = '<div></div><p></p><p></p>'; const result = getCssSelector(root.lastChild, { selectors: ['nthoftype'], includeTag: true, root, }); assert.equal(result, 'p:nth-of-type(2)'); }); it('should not throw for element without parent', function () { const element = document.createElement('div'); const fn = function () { getCssSelector(element, { selectors: ['nthoftype'], root, }); }; assert.doesNotThrow(fn); }); it('should not throw for element directly in document', function () { const element = document.querySelector('html'); const fn = function () { getCssSelector(element, { selectors: ['nthoftype'], root, }); }; assert.doesNotThrow(fn); }); });
test: adjust test
test/selector-nth-of-type.spec.js
test: adjust test
<ide><path>est/selector-nth-of-type.spec.js <ide> import {assert} from 'chai'; <ide> import {getNthOfTypeSelector} from '../src/selector-nth-of-type'; <ide> import {getCssSelector} from '../src'; <add>import {constructSelector} from '../src/utilities-selectors.js'; <ide> <ide> describe('selector - nth-of-type', function () { <ide> <ide> }); <ide> <ide> it('should not include tag if nthoftype is used', function () { <del> root.innerHTML = ` <del> <ul> <del> <li> <del> <a></a> <del> </li> <del> <li> <del> <a></a> <del> <ul> <del> <li></li> <del> <li></li> <del> </ul> <del> </li> <del> </ul> <del> `; <del> const result = getCssSelector(root.querySelector('a'), { <del> selectors: ['tag', 'nthoftype'], <del> root, <add> const result = constructSelector({ <add> tag: ['div'], <add> nthoftype: ['div:nth-of-type(1)'] <ide> }); <del> assert.equal(result, ':nth-child(1) > :nth-child(1) > :nth-child(1)'); <add> assert.equal(result, 'div:nth-of-type(1)'); <ide> }); <ide> <ide> it('should not collide with tag selector', function () {
Java
apache-2.0
34f75b0a5d020f8f21d8b53c39d3d584efda047c
0
mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver,mufaddalq/cloudstack-datera-driver
// 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 com.cloud.hypervisor.vmware.resource; import java.io.File; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.URI; import java.nio.channels.SocketChannel; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.concurrent.*; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import javax.inject.Inject; import javax.naming.ConfigurationException; import com.cloud.agent.api.to.DhcpTO; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import com.google.gson.Gson; import com.vmware.vim25.AboutInfo; import com.vmware.vim25.BoolPolicy; import com.vmware.vim25.ClusterDasConfigInfo; import com.vmware.vim25.ComputeResourceSummary; import com.vmware.vim25.DVPortConfigInfo; import com.vmware.vim25.DVPortConfigSpec; import com.vmware.vim25.DatastoreSummary; import com.vmware.vim25.DistributedVirtualPort; import com.vmware.vim25.DistributedVirtualSwitchPortConnection; import com.vmware.vim25.DistributedVirtualSwitchPortCriteria; import com.vmware.vim25.DynamicProperty; import com.vmware.vim25.GuestInfo; import com.vmware.vim25.HostCapability; import com.vmware.vim25.HostFirewallInfo; import com.vmware.vim25.HostFirewallRuleset; import com.vmware.vim25.HostHostBusAdapter; import com.vmware.vim25.HostInternetScsiHba; import com.vmware.vim25.HostInternetScsiHbaAuthenticationProperties; import com.vmware.vim25.HostInternetScsiHbaStaticTarget; import com.vmware.vim25.HostInternetScsiTargetTransport; import com.vmware.vim25.HostScsiDisk; import com.vmware.vim25.HostScsiTopology; import com.vmware.vim25.HostScsiTopologyInterface; import com.vmware.vim25.HostScsiTopologyLun; import com.vmware.vim25.HostScsiTopologyTarget; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.ObjectContent; import com.vmware.vim25.OptionValue; import com.vmware.vim25.PerfCounterInfo; import com.vmware.vim25.PerfEntityMetric; import com.vmware.vim25.PerfEntityMetricBase; import com.vmware.vim25.PerfMetricId; import com.vmware.vim25.PerfMetricIntSeries; import com.vmware.vim25.PerfMetricSeries; import com.vmware.vim25.PerfQuerySpec; import com.vmware.vim25.PerfSampleInfo; import com.vmware.vim25.RuntimeFaultFaultMsg; import com.vmware.vim25.ToolsUnavailableFaultMsg; import com.vmware.vim25.VMwareDVSPortSetting; import com.vmware.vim25.VimPortType; import com.vmware.vim25.VirtualDevice; import com.vmware.vim25.VirtualDeviceBackingInfo; import com.vmware.vim25.VirtualDeviceConfigSpec; import com.vmware.vim25.VirtualDeviceConfigSpecOperation; import com.vmware.vim25.VirtualDisk; import com.vmware.vim25.VirtualEthernetCard; import com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo; import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo; import com.vmware.vim25.VirtualLsiLogicController; import com.vmware.vim25.VirtualMachineConfigSpec; import com.vmware.vim25.VirtualMachineFileInfo; import com.vmware.vim25.VirtualMachineGuestOsIdentifier; import com.vmware.vim25.VirtualMachinePowerState; import com.vmware.vim25.VirtualMachineRelocateSpec; import com.vmware.vim25.VirtualMachineRelocateSpecDiskLocator; import com.vmware.vim25.VirtualMachineRuntimeInfo; import com.vmware.vim25.VirtualSCSISharing; import com.vmware.vim25.VmwareDistributedVirtualSwitchVlanIdSpec; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachVolumeAnswer; import com.cloud.agent.api.AttachVolumeCommand; import com.cloud.agent.api.BackupSnapshotAnswer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.BumpUpPriorityCommand; import com.cloud.agent.api.CheckHealthAnswer; import com.cloud.agent.api.CheckHealthCommand; import com.cloud.agent.api.CheckNetworkAnswer; import com.cloud.agent.api.CheckNetworkCommand; import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; import com.cloud.agent.api.CheckRouterAnswer; import com.cloud.agent.api.CheckRouterCommand; import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; import com.cloud.agent.api.CreateStoragePoolCommand; import com.cloud.agent.api.CreateVMSnapshotAnswer; import com.cloud.agent.api.CreateVMSnapshotCommand; import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.DeleteVMSnapshotAnswer; import com.cloud.agent.api.DeleteVMSnapshotCommand; import com.cloud.agent.api.GetDomRVersionAnswer; import com.cloud.agent.api.GetDomRVersionCmd; import com.cloud.agent.api.GetHostStatsAnswer; import com.cloud.agent.api.GetHostStatsCommand; import com.cloud.agent.api.GetStorageStatsAnswer; import com.cloud.agent.api.GetStorageStatsCommand; import com.cloud.agent.api.GetVmStatsAnswer; import com.cloud.agent.api.GetVmStatsCommand; import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortCommand; import com.cloud.agent.api.HostStatsEntry; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; import com.cloud.agent.api.ManageSnapshotAnswer; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.MigrateWithStorageAnswer; import com.cloud.agent.api.MigrateWithStorageCommand; import com.cloud.agent.api.ModifySshKeysCommand; import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.NetworkUsageAnswer; import com.cloud.agent.api.NetworkUsageCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingTestCommand; import com.cloud.agent.api.PlugNicAnswer; import com.cloud.agent.api.PlugNicCommand; import com.cloud.agent.api.PoolEjectCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.PvlanSetupCommand; import com.cloud.agent.api.ReadyAnswer; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootRouterCommand; import com.cloud.agent.api.RevertToVMSnapshotAnswer; import com.cloud.agent.api.RevertToVMSnapshotCommand; import com.cloud.agent.api.ScaleVmAnswer; import com.cloud.agent.api.ScaleVmCommand; import com.cloud.agent.api.SetupAnswer; import com.cloud.agent.api.SetupCommand; import com.cloud.agent.api.SetupGuestNetworkAnswer; import com.cloud.agent.api.SetupGuestNetworkCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupStorageCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.StoragePoolInfo; import com.cloud.agent.api.UnPlugNicAnswer; import com.cloud.agent.api.UnPlugNicCommand; import com.cloud.agent.api.UnregisterNicCommand; import com.cloud.agent.api.UnregisterVMCommand; import com.cloud.agent.api.UpgradeSnapshotCommand; import com.cloud.agent.api.ValidateSnapshotAnswer; import com.cloud.agent.api.ValidateSnapshotCommand; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.check.CheckSshAnswer; import com.cloud.agent.api.check.CheckSshCommand; import com.cloud.agent.api.routing.CreateIpAliasCommand; import com.cloud.agent.api.routing.DeleteIpAliasCommand; import com.cloud.agent.api.routing.DhcpEntryCommand; import com.cloud.agent.api.routing.DnsMasqConfigCommand; import com.cloud.agent.api.routing.IpAliasTO; import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.IpAssocVpcCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; import com.cloud.agent.api.routing.SavePasswordCommand; import com.cloud.agent.api.routing.SetFirewallRulesAnswer; import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetNetworkACLAnswer; import com.cloud.agent.api.routing.SetNetworkACLCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand; import com.cloud.agent.api.routing.SetSourceNatAnswer; import com.cloud.agent.api.routing.SetSourceNatCommand; import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.SetStaticRouteAnswer; import com.cloud.agent.api.routing.SetStaticRouteCommand; import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand; import com.cloud.agent.api.routing.VmDataCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; import com.cloud.agent.api.storage.CreateCommand; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.CreateVolumeOVAAnswer; import com.cloud.agent.api.storage.CreateVolumeOVACommand; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.MigrateVolumeAnswer; import com.cloud.agent.api.storage.MigrateVolumeCommand; import com.cloud.agent.api.storage.PrepareOVAPackingAnswer; import com.cloud.agent.api.storage.PrepareOVAPackingCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.storage.ResizeVolumeAnswer; import com.cloud.agent.api.storage.ResizeVolumeCommand; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DiskTO; import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.Vlan; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.vmware.manager.VmwareHostService; import com.cloud.hypervisor.vmware.manager.VmwareManager; import com.cloud.hypervisor.vmware.manager.VmwareStorageMount; import com.cloud.hypervisor.vmware.mo.ClusterMO; import com.cloud.hypervisor.vmware.mo.CustomFieldConstants; import com.cloud.hypervisor.vmware.mo.CustomFieldsManagerMO; import com.cloud.hypervisor.vmware.mo.DatacenterMO; import com.cloud.hypervisor.vmware.mo.DatastoreMO; import com.cloud.hypervisor.vmware.mo.DiskControllerType; import com.cloud.hypervisor.vmware.mo.FeatureKeyConstants; import com.cloud.hypervisor.vmware.mo.HostDatastoreSystemMO; import com.cloud.hypervisor.vmware.mo.HostFirewallSystemMO; import com.cloud.hypervisor.vmware.mo.HostMO; import com.cloud.hypervisor.vmware.mo.HostStorageSystemMO; import com.cloud.hypervisor.vmware.mo.HypervisorHostHelper; import com.cloud.hypervisor.vmware.mo.NetworkDetails; import com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType; import com.cloud.hypervisor.vmware.mo.VirtualMachineMO; import com.cloud.hypervisor.vmware.mo.VirtualSwitchType; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostNetworkSummary; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostResourceSummary; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareGuestOsMapper; import com.cloud.hypervisor.vmware.util.VmwareHelper; import com.cloud.network.HAProxyConfigurator; import com.cloud.network.LoadBalancerConfigurator; import com.cloud.network.Networks; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.VmwareTrafficLabel; import com.cloud.network.rules.FirewallRule; import com.cloud.resource.ServerResource; import com.cloud.serializer.GsonHelper; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Volume; import com.cloud.storage.VolumeManager; import com.cloud.storage.VolumeManagerImpl; import com.cloud.storage.resource.StoragePoolResource; import com.cloud.storage.resource.StorageSubsystemCommandHandler; import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase; import com.cloud.storage.resource.VmwareStorageProcessor; import com.cloud.storage.template.TemplateProp; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExceptionUtil; import com.cloud.utils.mgmt.JmxUtil; import com.cloud.utils.mgmt.PropertyMapDynamicBean; import com.cloud.utils.net.NetUtils; import com.cloud.utils.ssh.SshHelper; import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineName; import com.cloud.vm.VmDetailConstants; import org.apache.cloudstack.storage.command.DeleteCommand; import org.apache.cloudstack.storage.command.StorageSubSystemCommand; import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; public class VmwareResource implements StoragePoolResource, ServerResource, VmwareHostService { private static final Logger s_logger = Logger.getLogger(VmwareResource.class); protected String _name; protected final long _ops_timeout = 900000; // 15 minutes time out to time protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown @Inject protected VolumeManager volMgr; // out an operation protected final int _retry = 24; protected final int _sleep = 10000; protected final int DEFAULT_DOMR_SSHPORT = 3922; protected final int MAX_CMD_MBEAN = 100; protected String _url; protected String _dcId; protected String _pod; protected String _cluster; protected String _username; protected String _password; protected String _guid; protected String _vCenterAddress; protected String _privateNetworkVSwitchName; protected VmwareTrafficLabel _guestTrafficInfo = new VmwareTrafficLabel(TrafficType.Guest); protected VmwareTrafficLabel _publicTrafficInfo = new VmwareTrafficLabel(TrafficType.Public); protected int _portsPerDvPortGroup; protected boolean _fullCloneFlag = false; protected boolean _reserveCpu = false; protected boolean _reserveMem = false; protected boolean _recycleHungWorker = false; protected DiskControllerType _rootDiskController = DiskControllerType.ide; protected ManagedObjectReference _morHyperHost; protected VmwareContext _serviceContext; protected String _hostName; protected HashMap<String, State> _vms = new HashMap<String, State>(71); protected List<PropertyMapDynamicBean> _cmdMBeans = new ArrayList<PropertyMapDynamicBean>(); protected Gson _gson; protected volatile long _cmdSequence = 1; protected StorageSubsystemCommandHandler storageHandler; protected static HashMap<VirtualMachinePowerState, State> s_statesTable; static { s_statesTable = new HashMap<VirtualMachinePowerState, State>(); s_statesTable.put(VirtualMachinePowerState.POWERED_ON, State.Running); s_statesTable.put(VirtualMachinePowerState.POWERED_OFF, State.Stopped); s_statesTable.put(VirtualMachinePowerState.SUSPENDED, State.Stopped); } public Gson getGson() { return _gson; } public VmwareResource() { _gson = GsonHelper.getGsonLogger(); } @Override public Answer executeRequest(Command cmd) { if(s_logger.isTraceEnabled()) s_logger.trace("Begin executeRequest(), cmd: " + cmd.getClass().getSimpleName()); Answer answer = null; NDC.push(_hostName != null ? _hostName : _guid + "(" + this.getClass().getPackage().getImplementationVersion() + ")"); try { long cmdSequence = _cmdSequence++; Date startTime = DateUtil.currentGMTTime(); PropertyMapDynamicBean mbean = new PropertyMapDynamicBean(); mbean.addProp("StartTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), startTime)); mbean.addProp("Command", _gson.toJson(cmd)); mbean.addProp("Sequence", String.valueOf(cmdSequence)); mbean.addProp("Name", cmd.getClass().getSimpleName()); Class<? extends Command> clz = cmd.getClass(); if (clz == CreateCommand.class) { answer = execute((CreateCommand) cmd); } else if (clz == SetPortForwardingRulesCommand.class) { answer = execute((SetPortForwardingRulesCommand) cmd); } else if (clz == SetStaticNatRulesCommand.class) { answer = execute((SetStaticNatRulesCommand) cmd); } else if (clz == LoadBalancerConfigCommand.class) { answer = execute((LoadBalancerConfigCommand) cmd); } else if (clz == IpAssocCommand.class) { answer = execute((IpAssocCommand) cmd); } else if (clz == SavePasswordCommand.class) { answer = execute((SavePasswordCommand) cmd); } else if (clz == DhcpEntryCommand.class) { answer = execute((DhcpEntryCommand) cmd); } else if (clz == CreateIpAliasCommand.class) { return execute((CreateIpAliasCommand) cmd); } else if (clz == DnsMasqConfigCommand.class) { return execute((DnsMasqConfigCommand) cmd); } else if (clz == DeleteIpAliasCommand.class) { return execute((DeleteIpAliasCommand) cmd); } else if (clz == VmDataCommand.class) { answer = execute((VmDataCommand) cmd); } else if (clz == ReadyCommand.class) { answer = execute((ReadyCommand) cmd); } else if (clz == GetHostStatsCommand.class) { answer = execute((GetHostStatsCommand) cmd); } else if (clz == GetVmStatsCommand.class) { answer = execute((GetVmStatsCommand) cmd); } else if (clz == CheckHealthCommand.class) { answer = execute((CheckHealthCommand) cmd); } else if (clz == StopCommand.class) { answer = execute((StopCommand) cmd); } else if (clz == RebootRouterCommand.class) { answer = execute((RebootRouterCommand) cmd); } else if (clz == RebootCommand.class) { answer = execute((RebootCommand) cmd); } else if (clz == CheckVirtualMachineCommand.class) { answer = execute((CheckVirtualMachineCommand) cmd); } else if (clz == PrepareForMigrationCommand.class) { answer = execute((PrepareForMigrationCommand) cmd); } else if (clz == MigrateCommand.class) { answer = execute((MigrateCommand) cmd); } else if (clz == MigrateWithStorageCommand.class) { answer = execute((MigrateWithStorageCommand) cmd); } else if (clz == MigrateVolumeCommand.class) { answer = execute((MigrateVolumeCommand) cmd); } else if (clz == DestroyCommand.class) { answer = execute((DestroyCommand) cmd); } else if (clz == CreateStoragePoolCommand.class) { return execute((CreateStoragePoolCommand) cmd); } else if (clz == ModifyStoragePoolCommand.class) { answer = execute((ModifyStoragePoolCommand) cmd); } else if (clz == DeleteStoragePoolCommand.class) { answer = execute((DeleteStoragePoolCommand) cmd); } else if (clz == CopyVolumeCommand.class) { answer = execute((CopyVolumeCommand) cmd); } else if (clz == CreateVolumeOVACommand.class) { answer = execute((CreateVolumeOVACommand) cmd); } else if (clz == PrepareOVAPackingCommand.class) { answer = execute((PrepareOVAPackingCommand) cmd); } else if (clz == AttachVolumeCommand.class) { answer = execute((AttachVolumeCommand) cmd); } else if (clz == AttachIsoCommand.class) { answer = execute((AttachIsoCommand) cmd); } else if (clz == ValidateSnapshotCommand.class) { answer = execute((ValidateSnapshotCommand) cmd); } else if (clz == ManageSnapshotCommand.class) { answer = execute((ManageSnapshotCommand) cmd); } else if (clz == BackupSnapshotCommand.class) { answer = execute((BackupSnapshotCommand) cmd); } else if (clz == CreateVolumeFromSnapshotCommand.class) { answer = execute((CreateVolumeFromSnapshotCommand) cmd); } else if (clz == CreatePrivateTemplateFromVolumeCommand.class) { answer = execute((CreatePrivateTemplateFromVolumeCommand) cmd); } else if (clz == CreatePrivateTemplateFromSnapshotCommand.class) { answer = execute((CreatePrivateTemplateFromSnapshotCommand) cmd); } else if (clz == UpgradeSnapshotCommand.class) { answer = execute((UpgradeSnapshotCommand) cmd); } else if (clz == GetStorageStatsCommand.class) { answer = execute((GetStorageStatsCommand) cmd); } else if (clz == PrimaryStorageDownloadCommand.class) { answer = execute((PrimaryStorageDownloadCommand) cmd); } else if (clz == GetVncPortCommand.class) { answer = execute((GetVncPortCommand) cmd); } else if (clz == SetupCommand.class) { answer = execute((SetupCommand) cmd); } else if (clz == MaintainCommand.class) { answer = execute((MaintainCommand) cmd); } else if (clz == PingTestCommand.class) { answer = execute((PingTestCommand) cmd); } else if (clz == CheckOnHostCommand.class) { answer = execute((CheckOnHostCommand) cmd); } else if (clz == ModifySshKeysCommand.class) { answer = execute((ModifySshKeysCommand) cmd); } else if (clz == PoolEjectCommand.class) { answer = execute((PoolEjectCommand) cmd); } else if (clz == NetworkUsageCommand.class) { answer = execute((NetworkUsageCommand) cmd); } else if (clz == StartCommand.class) { answer = execute((StartCommand) cmd); } else if (clz == RemoteAccessVpnCfgCommand.class) { answer = execute((RemoteAccessVpnCfgCommand) cmd); } else if (clz == VpnUsersCfgCommand.class) { answer = execute((VpnUsersCfgCommand) cmd); } else if (clz == CheckSshCommand.class) { answer = execute((CheckSshCommand) cmd); } else if (clz == CheckRouterCommand.class) { answer = execute((CheckRouterCommand) cmd); } else if (clz == SetFirewallRulesCommand.class) { answer = execute((SetFirewallRulesCommand)cmd); } else if (clz == BumpUpPriorityCommand.class) { answer = execute((BumpUpPriorityCommand)cmd); } else if (clz == GetDomRVersionCmd.class) { answer = execute((GetDomRVersionCmd)cmd); } else if (clz == CheckNetworkCommand.class) { answer = execute((CheckNetworkCommand) cmd); } else if (clz == SetupGuestNetworkCommand.class) { answer = execute((SetupGuestNetworkCommand) cmd); } else if (clz == IpAssocVpcCommand.class) { answer = execute((IpAssocVpcCommand) cmd); } else if (clz == PlugNicCommand.class) { answer = execute((PlugNicCommand) cmd); } else if (clz == UnPlugNicCommand.class) { answer = execute((UnPlugNicCommand) cmd); } else if (clz == SetSourceNatCommand.class) { answer = execute((SetSourceNatCommand) cmd); } else if (clz == SetNetworkACLCommand.class) { answer = execute((SetNetworkACLCommand) cmd); } else if (cmd instanceof CreateVMSnapshotCommand) { return execute((CreateVMSnapshotCommand)cmd); } else if(cmd instanceof DeleteVMSnapshotCommand){ return execute((DeleteVMSnapshotCommand)cmd); } else if(cmd instanceof RevertToVMSnapshotCommand){ return execute((RevertToVMSnapshotCommand)cmd); }else if (clz == SetPortForwardingRulesVpcCommand.class) { answer = execute((SetPortForwardingRulesVpcCommand) cmd); } else if (clz == Site2SiteVpnCfgCommand.class) { answer = execute((Site2SiteVpnCfgCommand) cmd); } else if (clz == CheckS2SVpnConnectionsCommand.class) { answer = execute((CheckS2SVpnConnectionsCommand) cmd); } else if (clz == ResizeVolumeCommand.class) { return execute((ResizeVolumeCommand) cmd); } else if (clz == UnregisterVMCommand.class) { return execute((UnregisterVMCommand) cmd); } else if (cmd instanceof StorageSubSystemCommand) { return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd); } else if (clz == ScaleVmCommand.class) { return execute((ScaleVmCommand) cmd); } else if (clz == PvlanSetupCommand.class) { return execute((PvlanSetupCommand) cmd); } else if (clz == SetStaticRouteCommand.class) { answer = execute((SetStaticRouteCommand) cmd); } else if (clz == UnregisterNicCommand.class) { answer = execute((UnregisterNicCommand) cmd); } else { answer = Answer.createUnsupportedCommandAnswer(cmd); } if(cmd.getContextParam("checkpoint") != null) { answer.setContextParam("checkpoint", cmd.getContextParam("checkpoint")); } Date doneTime = DateUtil.currentGMTTime(); mbean.addProp("DoneTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), doneTime)); mbean.addProp("Answer", _gson.toJson(answer)); synchronized (this) { try { JmxUtil.registerMBean("VMware " + _morHyperHost.getValue(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean); _cmdMBeans.add(mbean); if (_cmdMBeans.size() >= MAX_CMD_MBEAN) { PropertyMapDynamicBean mbeanToRemove = _cmdMBeans.get(0); _cmdMBeans.remove(0); JmxUtil.unregisterMBean("VMware " + _morHyperHost.getValue(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); } } catch (Exception e) { if(s_logger.isTraceEnabled()) s_logger.trace("Unable to register JMX monitoring due to exception " + ExceptionUtil.toString(e)); } } } finally { NDC.pop(); } if(s_logger.isTraceEnabled()) s_logger.trace("End executeRequest(), cmd: " + cmd.getClass().getSimpleName()); return answer; } private Answer execute(ResizeVolumeCommand cmd) { String path = cmd.getPath(); String vmName = cmd.getInstanceName(); long newSize = cmd.getNewSize()/1024; try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); // find VM through datacenter (VM is not at the target host yet) VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter"; s_logger.error(msg); throw new Exception(msg); } Pair<VirtualDisk, String> vdisk = vmMo.getDiskDevice(path, false); if(vdisk == null) { if(s_logger.isTraceEnabled()) s_logger.trace("resize volume done (failed)"); throw new Exception("No such disk device: " + path); } VirtualDisk disk = vdisk.first(); long oldSize = disk.getCapacityInKB(); if (newSize < oldSize){ throw new Exception("VMware doesn't support shrinking volume from larger size: " + oldSize+ " MB to a smaller size: " + newSize + " MB"); } else if(newSize == oldSize){ return new ResizeVolumeAnswer(cmd, true, "success", newSize*1024); } disk.setCapacityInKB(newSize); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(disk); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT); vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if (!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure VM to resize disk. vmName: " + vmName); } return new ResizeVolumeAnswer(cmd, true, "success", newSize*1024); } catch (Exception e) { s_logger.error("Unable to resize volume",e); String error = "failed to resize volume:" +e; return new ResizeVolumeAnswer(cmd, false, error ); } } protected Answer execute(CheckNetworkCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckNetworkCommand " + _gson.toJson(cmd)); } // TODO setup portgroup for private network needs to be done here now return new CheckNetworkAnswer(cmd, true , "Network Setup check by names is done"); } protected Answer execute(NetworkUsageCommand cmd) { if ( cmd.isForVpc() ) { return VPCNetworkUsage(cmd); } if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource NetworkUsageCommand " + _gson.toJson(cmd)); } if(cmd.getOption()!=null && cmd.getOption().equals("create") ){ String result = networkUsage(cmd.getPrivateIP(), "create", null); NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L); return answer; } long[] stats = getNetworkStats(cmd.getPrivateIP()); NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); return answer; } private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetStaticRouteCommand: " + _gson.toJson(cmd)); } boolean endResult = true; String controlIp = getRouterSshControlIp(cmd); String args = ""; String[] results = new String[cmd.getStaticRoutes().length]; int i = 0; // Extract and build the arguments for the command to be sent to the VR. String [][] rules = cmd.generateSRouteRules(); StringBuilder sb = new StringBuilder(); String[] srRules = rules[0]; for (int j = 0; j < srRules.length; j++) { sb.append(srRules[j]).append(','); } args += " -a " + sb.toString(); // Send over the command for execution, via ssh, to the VR. try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticroute.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticroute.sh " + args); if (!result.first()) { s_logger.error("SetStaticRouteCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetStaticRouteCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; endResult = false; } return new SetStaticRouteAnswer(cmd, endResult, results); } protected NetworkUsageAnswer VPCNetworkUsage(NetworkUsageCommand cmd) { String privateIp = cmd.getPrivateIP(); String option = cmd.getOption(); String publicIp = cmd.getGatewayIP(); String args = "-l " + publicIp+ " "; if (option.equals("get")) { args += "-g"; } else if (option.equals("create")) { args += "-c"; String vpcCIDR = cmd.getVpcCIDR(); args += " -v " + vpcCIDR; } else if (option.equals("reset")) { args += "-r"; } else if (option.equals("vpn")) { args += "-n"; } else if (option.equals("remove")) { args += "-d"; } else { return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } try { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing /opt/cloud/bin/vpc_netusage.sh " + args + " on DomR " + privateIp); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> resultPair = SshHelper.sshExecute(privateIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_netusage.sh " + args); if (!resultPair.first()) { throw new Exception(" vpc network usage plugin call failed "); } if (option.equals("get") || option.equals("vpn")) { String result = resultPair.second(); if (result == null || result.isEmpty()) { throw new Exception(" vpc network usage get returns empty "); } long[] stats = new long[2]; if (result != null) { String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += (new Long(splitResult[i++])).longValue(); stats[1] += (new Long(splitResult[i++])).longValue(); } return new NetworkUsageAnswer(cmd, "success", stats[0], stats[1]); } } return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } catch (Throwable e) { s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } protected Answer execute(SetPortForwardingRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetPortForwardingRulesCommand: " + _gson.toJson(cmd)); } String controlIp = getRouterSshControlIp(cmd); String args = ""; String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (PortForwardingRuleTO rule : cmd.getRules()) { args += rule.revoked() ? " -D " : " -A "; args += " -P " + rule.getProtocol().toLowerCase(); args += " -l " + rule.getSrcIp(); args += " -p " + rule.getStringSrcPortRange(); args += " -r " + rule.getDstIp(); args += " -d " + rule.getStringDstPortRange(); try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); if (!result.first()) { s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; endResult = false; } } return new SetPortForwardingRulesAnswer(cmd, results, endResult); } protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { String controlIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; FirewallRuleTO[] allrules = cmd.getRules(); FirewallRule.TrafficType trafficType = allrules[0].getTrafficType(); String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT); String[][] rules = cmd.generateFwRules(); String args = ""; args += " -F "; if (trafficType == FirewallRule.TrafficType.Egress){ args+= " -E "; if (egressDefault.equals("true")) { args+= " -P 1 "; } else if (egressDefault.equals("System")) { args+= " -P 2 "; } else { args+= " -P 0 "; } } StringBuilder sb = new StringBuilder(); String[] fwRules = rules[0]; if (fwRules.length > 0) { for (int i = 0; i < fwRules.length; i++) { sb.append(fwRules[i]).append(','); } args += " -a " + sb.toString(); } try { VmwareManager mgr = getServiceContext().getStockObject( VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = null; if (trafficType == FirewallRule.TrafficType.Egress){ result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewallRule_egress.sh " + args); } else { result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall_rule.sh " + args); } if (s_logger.isDebugEnabled()) { if (trafficType == FirewallRule.TrafficType.Egress){ s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewallRule_egress.sh " + args); } else { s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall_rule.sh " + args); } } if (!result.first()) { s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: " + args); //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails for (int i=0; i < results.length; i++) { results[i] = "Failed"; } return new SetFirewallRulesAnswer(cmd, false, results); } } catch (Throwable e) { s_logger.error("SetFirewallRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails for (int i=0; i < results.length; i++) { results[i] = "Failed"; } return new SetFirewallRulesAnswer(cmd, false, results); } return new SetFirewallRulesAnswer(cmd, true, results); } protected SetStaticNatRulesAnswer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetVPCStaticNatRulesCommand: " + _gson.toJson(cmd)); } String[] results = new String[cmd.getRules().length]; VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); int i = 0; boolean endResult = true; for (StaticNatRuleTO rule : cmd.getRules()) { // Prepare command to be send to VPC VR String args = ""; args += rule.revoked() ? " -D" : " -A"; args += " -l " + rule.getSrcIp(); args += " -r " + rule.getDstIp(); // Invoke command on VPC VR. try { Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticnat.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticnat.sh " + args); if (!result.first()) { s_logger.error("SetVPCStaticNatRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetVPCStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; endResult = false; } } return new SetStaticNatRulesAnswer(cmd, results, endResult); } protected Answer execute(SetStaticNatRulesCommand cmd) { if (cmd.getVpcId() != null) { return SetVPCStaticNatRules(cmd); } if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetFirewallRuleCommand: " + _gson.toJson(cmd)); } String args = null; String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (StaticNatRuleTO rule : cmd.getRules()) { // 1:1 NAT needs instanceip;publicip;domrip;op args = rule.revoked() ? " -D " : " -A "; args += " -l " + rule.getSrcIp(); args += " -r " + rule.getDstIp(); if (rule.getProtocol() != null) { args += " -P " + rule.getProtocol().toLowerCase(); } args += " -d " + rule.getStringSrcPortRange(); args += " -G "; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); if (!result.first()) { s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; endResult = false; } } return new SetStaticNatRulesAnswer(cmd, results, endResult); } protected Answer VPCLoadBalancerConfig(final LoadBalancerConfigCommand cmd) { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); File keyFile = mgr.getSystemVMKeyFile(); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); assert(controlIp != null); LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); String[] config = cfgtr.generateConfiguration(cmd); String tmpCfgFilePath = "/etc/haproxy/haproxy.cfg.new"; String tmpCfgFileContents = ""; for (int i = 0; i < config.length; i++) { tmpCfgFileContents += config[i]; tmpCfgFileContents += "\n"; } try { SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/etc/haproxy/", tmpCfgFileContents.getBytes(), "haproxy.cfg.new", null); try { String[][] rules = cfgtr.generateFwRules(cmd); String[] addRules = rules[LoadBalancerConfigurator.ADD]; String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; String[] statRules = rules[LoadBalancerConfigurator.STATS]; String args = ""; String ip = cmd.getNic().getIp(); args += " -i " + ip; StringBuilder sb = new StringBuilder(); if (addRules.length > 0) { for (int i = 0; i < addRules.length; i++) { sb.append(addRules[i]).append(','); } args += " -a " + sb.toString(); } sb = new StringBuilder(); if (removeRules.length > 0) { for (int i = 0; i < removeRules.length; i++) { sb.append(removeRules[i]).append(','); } args += " -d " + sb.toString(); } sb = new StringBuilder(); if (statRules.length > 0) { for (int i = 0; i < statRules.length; i++) { sb.append(statRules[i]).append(','); } args += " -s " + sb.toString(); } // Invoke the command Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_loadbalancer.sh " + args); if (!result.first()) { String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new Answer(cmd, false, msg); } if (s_logger.isInfoEnabled()) { s_logger.info("VPCLoadBalancerConfigCommand on domain router " + routerIp + " completed"); } } finally { SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); } return new Answer(cmd); } catch (Throwable e) { s_logger.error("Unexpected exception: " + e.toString(), e); return new Answer(cmd, false, "VPCLoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); } } protected Answer execute(final LoadBalancerConfigCommand cmd) { if ( cmd.getVpcId() != null ) { return VPCLoadBalancerConfig(cmd); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); File keyFile = mgr.getSystemVMKeyFile(); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); assert(controlIp != null); LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); String[] config = cfgtr.generateConfiguration(cmd); String[][] rules = cfgtr.generateFwRules(cmd); String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; String tmpCfgFileContents = ""; for (int i = 0; i < config.length; i++) { tmpCfgFileContents += config[i]; tmpCfgFileContents += "\n"; } try { SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.getBytes(), routerIp.replace('.', '_') + ".cfg", null); try { String[] addRules = rules[LoadBalancerConfigurator.ADD]; String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; String[] statRules = rules[LoadBalancerConfigurator.STATS]; String args = ""; args += "-i " + routerIp; args += " -f " + tmpCfgFilePath; StringBuilder sb = new StringBuilder(); if (addRules.length > 0) { for (int i = 0; i < addRules.length; i++) { sb.append(addRules[i]).append(','); } args += " -a " + sb.toString(); } sb = new StringBuilder(); if (removeRules.length > 0) { for (int i = 0; i < removeRules.length; i++) { sb.append(removeRules[i]).append(','); } args += " -d " + sb.toString(); } sb = new StringBuilder(); if (statRules.length > 0) { for (int i = 0; i < statRules.length; i++) { sb.append(statRules[i]).append(','); } args += " -s " + sb.toString(); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "scp " + tmpCfgFilePath + " /etc/haproxy/haproxy.cfg.new"); if (!result.first()) { s_logger.error("Unable to copy haproxy configuration file"); return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to uanble to copy haproxy configuration file"); } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + routerIp + ", /root/loadbalancer.sh " + args); } result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/loadbalancer.sh " + args); if (!result.first()) { String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new Answer(cmd, false, msg); } if (s_logger.isInfoEnabled()) { s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed"); } } finally { SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); } return new Answer(cmd); } catch (Throwable e) { s_logger.error("Unexpected exception: " + e.toString(), e); return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); } } // // list available ethx devices // ls /proc/sys/net/ipv4/conf // private int allocRouterEthDeviceIndex(String domrName, String routerIp) throws Exception { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); if(result.first()) { String[] tokens = result.second().split("\\s+"); HashMap<String, String> deviceNames = new HashMap<String, String>(); for(String token: tokens) { if(!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { deviceNames.put(token, token); } } for(int i = 1; ; i++) { if(!deviceNames.containsKey("eth" + i)) return i; } } return -1; } // // find mac address of a specified ethx device // ip address show ethx | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2 // returns // eth0:xx.xx.xx.xx // // list IP with eth devices // ifconfig ethx |grep -B1 "inet addr" | awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' // | awk -F: '{ print $1 ": " $3 }' // // returns // eth0:xx.xx.xx.xx // // private int findRouterEthDeviceIndex(String domrName, String routerIp, String mac) throws Exception { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); s_logger.info("findRouterEthDeviceIndex. mac: " + mac); // TODO : this is a temporary very inefficient solution, will refactor it later Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS // we use a waiting loop here as a workaround to synchronize activities in systems long startTick = System.currentTimeMillis(); while(System.currentTimeMillis() - startTick < 15000) { if(result.first()) { String[] tokens = result.second().split("\\s+"); for(String token : tokens) { if(!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); if(s_logger.isDebugEnabled()) s_logger.debug("Run domr script " + cmd); Pair<Boolean, String> result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, // TODO need to find the dev index inside router based on IP address cmd); if(s_logger.isDebugEnabled()) s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); if(result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim())) return Integer.parseInt(token.substring(3)); } } } s_logger.warn("can not find intereface associated with mac: " + mac + ", guest OS may still at loading state, retry..."); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { } } return -1; } private VirtualDevice findVirtualNicDevice(VirtualMachineMO vmMo, String mac) throws Exception { VirtualDevice[] nics = vmMo.getNicDevices(); for(VirtualDevice nic : nics) { if(nic instanceof VirtualEthernetCard) { if(((VirtualEthernetCard)nic).getMacAddress().equals(mac)) return nic; } } return null; } private SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) { s_logger.info("Executing resource SetupGuestNetworkCommand " + _gson.toJson(cmd)); VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); NicTO nic = cmd.getNic(); String routerIp = getRouterSshControlIp(cmd); String domrGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); String domrName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String gw = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask())); String domainName = cmd.getNetworkDomain(); String dns = cmd.getDefaultDns1(); if (dns == null || dns.isEmpty()) { dns = cmd.getDefaultDns2(); } else { String dns2= cmd.getDefaultDns2(); if ( dns2 != null && !dns2.isEmpty()) { dns += "," + dns2; } } try { int ethDeviceNum = findRouterEthDeviceIndex(domrName, routerIp, nic.getMac()); s_logger.info("find interface index. routerIp: " + routerIp + ", mac: " + nic.getMac() + ", index: " + ethDeviceNum); String args =(cmd.isAdd()?"-C":"-D"); String dev = "eth" + ethDeviceNum; args += " -d " + dev; args += " -i " + domrGIP; args += " -g " + gw; args += " -m " + cidr; args += " -n " + NetUtils.getSubNet(domrGIP, nic.getNetmask()); if ( dns != null && !dns.isEmpty() ) { args += " -s " + dns; } if ( domainName != null && !domainName.isEmpty() ) { args += " -e " + domainName; } Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_guestnw.sh " + args); if (!result.first()) { String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetupGuestNetworkAnswer(cmd, false, msg); } if (s_logger.isInfoEnabled()) { s_logger.info("SetupGuestNetworkCommand on domain router " + routerIp + " completed"); } return new SetupGuestNetworkAnswer(cmd, true, "success"); } catch (Exception e) { String msg = "SetupGuestNetwork failed due to " + e.toString(); s_logger.warn(msg, e); return new SetupGuestNetworkAnswer(cmd, false, msg); } } protected IpAssocAnswer execute(IpAssocVpcCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource IpAssocVpcCommand " + _gson.toJson(cmd)); } String[] results = new String[cmd.getIpAddresses().length]; int i = 0; String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIp = getRouterSshControlIp(cmd); try { IpAddressTO[] ips = cmd.getIpAddresses(); for (IpAddressTO ip : ips) { assignVPCPublicIpAddress(routerName, routerIp, ip); results[i++] = ip.getPublicIp() + " - success"; } } catch (Exception e) { s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); results[i++] = IpAssocAnswer.errorResult; } return new IpAssocAnswer(cmd, results); } protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetSourceNatCommand " + _gson.toJson(cmd)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIp = getRouterSshControlIp(cmd); IpAddressTO pubIp = cmd.getIpAddress(); try { int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, pubIp.getVifMacAddress()); String args = ""; args += " -A "; args += " -l "; args += pubIp.getPublicIp(); args += " -c "; args += "eth" + ethDeviceNum; Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_snat.sh " + args); if (!result.first()) { String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetSourceNatAnswer(cmd, false, msg); } return new SetSourceNatAnswer(cmd, true, "success"); } catch (Exception e) { String msg = "Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); return new SetSourceNatAnswer(cmd, false, msg); } } private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetNetworkACLCommand " + _gson.toJson(cmd)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY); String routerIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; try { String [][] rules = cmd.generateFwRules(); StringBuilder sb = new StringBuilder(); String[] aclRules = rules[0]; if (aclRules.length == 0) { return new SetNetworkACLAnswer(cmd, true, results); } for (int i = 0; i < aclRules.length; i++) { sb.append(aclRules[i]).append(','); } NicTO nic = cmd.getNic(); int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, nic.getMac()); String args = ""; Pair<Boolean, String> result; if (privateGw != null) { s_logger.debug("Private gateway configuration is set"); args += " -d " + "eth" + ethDeviceNum; args += " -a " + sb.toString(); result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_privategw_acl.sh " + args); if (!result.first()) { String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetNetworkACLAnswer(cmd, false, results); } } else { args=""; args += " -d " + "eth" + ethDeviceNum; args += " -i " + nic.getIp(); args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask())); args += " -a " + sb.toString(); result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_acl.sh " + args); if (!result.first()) { String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetNetworkACLAnswer(cmd, false, results); } } return new SetNetworkACLAnswer(cmd, true, results); } catch (Exception e) { String msg = "SetNetworkACL failed due to " + e.toString(); s_logger.error(msg, e); return new SetNetworkACLAnswer(cmd, false, results); } } protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesVpcCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetPortForwardingRulesVpcCommand " + _gson.toJson(cmd)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (PortForwardingRuleTO rule : cmd.getRules()) { String args =""; args += rule.revoked() ? " -D" : " -A"; args += " -P " + rule.getProtocol().toLowerCase(); args += " -l " + rule.getSrcIp(); args += " -p " + rule.getStringSrcPortRange(); args += " -r " + rule.getDstIp(); args += " -d " + rule.getStringDstPortRange().replace(":", "-"); try { Pair<Boolean, String> sshResult = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_portforwarding.sh " + args); if (!sshResult.first()) { results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch(Exception e) { results[i++] = "Failed"; endResult = false; } } return new SetPortForwardingRulesAnswer(cmd, results, endResult); } protected Answer execute(Site2SiteVpnCfgCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource Site2SiteVpnCfgCommand " + _gson.toJson(cmd)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerIp = getRouterSshControlIp(cmd); String args =""; if (cmd.isCreate()) { args += " -A"; args += " -l "; args += cmd.getLocalPublicIp(); args += " -n "; args += cmd.getLocalGuestCidr(); args += " -g "; args += cmd.getLocalPublicGateway(); args += " -r "; args += cmd.getPeerGatewayIp(); args += " -N "; args += cmd.getPeerGuestCidrList(); args += " -e "; args += "\"" + cmd.getEspPolicy() + "\""; args += " -i "; args += "\"" + cmd.getIkePolicy() + "\""; args += " -t "; args += Long.toString(cmd.getIkeLifetime()); args += " -T "; args += Long.toString(cmd.getEspLifetime()); args += " -s "; args += "\"" + cmd.getIpsecPsk() + "\""; args += " -d "; if (cmd.getDpd()) { args += "1"; } else { args += "0"; } } else { args += " -D"; args += " -r "; args += cmd.getPeerGatewayIp(); args += " -n "; args += cmd.getLocalGuestCidr(); args += " -N "; args += cmd.getPeerGuestCidrList(); } Pair<Boolean, String> result; try { result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/ipsectunnel.sh " + args); if (!result.first()) { s_logger.error("Setup site2site VPN " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new Answer(cmd, false, "Setup site2site VPN falied due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("setup site 2 site vpn on router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "Setup site2site VPN falied due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, "Setup site2site VPN failed due to " + VmwareHelper.getExceptionMessage(e)); } return new Answer(cmd, true, result.second()); } private PlugNicAnswer execute(PlugNicCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PlugNicCommand " + _gson.toJson(cmd)); } getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); String vmName = cmd.getVmName(); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if(vmMo == null) { if(hyperHost instanceof HostMO) { ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO)hyperHost).getParentMor()); vmMo = clusterMo.findVmOnHyperHost(vmName); } } if (vmMo == null) { String msg = "Router " + vmName + " no longer exists to execute PlugNic command"; s_logger.error(msg); throw new Exception(msg); } if(!isVMWareToolsInstalled(vmMo)){ String errMsg = "vmware tools is not installed or not running, cannot add nic to vm " + vmName; s_logger.debug(errMsg); return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + errMsg); } // TODO need a way to specify the control of NIC device type VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.E1000; // find a usable device number in VMware environment VirtualDevice[] nicDevices = vmMo.getNicDevices(); int deviceNumber = -1; for(VirtualDevice device : nicDevices) { if(device.getUnitNumber() > deviceNumber) deviceNumber = device.getUnitNumber(); } deviceNumber++; NicTO nicTo = cmd.getNic(); VirtualDevice nic; Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, false, cmd.getVMType());; if (VmwareHelper.isDvPortGroup(networkInfo.first())) { String dvSwitchUuid; ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter(); DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor); ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first()); dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor); s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid); nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), deviceNumber, deviceNumber + 1, true, true); } else { s_logger.info("Preparing NIC device on network " + networkInfo.second()); nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), deviceNumber, deviceNumber + 1, true, true); } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(nic); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when running PlugNicCommand"); } return new PlugNicAnswer(cmd, true, "success"); } catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + e.toString()); } } private UnPlugNicAnswer execute(UnPlugNicCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource UnPlugNicCommand " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); String vmName = cmd.getVmName(); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if(vmMo == null) { if(hyperHost instanceof HostMO) { ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO)hyperHost).getParentMor()); vmMo = clusterMo.findVmOnHyperHost(vmName); } } if (vmMo == null) { String msg = "VM " + vmName + " no longer exists to execute UnPlugNic command"; s_logger.error(msg); throw new Exception(msg); } if(!isVMWareToolsInstalled(vmMo)){ String errMsg = "vmware tools not installed or not running, cannot remove nic from vm " + vmName; s_logger.debug(errMsg); return new UnPlugNicAnswer(cmd, false, "Unable to execute unPlugNicCommand due to " + errMsg); } VirtualDevice nic = findVirtualNicDevice(vmMo, cmd.getNic().getMac()); if ( nic == null ) { return new UnPlugNicAnswer(cmd, true, "success"); } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(nic); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE); vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when running unplugNicCommand"); } return new UnPlugNicAnswer(cmd, true, "success"); } catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new UnPlugNicAnswer(cmd, false, "Unable to execute unPlugNicCommand due to " + e.toString()); } } protected void assignVPCPublicIpAddress(String domrName, String routerIp, IpAddressTO ip) throws Exception { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource assignVPCPublicIpAddress. domrName: " + domrName + ", routerIp: " + routerIp + ", ip: " + _gson.toJson(ip)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); int ethDeviceNum = findRouterEthDeviceIndex(domrName, routerIp, ip.getVifMacAddress()); if (ethDeviceNum < 0) { if (ip.isAdd()) { throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); } else { s_logger.debug("VIF to deassociate IP with does not exist, return success"); return; } } String args = ""; String snatArgs = ""; if (ip.isAdd()) { args += " -A "; snatArgs += " -A "; } else { args += " -D "; snatArgs += " -D "; } args += " -l "; args += ip.getPublicIp(); args += " -c "; args += "eth" + ethDeviceNum; args += " -g "; args += ip.getVlanGateway(); args += " -m "; args += Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); args += " -n "; args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask()); Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_ipassoc.sh " + args); if (!result.first()) { throw new InternalErrorException("Unable to assign public IP address"); } if (ip.isSourceNat()) { snatArgs += " -l "; snatArgs += ip.getPublicIp(); snatArgs += " -c "; snatArgs += "eth" + ethDeviceNum; Pair<Boolean, String> result_gateway = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_privateGateway.sh " + snatArgs); if (!result_gateway.first()) { throw new InternalErrorException("Unable to configure source NAT for public IP address."); } } } protected void assignPublicIpAddress(VirtualMachineMO vmMo, final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception { String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); Pair<Integer, VirtualDevice> publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); if (s_logger.isDebugEnabled()) { s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first()); } boolean addVif = false; boolean removeVif = false; if (add && publicNicInfo.first().intValue() == -1) { if (s_logger.isDebugEnabled()) { s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress); } addVif = true; } else if (!add && firstIP) { removeVif = true; if (s_logger.isDebugEnabled()) { s_logger.debug("Unplug NIC " + publicNicInfo.first()); } } if (addVif) { plugPublicNic(vmMo, vlanId, vifMacAddress); publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); if (publicNicInfo.first().intValue() >= 0) { networkUsage(privateIpAddress, "addVif", "eth" + publicNicInfo.first()); } } if (publicNicInfo.first().intValue() < 0) { String msg = "Failed to find DomR VIF to associate/disassociate IP with."; s_logger.error(msg); throw new InternalErrorException(msg); } String args = null; if (add) { args = " -A "; } else { args = " -D "; } if (sourceNat) { args += " -s "; } if (firstIP) { args += " -f "; } String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); args += " -l "; args += publicIpAddress + "/" + cidrSize; args += " -c "; args += "eth" + publicNicInfo.first(); args += " -g "; args += vlanGateway; if (addVif) { args += " -n "; } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + privateIpAddress + ", /opt/cloud/bin/ipassoc.sh " + args); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args); if (!result.first()) { s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); throw new Exception("ipassoc failed due to " + result.second()); } if (removeVif) { String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); int nicMasks = Integer.parseInt(nicMasksStr); nicMasks &= ~(1 << publicNicInfo.first().intValue()); vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); HostMO hostMo = vmMo.getRunningHost(); List<NetworkDetails> networks = vmMo.getNetworksWithDetails(); for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { cleanupNetwork(hostMo, netDetails); } } } } if (s_logger.isInfoEnabled()) { s_logger.info("ipassoc command on domain router " + privateIpAddress + " completed"); } } private void plugPublicNic(VirtualMachineMO vmMo, final String vlanId, final String vifMacAddress) throws Exception { // TODO : probably need to set traffic shaping Pair<ManagedObjectReference, String> networkInfo = null; VirtualSwitchType vSwitchType = VirtualSwitchType.StandardVirtualSwitch; if (_publicTrafficInfo != null) { vSwitchType = _publicTrafficInfo.getVirtualSwitchType(); } /** FIXME We have no clue which network this nic is on and that means that we can't figure out the BroadcastDomainType * so we assume that it's VLAN for now */ if (VirtualSwitchType.StandardVirtualSwitch == vSwitchType) { networkInfo = HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, _ops_timeout, true, BroadcastDomainType.Vlan, null); } else { networkInfo = HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, null, _ops_timeout, vSwitchType, _portsPerDvPortGroup, null, false, BroadcastDomainType.Vlan); } int nicIndex = allocPublicNicIndex(vmMo); try { VirtualDevice[] nicDevices = vmMo.getNicDevices(); VirtualEthernetCard device = (VirtualEthernetCard) nicDevices[nicIndex]; if (VirtualSwitchType.StandardVirtualSwitch == vSwitchType) { VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); nicBacking.setDeviceName(networkInfo.second()); nicBacking.setNetwork(networkInfo.first()); device.setBacking(nicBacking); } else { HostMO hostMo = vmMo.getRunningHost(); DatacenterMO dataCenterMo = new DatacenterMO(hostMo.getContext(), hostMo.getHyperHostDatacenter()); device.setBacking(dataCenterMo.getDvPortBackingInfo(networkInfo)); } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(device); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT); vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when plugPublicNic"); } } catch(Exception e) { // restore allocation mask in case of exceptions String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); int nicMasks = Integer.parseInt(nicMasksStr); nicMasks &= ~(1 << nicIndex); vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); throw e; } } private int allocPublicNicIndex(VirtualMachineMO vmMo) throws Exception { String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); if(nicMasksStr == null || nicMasksStr.isEmpty()) { throw new Exception("Could not find NIC allocation info"); } int nicMasks = Integer.parseInt(nicMasksStr); VirtualDevice[] nicDevices = vmMo.getNicDevices(); for(int i = 3; i < nicDevices.length; i++) { if((nicMasks & (1 << i)) == 0) { nicMasks |= (1 << i); vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); return i; } } throw new Exception("Could not allocate a free public NIC"); } protected Answer execute(IpAssocCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource IPAssocCommand: " + _gson.toJson(cmd)); } int i = 0; String[] results = new String[cmd.getIpAddresses().length]; VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); IpAddressTO[] ips = cmd.getIpAddresses(); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String controlIp = VmwareResource.getRouterSshControlIp(cmd); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(routerName); // command may sometimes be redirect to a wrong host, we relax // the check and will try to find it within cluster if(vmMo == null) { if(hyperHost instanceof HostMO) { ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO)hyperHost).getParentMor()); vmMo = clusterMo.findVmOnHyperHost(routerName); } } if (vmMo == null) { String msg = "Router " + routerName + " no longer exists to execute IPAssoc command"; s_logger.error(msg); throw new Exception(msg); } for (IpAddressTO ip : ips) { assignPublicIpAddress(vmMo, routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress()); results[i++] = ip.getPublicIp() + " - success"; } } catch (Throwable e) { s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); for (; i < cmd.getIpAddresses().length; i++) { results[i++] = IpAssocAnswer.errorResult; } } return new IpAssocAnswer(cmd, results); } protected Answer execute(SavePasswordCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } String controlIp = getRouterSshControlIp(cmd); final String password = cmd.getPassword(); final String vmIpAddress = cmd.getVmIpAddress(); // Run save_password_to_domr.sh String args = " -v " + vmIpAddress; if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + controlIp + ", /root/savepassword.sh " + args + " -p " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } args += " -p " + password; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/savepassword.sh " + args); if (!result.first()) { s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "SavePassword failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("savepassword command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "SavePasswordCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(DhcpEntryCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DhcpEntryCommand: " + _gson.toJson(cmd)); } // ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/root/edithosts.sh $mac $ip $vm $dfltrt $ns $staticrt" >/dev/null String args = " -m " + cmd.getVmMac(); if (cmd.getVmIpAddress() != null) { args += " -4 " + cmd.getVmIpAddress(); } args += " -h " + cmd.getVmName(); if (cmd.getDefaultRouter() != null) { args += " -d " + cmd.getDefaultRouter(); } if (cmd.getDefaultDns() != null) { args += " -n " + cmd.getDefaultDns(); } if (cmd.getStaticRoutes() != null) { args += " -s " + cmd.getStaticRoutes(); } if (cmd.getVmIp6Address() != null) { args += " -6 " + cmd.getVmIp6Address(); args += " -u " + cmd.getDuid(); } if (!cmd.isDefault()) { args += " -N"; } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/edithosts.sh " + args); if (!result.first()) { s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "DhcpEntry failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("dhcp_entry command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "DhcpEntryCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(final CreateIpAliasCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing createipAlias command: " + _gson.toJson(cmd)); } String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList(); String args=routerIp+" "; for (IpAliasTO ipaliasto : ipAliasTOs) { args = args + ipaliasto.getAlias_count()+":"+ipaliasto.getRouterip()+":"+ipaliasto.getNetmask()+"-"; } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/createipAlias " + args); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/createipAlias.sh " + args); if (!result.first()) { s_logger.error("ipAlias command on domr " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "createipAlias failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("createipAlias command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "createipAlias failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(final DeleteIpAliasCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos(); if (s_logger.isInfoEnabled()) { s_logger.info("Executing deleteipAlias command: " + _gson.toJson(cmd)); } String args=routerIp+" "; for (IpAliasTO ipAliasTO : revokedIpAliasTOs) { args = args + ipAliasTO.getAlias_count()+":"+ipAliasTO.getRouterip()+":"+ipAliasTO.getNetmask()+"-"; } args = args + "- " ; for (IpAliasTO ipAliasTO : activeIpAliasTOs) { args = args + ipAliasTO.getAlias_count()+":"+ipAliasTO.getRouterip()+":"+ipAliasTO.getNetmask()+"-"; } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/deleteipAlias " + args); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/deleteipAlias.sh " + args); if (!result.first()) { s_logger.error("ipAlias command on domr " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "deleteipAlias failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("deleteipAlias command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "deleteipAlias failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(final DnsMasqConfigCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing dnsmasqConfig command: " + _gson.toJson(cmd)); } String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); assert(controlIp != null); List<DhcpTO> dhcpTos = cmd.getIps(); String args =""; for(DhcpTO dhcpTo : dhcpTos) { args = args + dhcpTo.getRouterIp()+":"+dhcpTo.getGateway()+":"+dhcpTo.getNetmask()+":"+dhcpTo.getStartIpOfSubnet()+"-"; } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); File keyFile = mgr.getSystemVMKeyFile(); try { Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/dnsmasq.sh " + args); if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + routerIp + ", /root/dnsmasq.sh"); } if (!result.first()) { s_logger.error("Unable update dnsmasq config file"); return new Answer(cmd, false, "dnsmasq config update failed due to: " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("dnsmasq config command on domain router " + routerIp + " completed"); } }catch (Throwable e) { String msg = "Dnsmasqconfig command failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkbatchs2svpn.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); String cmdline = "/opt/cloud/bin/checkbatchs2svpn.sh "; for (String ip : cmd.getVpnIps()) { cmdline += " " + ip; } result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, cmdline); if (!result.first()) { s_logger.error("check site-to-site vpn connections command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new CheckS2SVpnConnectionsAnswer(cmd, false, result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("check site-to-site vpn connections command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "CheckS2SVpnConnectionsCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); } return new CheckS2SVpnConnectionsAnswer(cmd, true, result.second()); } protected Answer execute(CheckRouterCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckRouterCommand: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkrouter.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/checkrouter.sh "); if (!result.first()) { s_logger.error("check router command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new CheckRouterAnswer(cmd, "CheckRouter failed due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("check router command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "CheckRouterCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CheckRouterAnswer(cmd, msg); } return new CheckRouterAnswer(cmd, result.second(), true); } protected Answer execute(GetDomRVersionCmd cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource GetDomRVersionCmd: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/get_template_version.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/get_template_version.sh "); if (!result.first()) { s_logger.error("GetDomRVersionCmd on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new GetDomRVersionAnswer(cmd, "GetDomRVersionCmd failed due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("GetDomRVersionCmd on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "GetDomRVersionCmd failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new GetDomRVersionAnswer(cmd, msg); } String[] lines = result.second().split("&"); if (lines.length != 2) { return new GetDomRVersionAnswer(cmd, result.second()); } return new GetDomRVersionAnswer(cmd, result.second(), lines[0], lines[1]); } protected Answer execute(BumpUpPriorityCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource BumpUpPriorityCommand: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/bumpup_priority.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/bumpup_priority.sh "); if (!result.first()) { s_logger.error("BumpUpPriority command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new Answer(cmd, false, "BumpUpPriorityCommand failed due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("BumpUpPriorityCommand on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "BumpUpPriorityCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } if (result.second() == null || result.second().isEmpty()) { return new Answer(cmd, true, result.second()); } return new Answer(cmd, false, result.second()); } protected Answer execute(VmDataCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource VmDataCommand: " + _gson.toJson(cmd)); } String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); String vmIpAddress = cmd.getVmIpAddress(); List<String[]> vmData = cmd.getVmData(); String[] vmDataArgs = new String[vmData.size() * 2 + 4]; vmDataArgs[0] = "routerIP"; vmDataArgs[1] = routerPrivateIpAddress; vmDataArgs[2] = "vmIP"; vmDataArgs[3] = vmIpAddress; int i = 4; for (String[] vmDataEntry : vmData) { String folder = vmDataEntry[0]; String file = vmDataEntry[1]; String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; vmDataArgs[i] = folder + "," + file; vmDataArgs[i + 1] = contents; i += 2; } String content = encodeDataArgs(vmDataArgs); String tmpFileName = UUID.randomUUID().toString(); if (s_logger.isDebugEnabled()) { s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null); try { Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/userdata.py " + tmpFileName); if (!result.first()) { s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); } } finally { SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName); } if (s_logger.isInfoEnabled()) { s_logger.info("vm_data command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "VmDataCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } private String encodeDataArgs(String[] dataArgs) { StringBuilder sb = new StringBuilder(); for (String arg : dataArgs) { sb.append(arg); sb.append("\n"); } return sb.toString(); } protected CheckSshAnswer execute(CheckSshCommand cmd) { String vmName = cmd.getName(); String privateIp = cmd.getIp(); int cmdPort = cmd.getPort(); if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); } try { String result = connect(cmd.getName(), privateIp, cmdPort); if (result != null) { s_logger.error("Can not ping System vm " + vmName + "due to:" + result); return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + "due to:" + result); } } catch (Exception e) { s_logger.error("Can not ping System vm " + vmName + "due to exception"); return new CheckSshAnswer(cmd, e); } if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port succeeded for vm " + vmName); } if (VirtualMachineName.isValidRouterName(vmName)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Execute network usage setup command on " + vmName); } networkUsage(privateIp, "create", null); } return new CheckSshAnswer(cmd); } private DiskTO[] validateDisks(DiskTO[] disks) { List<DiskTO> validatedDisks = new ArrayList<DiskTO>(); for (DiskTO vol : disks) { if (vol.getType() != Volume.Type.ISO) { VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); if (primaryStore.getUuid() != null && !primaryStore.getUuid().isEmpty()) { validatedDisks.add(vol); } } else if (vol.getType() == Volume.Type.ISO) { TemplateObjectTO templateTO = (TemplateObjectTO)vol.getData(); if (templateTO.getPath() != null && !templateTO.getPath().isEmpty()) { validatedDisks.add(vol); } } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Drop invalid disk option, volumeTO: " + _gson.toJson(vol)); } } } return validatedDisks.toArray(new DiskTO[0]); } protected ScaleVmAnswer execute(ScaleVmCommand cmd) { VmwareContext context = getServiceContext(); VirtualMachineTO vmSpec = cmd.getVirtualMachine(); try{ VmwareHypervisorHost hyperHost = getHyperHost(context); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); int ramMb = (int) (vmSpec.getMinRam()/(1024 * 1024)); long hotaddIncrementSizeInMb; long hotaddMemoryLimitInMb; long requestedMaxMemoryInMb = vmSpec.getMaxRam() / (1024 * 1024); // Check if VM is really running on hypervisor host if (getVmState(vmMo) != State.Running) { throw new CloudRuntimeException("Found that the VM " + vmMo.getVmName() + " is not running. Unable to scale-up this VM"); } // Check max hot add limit hotaddIncrementSizeInMb = vmMo.getHotAddMemoryIncrementSizeInMb(); hotaddMemoryLimitInMb = vmMo.getHotAddMemoryLimitInMb(); if (requestedMaxMemoryInMb > hotaddMemoryLimitInMb) { throw new CloudRuntimeException("Memory of VM " + vmMo.getVmName() + " cannot be scaled to " + requestedMaxMemoryInMb + "MB." + " Requested memory limit is beyond the hotadd memory limit for this VM at the moment is " + hotaddMemoryLimitInMb + "MB."); } // Check increment is multiple of increment size long reminder = requestedMaxMemoryInMb % hotaddIncrementSizeInMb; if (reminder != 0) { requestedMaxMemoryInMb = requestedMaxMemoryInMb + hotaddIncrementSizeInMb - reminder; } // Check if license supports the feature VmwareHelper.isFeatureLicensed(hyperHost, FeatureKeyConstants.HOTPLUG); VmwareHelper .setVmScaleUpConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), vmSpec.getMinSpeed(), (int)requestedMaxMemoryInMb, ramMb, vmSpec.getLimitCpuUse()); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Unable to execute ScaleVmCommand"); } }catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new ScaleVmAnswer(cmd, false, "Unable to execute ScaleVmCommand due to " + e.toString()); } return new ScaleVmAnswer(cmd, true, null); } protected StartAnswer execute(StartCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource StartCommand: " + _gson.toJson(cmd)); } VirtualMachineTO vmSpec = cmd.getVirtualMachine(); String vmName = vmSpec.getName(); State state = State.Stopped; VmwareContext context = getServiceContext(); try { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // mark VM as starting state so that sync() can know not to report stopped too early synchronized (_vms) { _vms.put(vmName, State.Starting); } VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.valueOf(vmSpec.getDetails().get(VmDetailConstants.NIC_ADAPTER)); if(s_logger.isDebugEnabled()) s_logger.debug("VM " + vmName + " will be started with NIC device type: " + nicDeviceType); VmwareHypervisorHost hyperHost = getHyperHost(context); DiskTO[] disks = validateDisks(vmSpec.getDisks()); assert (disks.length > 0); NicTO[] nics = vmSpec.getNics(); HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks); if ((dataStoresDetails == null) || (dataStoresDetails.isEmpty()) ){ String msg = "Unable to locate datastore details of the volumes to be attached"; s_logger.error(msg); throw new Exception(msg); } VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo != null) { s_logger.info("VM " + vmName + " already exists, tear down devices for reconfiguration"); if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.ensureScsiDeviceController(); } else { ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); assert (morDc != null); vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo != null) { if (s_logger.isInfoEnabled()) { s_logger.info("Found vm " + vmName + " at other host, relocate to " + hyperHost.getHyperHostName()); } takeVmFromOtherHyperHost(hyperHost, vmName); if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.ensureScsiDeviceController(); } else { int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); Pair<ManagedObjectReference, DatastoreMO> rootDiskDataStoreDetails = null; for (DiskTO vol : disks) { if (vol.getType() == Volume.Type.ROOT) { PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)vol.getData().getDataStore(); rootDiskDataStoreDetails = dataStoresDetails.get(primaryStore.getUuid()); } } assert (vmSpec.getMinSpeed() != null) && (rootDiskDataStoreDetails != null); if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getMaxSpeed().intValue(), vmSpec.getMinSpeed(), vmSpec.getLimitCpuUse(),(int)(vmSpec.getMaxRam()/(1024*1024)), ramMb, translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), rootDiskDataStoreDetails.first(), false)) { throw new Exception("Failed to create VM. vmName: " + vmName); } } vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo == null) { throw new Exception("Failed to find the newly create or relocated VM. vmName: " + vmName); } } int totalChangeDevices = disks.length + nics.length; DiskTO volIso = null; if (vmSpec.getType() != VirtualMachine.Type.User) { // system VM needs a patch ISO totalChangeDevices++; } else { for (DiskTO vol : disks) { if (vol.getType() == Volume.Type.ISO) { volIso = vol; break; } } if (volIso == null) totalChangeDevices++; } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), vmSpec.getMinSpeed(),(int) (vmSpec.getMaxRam()/(1024*1024)), ramMb, translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), vmSpec.getLimitCpuUse()); String guestOsId = translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(); // Check for hotadd settings vmConfigSpec.setMemoryHotAddEnabled(vmMo.isMemoryHotAddSupported(guestOsId)); vmConfigSpec.setCpuHotAddEnabled(vmMo.isCpuHotAddSupported(guestOsId)); if ("true".equals(vmSpec.getDetails().get(VmDetailConstants.NESTED_VIRTUALIZATION_FLAG))) { s_logger.debug("Nested Virtualization enabled in configuration, checking hypervisor capability"); ManagedObjectReference hostMor = vmMo.getRunningHost().getMor(); ManagedObjectReference computeMor = context.getVimClient().getMoRefProp(hostMor, "parent"); ManagedObjectReference environmentBrowser = context.getVimClient().getMoRefProp(computeMor, "environmentBrowser"); HostCapability hostCapability = context.getService().queryTargetCapabilities(environmentBrowser, hostMor); if (hostCapability.isNestedHVSupported()) { s_logger.debug("Hypervisor supports nested virtualization, enabling for VM " + vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(true); } else { s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " +vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(false); } } VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; int i = 0; int ideUnitNumber = 0; int scsiUnitNumber =0; int nicUnitNumber = 0; int ideControllerKey = vmMo.getIDEDeviceControllerKey(); int scsiControllerKey = vmMo.getScsiDeviceControllerKey(); int controllerKey; String datastoreDiskPath; // prepare systemvm patch ISO if (vmSpec.getType() != VirtualMachine.Type.User) { // attach ISO (for patching of system VM) String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); if(secStoreUrl == null) { String msg = "secondary storage for dc " + _dcId + " is not ready yet?"; throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; throw new Exception(msg); } DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs); deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), secDsMo.getMor(), true, true, ideUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } } else { // we will always plugin a CDROM device if (volIso != null) { TemplateObjectTO iso = (TemplateObjectTO)volIso.getData(); if (iso.getPath() != null && !iso.getPath().isEmpty()) { DataStoreTO imageStore = iso.getDataStore(); if (!(imageStore instanceof NfsTO)) { s_logger.debug("unsupported protocol"); throw new Exception("unsupported protocol"); } NfsTO nfsImageStore = (NfsTO)imageStore; String isoPath = nfsImageStore.getUrl() + File.separator + iso.getPath(); Pair<String, ManagedObjectReference> isoDatastoreInfo = getIsoDatastoreInfo(hyperHost, isoPath); assert (isoDatastoreInfo != null); assert (isoDatastoreInfo.second() != null); deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, ideUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } } } else { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, null, null, true, true, ideUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } } } i++; for (DiskTO vol : sortVolumesByDeviceId(disks)) { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); if (vol.getType() == Volume.Type.ISO) { controllerKey = ideControllerKey; } else { if(vol.getType() == Volume.Type.ROOT) { if(vmSpec.getDetails() != null && vmSpec.getDetails().get(VmDetailConstants.ROOK_DISK_CONTROLLER) != null) { if(vmSpec.getDetails().get(VmDetailConstants.ROOK_DISK_CONTROLLER).equalsIgnoreCase("scsi")) controllerKey = scsiControllerKey; else controllerKey = ideControllerKey; } else { controllerKey = scsiControllerKey; } } else { // DATA volume always use SCSI device controllerKey = scsiControllerKey; } } if (vol.getType() != Volume.Type.ISO) { VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); Pair<ManagedObjectReference, DatastoreMO> volumeDsDetails = dataStoresDetails.get(primaryStore.getUuid()); assert (volumeDsDetails != null); VirtualDevice device; datastoreDiskPath = String.format("[%s] %s.vmdk", volumeDsDetails.second().getName(), volumeTO.getPath()); String chainInfo = volumeTO.getChainInfo(); if (chainInfo != null && !chainInfo.isEmpty()) { String[] diskChain = _gson.fromJson(chainInfo, String[].class); if (diskChain == null || diskChain.length < 1) { s_logger.warn("Empty previously-saved chain info, fall back to the original"); device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), (controllerKey==ideControllerKey)?ideUnitNumber++:scsiUnitNumber++, i + 1); } else { s_logger.info("Attach the disk with stored chain info: " + chainInfo); for (int j = 0; j < diskChain.length; j++) { diskChain[j] = String.format("[%s] %s", volumeDsDetails.second().getName(), diskChain[j]); } device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, diskChain, volumeDsDetails.first(), (controllerKey==ideControllerKey)?ideUnitNumber++:scsiUnitNumber++, i + 1); } } else { device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), (controllerKey==ideControllerKey)?ideUnitNumber++:scsiUnitNumber++, i + 1); } deviceConfigSpecArray[i].setDevice(device); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); if(s_logger.isDebugEnabled()) s_logger.debug("Prepare volume at new device " + _gson.toJson(device)); i++; } } VirtualDevice nic; int nicMask = 0; int nicCount = 0; for (NicTO nicTo : sortNicsByDeviceId(nics)) { s_logger.info("Prepare NIC device based on NicTO: " + _gson.toJson(nicTo)); boolean configureVServiceInNexus = (nicTo.getType() == TrafficType.Guest) && (vmSpec.getDetails().containsKey("ConfigureVServiceInNexus")); VirtualMachine.Type vmType = cmd.getVirtualMachine().getType(); Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, configureVServiceInNexus, vmType); if (VmwareHelper.isDvPortGroup(networkInfo.first())) { String dvSwitchUuid; ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter(); DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor); ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first()); dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor); s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid); nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), nicUnitNumber++, i + 1, true, true); } else { s_logger.info("Preparing NIC device on network " + networkInfo.second()); nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), nicUnitNumber++, i + 1, true, true); } deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(nic); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); if(s_logger.isDebugEnabled()) s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i])); // this is really a hacking for DomR, upon DomR startup, we will reset all the NIC allocation after eth3 if(nicCount < 3) nicMask |= (1 << nicCount); i++; nicCount++; } vmConfigSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray)); // pass boot arguments through machine.id & perform customized options to VMX ArrayList<OptionValue> extraOptions = new ArrayList<OptionValue>(); OptionValue newVal = new OptionValue(); newVal.setKey("machine.id"); newVal.setValue(vmSpec.getBootArgs()); extraOptions.add(newVal); newVal = new OptionValue(); newVal.setKey("devices.hotplug"); newVal.setValue("true"); extraOptions.add(newVal); /** * Extra Config : nvp.vm-uuid = uuid * - Required for Nicira NVP integration */ newVal = new OptionValue(); newVal.setKey("nvp.vm-uuid"); newVal.setValue(vmSpec.getUuid()); extraOptions.add(newVal); /** * Extra Config : nvp.iface-id.<num> = uuid * - Required for Nicira NVP integration */ int nicNum = 0; for (NicTO nicTo : sortNicsByDeviceId(nics)) { if (nicTo.getUuid() != null) { newVal = new OptionValue(); newVal.setKey("nvp.iface-id." + nicNum); newVal.setValue(nicTo.getUuid()); extraOptions.add(newVal); } nicNum++; } for(Map.Entry<String, String> entry : validateVmDetails(vmSpec.getDetails()).entrySet()) { newVal = new OptionValue(); newVal.setKey(entry.getKey()); newVal.setValue(entry.getValue()); extraOptions.add(newVal); } String keyboardLayout = null; if(vmSpec.getDetails() != null) keyboardLayout = vmSpec.getDetails().get(VmDetailConstants.KEYBOARD); vmConfigSpec.getExtraConfig().addAll(Arrays.asList(configureVnc(extraOptions.toArray(new OptionValue[0]), hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout))); if (!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure VM before start. vmName: " + vmName); } vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMask)); /** * We need to configure the port on the DV switch after the host is * connected. So make this happen between the configure and start of * the VM */ int nicIndex = 0; for (NicTO nicTo : sortNicsByDeviceId(nics)) { if (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch) { // We need to create a port with a unique vlan and pass the key to the nic device s_logger.trace("Nic " + nicTo.toString() + " is connected to an NVP logicalswitch"); VirtualDevice nicVirtualDevice = vmMo.getNicDeviceByIndex(nicIndex); if (nicVirtualDevice == null) { throw new Exception("Failed to find a VirtualDevice for nic " + nicIndex); //FIXME Generic exceptions are bad } VirtualDeviceBackingInfo backing = nicVirtualDevice.getBacking(); if (backing instanceof VirtualEthernetCardDistributedVirtualPortBackingInfo) { // This NIC is connected to a Distributed Virtual Switch VirtualEthernetCardDistributedVirtualPortBackingInfo portInfo = (VirtualEthernetCardDistributedVirtualPortBackingInfo) backing; DistributedVirtualSwitchPortConnection port = portInfo.getPort(); String portKey = port.getPortKey(); String portGroupKey = port.getPortgroupKey(); String dvSwitchUuid = port.getSwitchUuid(); s_logger.debug("NIC " + nicTo.toString() + " is connected to dvSwitch " + dvSwitchUuid + " pg " + portGroupKey + " port " + portKey); ManagedObjectReference dvSwitchManager = vmMo.getContext().getVimClient().getServiceContent().getDvSwitchManager(); ManagedObjectReference dvSwitch = vmMo.getContext().getVimClient().getService().queryDvsByUuid(dvSwitchManager, dvSwitchUuid); // Get all ports DistributedVirtualSwitchPortCriteria criteria = new DistributedVirtualSwitchPortCriteria(); criteria.setInside(true); criteria.getPortgroupKey().add(portGroupKey); List<DistributedVirtualPort> dvPorts = vmMo.getContext().getVimClient().getService().fetchDVPorts(dvSwitch, criteria); DistributedVirtualPort vmDvPort = null; List<Integer> usedVlans = new ArrayList<Integer>(); for (DistributedVirtualPort dvPort : dvPorts) { // Find the port for this NIC by portkey if (portKey.equals(dvPort.getKey())) { vmDvPort = dvPort; } VMwareDVSPortSetting settings = (VMwareDVSPortSetting) dvPort .getConfig().getSetting(); VmwareDistributedVirtualSwitchVlanIdSpec vlanId = (VmwareDistributedVirtualSwitchVlanIdSpec) settings .getVlan(); s_logger.trace("Found port " + dvPort.getKey() + " with vlan " + vlanId.getVlanId()); if (vlanId.getVlanId() > 0 && vlanId.getVlanId() < 4095) { usedVlans.add(vlanId.getVlanId()); } } if (vmDvPort == null) { throw new Exception("Empty port list from dvSwitch for nic " + nicTo.toString()); } DVPortConfigInfo dvPortConfigInfo = vmDvPort .getConfig(); VMwareDVSPortSetting settings = (VMwareDVSPortSetting) dvPortConfigInfo.getSetting(); VmwareDistributedVirtualSwitchVlanIdSpec vlanId = (VmwareDistributedVirtualSwitchVlanIdSpec) settings.getVlan(); BoolPolicy blocked = settings.getBlocked(); if (blocked.isValue() == Boolean.TRUE) { s_logger.trace("Port is blocked, set a vlanid and unblock"); DVPortConfigSpec dvPortConfigSpec = new DVPortConfigSpec(); VMwareDVSPortSetting edittedSettings = new VMwareDVSPortSetting(); // Unblock blocked.setValue(Boolean.FALSE); blocked.setInherited(Boolean.FALSE); edittedSettings.setBlocked(blocked); // Set vlan for (i = 1; i < 4095; i++) { if (!usedVlans.contains(i)) break; } vlanId.setVlanId(i); // FIXME should be a determined // based on usage vlanId.setInherited(false); edittedSettings.setVlan(vlanId); dvPortConfigSpec.setSetting(edittedSettings); dvPortConfigSpec.setOperation("edit"); dvPortConfigSpec.setKey(portKey); List<DVPortConfigSpec> dvPortConfigSpecs = new ArrayList<DVPortConfigSpec>(); dvPortConfigSpecs.add(dvPortConfigSpec); ManagedObjectReference task = vmMo.getContext().getVimClient().getService().reconfigureDVPortTask(dvSwitch, dvPortConfigSpecs); if (!vmMo.getContext().getVimClient().waitForTask(task)) { throw new Exception( "Failed to configure the dvSwitch port for nic " + nicTo.toString()); } s_logger.debug("NIC " + nicTo.toString() + " connected to vlan " + i); } else { s_logger.trace("Port already configured and set to vlan " + vlanId.getVlanId()); } } else if (backing instanceof VirtualEthernetCardNetworkBackingInfo) { // This NIC is connected to a Virtual Switch // Nothing to do } else { s_logger.error("nic device backing is of type " + backing.getClass().getName()); throw new Exception("Incompatible backing for a VirtualDevice for nic " + nicIndex); //FIXME Generic exceptions are bad } } nicIndex++; } if (!vmMo.powerOn()) { throw new Exception("Failed to start VM. vmName: " + vmName); } state = State.Running; return new StartAnswer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "StartCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new StartAnswer(cmd, msg); } finally { synchronized (_vms) { if (state != State.Stopped) { _vms.put(vmName, state); } else { _vms.remove(vmName); } } } } private Map<String, String> validateVmDetails(Map<String, String> vmDetails) { Map<String, String> validatedDetails = new HashMap<String, String>(); if(vmDetails != null && vmDetails.size() > 0) { for(Map.Entry<String, String> entry : vmDetails.entrySet()) { if("machine.id".equalsIgnoreCase(entry.getKey())) continue; else if("devices.hotplug".equalsIgnoreCase(entry.getKey())) continue; else if("RemoteDisplay.vnc.enabled".equalsIgnoreCase(entry.getKey())) continue; else if("RemoteDisplay.vnc.password".equalsIgnoreCase(entry.getKey())) continue; else if("RemoteDisplay.vnc.port".equalsIgnoreCase(entry.getKey())) continue; else if("RemoteDisplay.vnc.keymap".equalsIgnoreCase(entry.getKey())) continue; else validatedDetails.put(entry.getKey(), entry.getValue()); } } return validatedDetails; } private NicTO[] sortNicsByDeviceId(NicTO[] nics) { List<NicTO> listForSort = new ArrayList<NicTO>(); for (NicTO nic : nics) { listForSort.add(nic); } Collections.sort(listForSort, new Comparator<NicTO>() { @Override public int compare(NicTO arg0, NicTO arg1) { if (arg0.getDeviceId() < arg1.getDeviceId()) { return -1; } else if (arg0.getDeviceId() == arg1.getDeviceId()) { return 0; } return 1; } }); return listForSort.toArray(new NicTO[0]); } private DiskTO[] sortVolumesByDeviceId(DiskTO[] volumes) { List<DiskTO> listForSort = new ArrayList<DiskTO>(); for (DiskTO vol : volumes) { listForSort.add(vol); } Collections.sort(listForSort, new Comparator<DiskTO>() { @Override public int compare(DiskTO arg0, DiskTO arg1) { if (arg0.getDiskSeq() < arg1.getDiskSeq()) { return -1; } else if (arg0.getDiskSeq() == arg1.getDiskSeq()) { return 0; } return 1; } }); return listForSort.toArray(new DiskTO[0]); } private HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> inferDatastoreDetailsFromDiskInfo(VmwareHypervisorHost hyperHost, VmwareContext context, DiskTO[] disks) throws Exception { HashMap<String ,Pair<ManagedObjectReference, DatastoreMO>> poolMors = new HashMap<String, Pair<ManagedObjectReference, DatastoreMO>>(); assert (hyperHost != null) && (context != null); for (DiskTO vol : disks) { if (vol.getType() != Volume.Type.ISO) { VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); String poolUuid = primaryStore.getUuid(); if(poolMors.get(poolUuid) == null) { ManagedObjectReference morDataStore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, poolUuid); if (morDataStore == null) { String msg = "Failed to get the mounted datastore for the volume's pool " + poolUuid; s_logger.error(msg); throw new Exception(msg); } poolMors.put(poolUuid, new Pair<ManagedObjectReference, DatastoreMO> (morDataStore, new DatastoreMO(context, morDataStore))); } } } return poolMors; } private String getPvlanInfo(NicTO nicTo) { if (nicTo.getBroadcastType() == BroadcastDomainType.Pvlan) { return NetUtils.getIsolatedPvlanFromUri(nicTo.getBroadcastUri()); } return null; } private String getVlanInfo(NicTO nicTo, String defaultVlan) { if (nicTo.getBroadcastType() == BroadcastDomainType.Native) { return defaultVlan; } else if (nicTo.getBroadcastType() == BroadcastDomainType.Vlan || nicTo.getBroadcastType() == BroadcastDomainType.Pvlan) { if (nicTo.getBroadcastUri() != null) { if (nicTo.getBroadcastType() == BroadcastDomainType.Vlan) // For vlan, the broadcast uri is of the form vlan://<vlanid> return nicTo.getBroadcastUri().getHost(); else // for pvlan, the broacast uri will be of the form pvlan://<vlanid>-i<pvlanid> return NetUtils.getPrimaryPvlanFromUri(nicTo.getBroadcastUri()); } else { s_logger.warn("BroadcastType is not claimed as VLAN or PVLAN, but without vlan info in broadcast URI. Use vlan info from labeling: " + defaultVlan); return defaultVlan; } } else if (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch) { // We don't need to set any VLAN id for an NVP logical switch return null; } s_logger.warn("Unrecognized broadcast type in VmwareResource, type: " + nicTo.getBroadcastType().toString() + ". Use vlan info from labeling: " + defaultVlan); return defaultVlan; } private Pair<ManagedObjectReference, String> prepareNetworkFromNicInfo(HostMO hostMo, NicTO nicTo, boolean configureVServiceInNexus, VirtualMachine.Type vmType) throws Exception { Pair<String, String> switchName; TrafficType trafficType; VirtualSwitchType switchType; switchName = getTargetSwitch(nicTo); trafficType = nicTo.getType(); // Get switch type from resource property which is dictated by cluster property // If a virtual switch type is specified while adding cluster that will be used. // Else If virtual switch type is specified in physical traffic label that will be used // Else use standard vSwitch switchType = VirtualSwitchType.StandardVirtualSwitch; if (trafficType == TrafficType.Guest && _guestTrafficInfo != null) { switchType = _guestTrafficInfo.getVirtualSwitchType(); } else if (trafficType == TrafficType.Public && _publicTrafficInfo != null) { switchType = _publicTrafficInfo.getVirtualSwitchType(); } String namePrefix = getNetworkNamePrefix(nicTo); Pair<ManagedObjectReference, String> networkInfo = null; s_logger.info("Prepare network on " + switchType + " " + switchName + " with name prefix: " + namePrefix); if (VirtualSwitchType.StandardVirtualSwitch == switchType) { networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()), nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _ops_timeout, !namePrefix.startsWith("cloud.private"), nicTo.getBroadcastType(), nicTo.getUuid()); } else { String vlanId = getVlanInfo(nicTo, switchName.second()); String svlanId = null; boolean pvlannetwork = (getPvlanInfo(nicTo) == null)?false:true; if (vmType != null && vmType.equals(VirtualMachine.Type.DomainRouter) && pvlannetwork) { // plumb this network to the promiscuous vlan. svlanId = vlanId; } else { // plumb this network to the isolated vlan. svlanId = getPvlanInfo(nicTo); } networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, vlanId, svlanId, nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _ops_timeout, switchType, _portsPerDvPortGroup, nicTo.getGateway(), configureVServiceInNexus, nicTo.getBroadcastType()); } return networkInfo; } // return Pair<switch name, vlan tagging> private Pair<String, String> getTargetSwitch(NicTO nicTo) throws Exception { if(nicTo.getName() != null && !nicTo.getName().isEmpty()) { String[] tokens = nicTo.getName().split(","); // Format of network traffic label is <VSWITCH>,<VLANID>,<VSWITCHTYPE> // If all 3 fields are mentioned then number of tokens would be 3. // If only <VSWITCH>,<VLANID> are mentioned then number of tokens would be 2. if(tokens.length == 2 || tokens.length == 3) { String vlanToken = tokens[1]; if (vlanToken.isEmpty()) { vlanToken = Vlan.UNTAGGED; } return new Pair<String, String>(tokens[0], vlanToken); } else { return new Pair<String, String>(nicTo.getName(), Vlan.UNTAGGED); } } if (nicTo.getType() == Networks.TrafficType.Guest) { return new Pair<String, String>(_guestTrafficInfo.getVirtualSwitchName(), Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management) { return new Pair<String, String>(_privateNetworkVSwitchName, Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Public) { return new Pair<String, String>(_publicTrafficInfo.getVirtualSwitchName(), Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Storage) { return new Pair<String, String>(_privateNetworkVSwitchName, Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Vpn) { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } else { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } } private String getNetworkNamePrefix(NicTO nicTo) throws Exception { if (nicTo.getType() == Networks.TrafficType.Guest) { return "cloud.guest"; } else if (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management) { return "cloud.private"; } else if (nicTo.getType() == Networks.TrafficType.Public) { return "cloud.public"; } else if (nicTo.getType() == Networks.TrafficType.Storage) { return "cloud.storage"; } else if (nicTo.getType() == Networks.TrafficType.Vpn) { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } else { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } } protected synchronized Answer execute(final RemoteAccessVpnCfgCommand cmd) { String controlIp = getRouterSshControlIp(cmd); StringBuffer argsBuf = new StringBuffer(); if (cmd.isCreate()) { argsBuf.append(" -r ").append(cmd.getIpRange()).append(" -p ").append(cmd.getPresharedKey()).append(" -s ").append(cmd.getVpnServerIp()).append(" -l ").append(cmd.getLocalIp()) .append(" -c "); } else { argsBuf.append(" -d ").append(" -s ").append(cmd.getVpnServerIp()); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if (s_logger.isDebugEnabled()) { s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); if (!result.first()) { s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second()); return new Answer(cmd, false, "RemoteAccessVpnCfg command failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed"); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "RemoteAccessVpnCfg command failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected synchronized Answer execute(final VpnUsersCfgCommand cmd) { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { StringBuffer argsBuf = new StringBuffer(); if (!userpwd.isAdd()) { argsBuf.append(" -U ").append(userpwd.getUsername()); } else { argsBuf.append(" -u ").append(userpwd.getUsernamePassword()); } try { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); if (!result.first()) { s_logger.error("VpnUserCfg command on domR failed, message: " + result.second()); return new Answer(cmd, false, "VpnUserCfg command failed due to " + result.second()); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "VpnUserCfg command failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } } return new Answer(cmd); } private VirtualMachineMO takeVmFromOtherHyperHost(VmwareHypervisorHost hyperHost, String vmName) throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo != null) { ManagedObjectReference morTargetPhysicalHost = hyperHost.findMigrationTarget(vmMo); if (morTargetPhysicalHost == null) { String msg = "VM " + vmName + " is on other host and we have no resource available to migrate and start it here"; s_logger.error(msg); throw new Exception(msg); } if (!vmMo.relocate(morTargetPhysicalHost)) { String msg = "VM " + vmName + " is on other host and we failed to relocate it here"; s_logger.error(msg); throw new Exception(msg); } return vmMo; } return null; } // isoUrl sample content : // nfs://192.168.10.231/export/home/kelven/vmware-test/secondary/template/tmpl/2/200//200-2-80f7ee58-6eff-3a2d-bcb0-59663edf6d26.iso private Pair<String, ManagedObjectReference> getIsoDatastoreInfo(VmwareHypervisorHost hyperHost, String isoUrl) throws Exception { assert (isoUrl != null); int isoFileNameStartPos = isoUrl.lastIndexOf("/"); if (isoFileNameStartPos < 0) { throw new Exception("Invalid ISO path info"); } String isoFileName = isoUrl.substring(isoFileNameStartPos); int templateRootPos = isoUrl.indexOf("template/tmpl"); if (templateRootPos < 0) { throw new Exception("Invalid ISO path info"); } String storeUrl = isoUrl.substring(0, templateRootPos - 1); String isoPath = isoUrl.substring(templateRootPos, isoFileNameStartPos); ManagedObjectReference morDs = prepareSecondaryDatastoreOnHost(storeUrl); DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); return new Pair<String, ManagedObjectReference>(String.format("[%s] %s%s", dsMo.getName(), isoPath, isoFileName), morDs); } protected Answer execute(ReadyCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ReadyCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); if(hyperHost.isHyperHostConnected()) { return new ReadyAnswer(cmd); } else { return new ReadyAnswer(cmd, "Host is not in connect state"); } } catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new ReadyAnswer(cmd, VmwareHelper.getExceptionMessage(e)); } } protected Answer execute(GetHostStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetHostStatsCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), 0, 0, 0, "host", 0, 0, 0, 0); Answer answer = new GetHostStatsAnswer(cmd, hostStats); try { HostStatsEntry entry = getHyperHostStats(hyperHost); if(entry != null) { entry.setHostId(cmd.getHostId()); answer = new GetHostStatsAnswer(cmd, entry); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unable to execute GetHostStatsCommand due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); } if (s_logger.isTraceEnabled()) { s_logger.trace("GetHostStats Answer: " + _gson.toJson(answer)); } return answer; } protected Answer execute(GetVmStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetVmStatsCommand: " + _gson.toJson(cmd)); } HashMap<String, VmStatsEntry> vmStatsMap = null; try { HashMap<String, State> newStates = getVmStates(); List<String> requestedVmNames = cmd.getVmNames(); List<String> vmNames = new ArrayList<String>(); if (requestedVmNames != null) { for (String vmName : requestedVmNames) { if (newStates.get(vmName) != null) { vmNames.add(vmName); } } } if (vmNames != null) { vmStatsMap = getVmStats(vmNames); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to execute GetVmStatsCommand due to : " + VmwareHelper.getExceptionMessage(e), e); } Answer answer = new GetVmStatsAnswer(cmd, vmStatsMap); if (s_logger.isTraceEnabled()) { s_logger.trace("Report GetVmStatsAnswer: " + _gson.toJson(answer)); } return answer; } protected Answer execute(CheckHealthCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckHealthCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); if (hyperHost.isHyperHostConnected()) { return new CheckHealthAnswer(cmd, true); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to execute CheckHealthCommand due to " + VmwareHelper.getExceptionMessage(e), e); } return new CheckHealthAnswer(cmd, false); } protected Answer execute(StopCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource StopCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { State state = null; synchronized (_vms) { state = _vms.get(cmd.getVmName()); _vms.put(cmd.getVmName(), State.Stopping); } try { vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, "0"); if (getVmState(vmMo) != State.Stopped) { if (vmMo.safePowerOff(_shutdown_waitMs)) { state = State.Stopped; return new StopAnswer(cmd, "Stop VM " + cmd.getVmName() + " Succeed", 0, true); } else { String msg = "Have problem in powering off VM " + cmd.getVmName() + ", let the process continue"; s_logger.warn(msg); return new StopAnswer(cmd, msg, 0, true); } } else { state = State.Stopped; } String msg = "VM " + cmd.getVmName() + " is already in stopped state"; s_logger.info(msg); return new StopAnswer(cmd, msg, 0, true); } finally { synchronized (_vms) { _vms.put(cmd.getVmName(), state); } } } else { synchronized (_vms) { _vms.remove(cmd.getVmName()); } String msg = "VM " + cmd.getVmName() + " is no longer in vSphere"; s_logger.info(msg); return new StopAnswer(cmd, msg, 0, true); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "StopCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new StopAnswer(cmd, msg, false); } } protected Answer execute(RebootRouterCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource RebootRouterCommand: " + _gson.toJson(cmd)); } RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); if (answer.getResult()) { String connectResult = connect(cmd.getVmName(), cmd.getPrivateIpAddress()); networkUsage(cmd.getPrivateIpAddress(), "create", null); if (connectResult == null) { return answer; } else { return new Answer(cmd, false, connectResult); } } return answer; } protected Answer execute(RebootCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource RebootCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { try { vmMo.rebootGuest(); return new RebootAnswer(cmd, "reboot succeeded", true); } catch(ToolsUnavailableFaultMsg e) { s_logger.warn("VMware tools is not installed at guest OS, we will perform hard reset for reboot"); } catch(Exception e) { s_logger.warn("We are not able to perform gracefull guest reboot due to " + VmwareHelper.getExceptionMessage(e)); } // continue to try with hard-reset if (vmMo.reset()) { return new RebootAnswer(cmd, "reboot succeeded", true); } String msg = "Reboot failed in vSphere. vm: " + cmd.getVmName(); s_logger.warn(msg); return new RebootAnswer(cmd, msg, false); } else { String msg = "Unable to find the VM in vSphere to reboot. vm: " + cmd.getVmName(); s_logger.warn(msg); return new RebootAnswer(cmd, msg, false); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "RebootCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new RebootAnswer(cmd, msg, false); } } protected Answer execute(CheckVirtualMachineCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckVirtualMachineCommand: " + _gson.toJson(cmd)); } final String vmName = cmd.getVmName(); State state = State.Unknown; Integer vncPort = null; VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo != null) { state = getVmState(vmMo); if (state == State.Running) { synchronized (_vms) { _vms.put(vmName, State.Running); } } return new CheckVirtualMachineAnswer(cmd, state, vncPort); } else { s_logger.warn("Can not find vm " + vmName + " to execute CheckVirtualMachineCommand"); return new CheckVirtualMachineAnswer(cmd, state, vncPort); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unexpected exception: " + VmwareHelper.getExceptionMessage(e), e); return new CheckVirtualMachineAnswer(cmd, state, vncPort); } } protected Answer execute(PrepareForMigrationCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PrepareForMigrationCommand: " + _gson.toJson(cmd)); } VirtualMachineTO vm = cmd.getVirtualMachine(); if (s_logger.isDebugEnabled()) { s_logger.debug("Preparing host for migrating " + vm); } final String vmName = vm.getName(); try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // find VM through datacenter (VM is not at the target host yet) VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter"; s_logger.error(msg); throw new Exception(msg); } NicTO[] nics = vm.getNics(); for (NicTO nic : nics) { // prepare network on the host prepareNetworkFromNicInfo(new HostMO(getServiceContext(), _morHyperHost), nic, false, cmd.getVirtualMachine().getType()); } String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); if(secStoreUrl == null) { String msg = "secondary storage for dc " + _dcId + " is not ready yet?"; throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; throw new Exception(msg); } synchronized (_vms) { _vms.put(vm.getName(), State.Migrating); } return new PrepareForMigrationAnswer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unexcpeted exception " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new PrepareForMigrationAnswer(cmd, msg); } } protected Answer execute(MigrateCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MigrateCommand: " + _gson.toJson(cmd)); } final String vmName = cmd.getVmName(); State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); // find VM through datacenter (VM is not at the target host yet) VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter"; s_logger.error(msg); throw new Exception(msg); } VmwareHypervisorHost destHyperHost = getTargetHyperHost(new DatacenterMO(hyperHost.getContext(), morDc), cmd.getDestinationIp()); ManagedObjectReference morTargetPhysicalHost = destHyperHost.findMigrationTarget(vmMo); if (morTargetPhysicalHost == null) { throw new Exception("Unable to find a target capable physical host"); } if (!vmMo.migrate(destHyperHost.getHyperHostOwnerResourcePool(), morTargetPhysicalHost)) { throw new Exception("Migration failed"); } state = State.Stopping; return new MigrateAnswer(cmd, true, "migration succeeded", null); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new MigrateAnswer(cmd, false, msg, null); } finally { synchronized (_vms) { _vms.put(vmName, state); } } } protected Answer execute(MigrateWithStorageCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MigrateWithStorageCommand: " + _gson.toJson(cmd)); } VirtualMachineTO vmTo = cmd.getVirtualMachine(); final String vmName = vmTo.getName(); State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } VmwareHypervisorHost srcHyperHost = null; VmwareHypervisorHost tgtHyperHost = null; VirtualMachineMO vmMo = null; ManagedObjectReference morDsAtTarget = null; ManagedObjectReference morDsAtSource = null; ManagedObjectReference morDc = null; ManagedObjectReference morDcOfTargetHost = null; ManagedObjectReference morTgtHost = new ManagedObjectReference(); VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec(); List<VirtualMachineRelocateSpecDiskLocator> diskLocators = new ArrayList<VirtualMachineRelocateSpecDiskLocator>(); VirtualMachineRelocateSpecDiskLocator diskLocator = null; boolean isFirstDs = true; String srcDiskName = ""; String srcDsName = ""; String tgtDsName = ""; String tgtDsNfsHost; String tgtDsNfsPath; int tgtDsNfsPort; VolumeTO volume; StorageFilerTO filerTo; Set<String> mountedDatastoresAtSource = new HashSet<String>(); Map<VolumeTO, StorageFilerTO> volToFiler = cmd.getVolumeToFiler(); String tgtHost = cmd.getTargetHost(); String tgtHostMorInfo = tgtHost.split("@")[0]; morTgtHost.setType(tgtHostMorInfo.split(":")[0]); morTgtHost.setValue(tgtHostMorInfo.split(":")[1]); try { srcHyperHost = getHyperHost(getServiceContext()); tgtHyperHost = new HostMO(getServiceContext(), morTgtHost); morDc = srcHyperHost.getHyperHostDatacenter(); morDcOfTargetHost = tgtHyperHost.getHyperHostDatacenter(); if (!morDc.getValue().equalsIgnoreCase(morDcOfTargetHost.getValue())) { String msg = "Source host & target host are in different datacentesr"; throw new CloudRuntimeException(msg); } VmwareManager mgr = tgtHyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // find VM through datacenter (VM is not at the target host yet) vmMo = srcHyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter " + morDc.getValue(); s_logger.error(msg); throw new Exception(msg); } // Get details of each target datastore & attach to source host. for (Entry<VolumeTO, StorageFilerTO> entry : volToFiler.entrySet()) { volume = entry.getKey(); filerTo = entry.getValue(); srcDsName = volume.getPoolUuid().replace("-", ""); tgtDsName = filerTo.getUuid().replace("-", ""); tgtDsNfsHost = filerTo.getHost(); tgtDsNfsPath = filerTo.getPath(); tgtDsNfsPort = filerTo.getPort(); s_logger.debug("Preparing spec for volume : " + volume.getName()); morDsAtTarget = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(tgtHyperHost, filerTo.getUuid()); if (morDsAtTarget == null) { String msg = "Unable to find the mounted datastore with uuid " + morDsAtTarget + " to execute MigrateWithStorageCommand"; s_logger.error(msg); throw new Exception(msg); } morDsAtSource = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(srcHyperHost, filerTo.getUuid()); if (morDsAtSource == null) { morDsAtSource = srcHyperHost.mountDatastore(false, tgtDsNfsHost, tgtDsNfsPort, tgtDsNfsPath, tgtDsName); if (morDsAtSource == null) { throw new Exception("Unable to mount datastore " + tgtDsNfsHost + ":/" + tgtDsNfsPath + " on " + _hostName); } mountedDatastoresAtSource.add(tgtDsName); s_logger.debug("Mounted datastore " + tgtDsNfsHost + ":/" + tgtDsNfsPath + " on " + _hostName); } if (isFirstDs) { relocateSpec.setDatastore(morDsAtSource); isFirstDs = false; } srcDiskName = String.format("[%s] %s.vmdk", srcDsName, volume.getPath()); diskLocator = new VirtualMachineRelocateSpecDiskLocator(); diskLocator.setDatastore(morDsAtSource); diskLocator.setDiskId(getVirtualDiskInfo(vmMo, srcDiskName)); diskLocators.add(diskLocator); } relocateSpec.getDisk().addAll(diskLocators); // Prepare network at target before migration NicTO[] nics = vmTo.getNics(); for (NicTO nic : nics) { // prepare network on the host prepareNetworkFromNicInfo(new HostMO(getServiceContext(), morTgtHost), nic, false, vmTo.getType()); } // Ensure secondary storage mounted on target host String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); if(secStoreUrl == null) { String msg = "secondary storage for dc " + _dcId + " is not ready yet?"; throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; throw new Exception(msg); } // Change datastore if (!vmMo.changeDatastore(relocateSpec)) { throw new Exception("Change datastore operation failed during storage migration"); } else { s_logger.debug("Successfully migrated storage of VM " + vmName + " to target datastore(s)"); } // Change host ManagedObjectReference morPool = tgtHyperHost.getHyperHostOwnerResourcePool(); if (!vmMo.migrate(morPool, tgtHyperHost.getMor())) { throw new Exception("Change datastore operation failed during storage migration"); } else { s_logger.debug("Successfully relocated VM " + vmName + " from " + _hostName + " to " + tgtHyperHost.getHyperHostName()); } state = State.Stopping; List<VolumeObjectTO> volumeToList = null; return new MigrateWithStorageAnswer(cmd, volumeToList); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encountered remote exception at vCenter, invalidating VMware session context"); invalidateServiceContext(); } String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new MigrateWithStorageAnswer(cmd, (Exception) e); } finally { // Cleanup datastores mounted on source host for(String mountedDatastore : mountedDatastoresAtSource) { s_logger.debug("Attempting to unmount datastore " + mountedDatastore + " at " + _hostName); try { srcHyperHost.unmountDatastore(mountedDatastore); } catch (Exception unmountEx) { s_logger.debug("Failed to unmount datastore " + mountedDatastore + " at " + _hostName + ". Seems the datastore is still being used by " + _hostName + ". Please unmount manually to cleanup."); } s_logger.debug("Successfully unmounted datastore " + mountedDatastore + " at " + _hostName); } synchronized (_vms) { _vms.put(vmName, state); } } } private Answer execute(MigrateVolumeCommand cmd) { String volumePath = cmd.getVolumePath(); StorageFilerTO poolTo = cmd.getPool(); if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MigrateVolumeCommand: " + _gson.toJson(cmd)); } final String vmName = volMgr.getVmNameFromVolumeId(cmd.getVolumeId()); VirtualMachineMO vmMo = null; VmwareHypervisorHost srcHyperHost = null; ManagedObjectReference morDs = null; ManagedObjectReference morDc = null; VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec(); List<VirtualMachineRelocateSpecDiskLocator> diskLocators = new ArrayList<VirtualMachineRelocateSpecDiskLocator>(); VirtualMachineRelocateSpecDiskLocator diskLocator = null; String srcDiskName = ""; String srcDsName = ""; String tgtDsName = ""; try { srcHyperHost = getHyperHost(getServiceContext()); morDc = srcHyperHost.getHyperHostDatacenter(); srcDsName = volMgr.getStoragePoolOfVolume(cmd.getVolumeId()); tgtDsName = poolTo.getUuid().replace("-", ""); // find VM through datacenter (VM is not at the target host yet) vmMo = srcHyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter " + morDc.getValue(); s_logger.error(msg); throw new Exception(msg); } morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(srcHyperHost, tgtDsName); if (morDs == null) { String msg = "Unable to find the mounted datastore with name " + tgtDsName + " to execute MigrateVolumeCommand"; s_logger.error(msg); throw new Exception(msg); } srcDiskName = String.format("[%s] %s.vmdk", srcDsName, volumePath); diskLocator = new VirtualMachineRelocateSpecDiskLocator(); diskLocator.setDatastore(morDs); diskLocator.setDiskId(getVirtualDiskInfo(vmMo, srcDiskName)); diskLocators.add(diskLocator); relocateSpec.getDisk().add(diskLocator); // Change datastore if (!vmMo.changeDatastore(relocateSpec)) { throw new Exception("Change datastore operation failed during volume migration"); } else { s_logger.debug("Successfully migrated volume " + volumePath + " to target datastore " + tgtDsName); } return new MigrateVolumeAnswer(cmd, true, null, volumePath); } catch (Exception e) { String msg = "Catch Exception " + e.getClass().getName() + " due to " + e.toString(); s_logger.error(msg, e); return new MigrateVolumeAnswer(cmd, false, msg, null); } } private int getVirtualDiskInfo(VirtualMachineMO vmMo, String srcDiskName) throws Exception { Pair<VirtualDisk, String> deviceInfo = vmMo.getDiskDevice(srcDiskName, false); if(deviceInfo == null) { throw new Exception("No such disk device: " + srcDiskName); } return deviceInfo.first().getKey(); } private VmwareHypervisorHost getTargetHyperHost(DatacenterMO dcMo, String destIp) throws Exception { VmwareManager mgr = dcMo.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); List<ObjectContent> ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" }); if (ocs != null && ocs.size() > 0) { for (ObjectContent oc : ocs) { HostMO hostMo = new HostMO(dcMo.getContext(), oc.getObj()); VmwareHypervisorHostNetworkSummary netSummary = hostMo.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost(hostMo)); if (destIp.equalsIgnoreCase(netSummary.getHostIp())) { return new HostMO(dcMo.getContext(), oc.getObj()); } } } throw new Exception("Unable to locate dest host by " + destIp); } protected Answer execute(CreateStoragePoolCommand cmd) { return new Answer(cmd, true, "success"); } protected Answer execute(ModifyStoragePoolCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ModifyStoragePoolCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); StorageFilerTO pool = cmd.getPool(); if (pool.getType() != StoragePoolType.NetworkFilesystem && pool.getType() != StoragePoolType.VMFS) { throw new Exception("Unsupported storage pool type " + pool.getType()); } ManagedObjectReference morDatastore = null; morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, pool.getUuid()); if(morDatastore == null) morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), pool.getPort(), pool.getPath(), pool.getUuid().replace("-", "")); assert (morDatastore != null); DatastoreSummary summary = new DatastoreMO(getServiceContext(), morDatastore).getSummary(); long capacity = summary.getCapacity(); long available = summary.getFreeSpace(); Map<String, TemplateProp> tInfo = new HashMap<String, TemplateProp>(); ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo); return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "ModifyStoragePoolCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } } protected Answer execute(DeleteStoragePoolCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DeleteStoragePoolCommand: " + _gson.toJson(cmd)); } StorageFilerTO pool = cmd.getPool(); try { // We will leave datastore cleanup management to vCenter. Since for cluster VMFS datastore, it will always // be mounted by vCenter. // VmwareHypervisorHost hyperHost = this.getHyperHost(getServiceContext()); // hyperHost.unmountDatastore(pool.getUuid()); Answer answer = new Answer(cmd, true, "success"); return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "DeleteStoragePoolCommand (pool: " + pool.getHost() + ", path: " + pool.getPath() + ") failed due to " + VmwareHelper.getExceptionMessage(e); return new Answer(cmd, false, msg); } } public static String getDatastoreName(String str) { return str.replace('/', '-'); } // This methd can be used to determine if the datastore is active yet. // When an iSCSI target is created on a host and that target already contains // the metadata that represents a datastore, the datastore shows up within // vCenter as existent, but not necessarily active. // Call this method and pass in the datastore's name to wait, if necessary, // for the datastore to become active. private boolean datastoreFileExists(DatastoreMO dsMo, String volumeDatastorePath) { for (int i = 0; i < 10; i++) { try { return dsMo.fileExists(volumeDatastorePath); } catch (Exception e) { if (!e.getMessage().contains("is not accessible")) { break; } } try { Thread.sleep(5000); } catch (Exception e) { } } return false; } public ManagedObjectReference handleDatastoreAndVmdkAttach(Command cmd, String iqn, String storageHost, int storagePort, String initiatorUsername, String initiatorPassword, String targetUsername, String targetPassword) throws Exception { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); ManagedObjectReference morDs = createVmfsDatastore(hyperHost, getDatastoreName(iqn), storageHost, storagePort, iqn, initiatorUsername, initiatorPassword, targetUsername, targetPassword); DatastoreMO dsMo = new DatastoreMO(context, morDs); String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), dsMo.getName()); if (!dsMo.fileExists(volumeDatastorePath)) { String dummyVmName = getWorkerName(context, cmd, 0); VirtualMachineMO vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); if (vmMo == null) { throw new Exception("Unable to create a dummy VM for volume creation"); } vmMo.createDisk(volumeDatastorePath, getMBsFromBytes(dsMo.getSummary().getFreeSpace()), morDs, vmMo.getScsiDeviceControllerKey()); vmMo.detachDisk(volumeDatastorePath, false); vmMo.destroy(); } return morDs; } public void handleDatastoreAndVmdkDetach(String iqn, String storageHost, int storagePort) throws Exception { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); deleteVmfsDatastore(hyperHost, getDatastoreName(iqn), storageHost, storagePort, iqn); } protected Answer execute(AttachVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource AttachVolumeCommand: " + _gson.toJson(cmd)); } /* * AttachVolumeCommand { "attach":true,"vmName":"i-2-1-KY","pooltype":"NetworkFilesystem", * "volumeFolder":"/export/home/kelven/vmware-test/primary", "volumePath":"uuid", * "volumeName":"volume name","deviceId":1 } */ try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo == null) { String msg = "Unable to find the VM to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } ManagedObjectReference morDs = null; if (cmd.getAttach() && cmd.isManaged()) { morDs = handleDatastoreAndVmdkAttach(cmd, cmd.get_iScsiName(), cmd.getStorageHost(), cmd.getStoragePort(), cmd.getChapInitiatorUsername(), cmd.getChapInitiatorPassword(), cmd.getChapTargetUsername(), cmd.getChapTargetPassword()); } else { morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, cmd.getPoolUuid()); } if (morDs == null) { String msg = "Unable to find the mounted datastore to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); String datastoreVolumePath = dsMo.searchFileInSubFolders(cmd.getVolumePath() + ".vmdk", true); assert (datastoreVolumePath != null) : "Virtual disk file must exist in specified datastore for attach/detach operations."; AttachVolumeAnswer answer = new AttachVolumeAnswer(cmd, cmd.getDeviceId(), datastoreVolumePath); if (cmd.getAttach()) { vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs); } else { vmMo.removeAllSnapshots(); vmMo.detachDisk(datastoreVolumePath, false); if (cmd.isManaged()) { handleDatastoreAndVmdkDetach(cmd.get_iScsiName(), cmd.getStorageHost(), cmd.getStoragePort()); } } return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "AttachVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new AttachVolumeAnswer(cmd, msg); } } private void addRemoveInternetScsiTargetsToAllHosts(final boolean add, final List<HostInternetScsiHbaStaticTarget> lstTargets, final List<Pair<ManagedObjectReference, String>> lstHosts) throws Exception { VmwareContext context = getServiceContext(); ExecutorService executorService = Executors.newFixedThreadPool(lstHosts.size()); final List<Exception> exceptions = new ArrayList<Exception>(); for (Pair<ManagedObjectReference, String> hostPair : lstHosts) { HostMO host = new HostMO(context, hostPair.first()); HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO(); boolean iScsiHbaConfigured = false; for (HostHostBusAdapter hba : hostStorageSystem.getStorageDeviceInfo().getHostBusAdapter()) { if (hba instanceof HostInternetScsiHba) { // just finding an instance of HostInternetScsiHba means that we have found at least one configured iSCSI HBA // at least one iSCSI HBA must be configured before a CloudStack user can use this host for iSCSI storage iScsiHbaConfigured = true; final String iScsiHbaDevice = hba.getDevice(); final HostStorageSystemMO hss = hostStorageSystem; executorService.submit(new Thread() { @Override public void run() { try { if (add) { hss.addInternetScsiStaticTargets(iScsiHbaDevice, lstTargets); } else { hss.removeInternetScsiStaticTargets(iScsiHbaDevice, lstTargets); } hss.rescanHba(iScsiHbaDevice); hss.rescanVmfs(); } catch (Exception ex) { synchronized (exceptions) { exceptions.add(ex); } } } }); } } if (!iScsiHbaConfigured) { throw new Exception("An iSCSI HBA must be configured before a host can use iSCSI storage."); } } executorService.shutdown(); if (!executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES)) { throw new Exception("The system timed out before completing the task 'rescanAllHosts'."); } if (exceptions.size() > 0) { throw new Exception(exceptions.get(0).getMessage()); } } private void rescanAllHosts(final List<Pair<ManagedObjectReference, String>> lstHosts) throws Exception { VmwareContext context = getServiceContext(); ExecutorService executorService = Executors.newFixedThreadPool(lstHosts.size()); final List<Exception> exceptions = new ArrayList<Exception>(); for (Pair<ManagedObjectReference, String> hostPair : lstHosts) { HostMO host = new HostMO(context, hostPair.first()); HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO(); boolean iScsiHbaConfigured = false; for (HostHostBusAdapter hba : hostStorageSystem.getStorageDeviceInfo().getHostBusAdapter()) { if (hba instanceof HostInternetScsiHba) { // just finding an instance of HostInternetScsiHba means that we have found at least one configured iSCSI HBA // at least one iSCSI HBA must be configured before a CloudStack user can use this host for iSCSI storage iScsiHbaConfigured = true; final String iScsiHbaDevice = hba.getDevice(); final HostStorageSystemMO hss = hostStorageSystem; executorService.submit(new Thread() { @Override public void run() { try { hss.rescanHba(iScsiHbaDevice); hss.rescanVmfs(); } catch (Exception ex) { synchronized (exceptions) { exceptions.add(ex); } } } }); } } if (!iScsiHbaConfigured) { throw new Exception("An iSCSI HBA must be configured before a host can use iSCSI storage."); } } executorService.shutdown(); if (!executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES)) { throw new Exception("The system timed out before completing the task 'rescanAllHosts'."); } if (exceptions.size() > 0) { throw new Exception(exceptions.get(0).getMessage()); } } private ManagedObjectReference createVmfsDatastore(VmwareHypervisorHost hyperHost, String datastoreName, String storageIpAddress, int storagePortNumber, String iqn, String chapName, String chapSecret, String mutualChapName, String mutualChapSecret) throws Exception { VmwareContext context = getServiceContext(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO cluster = new ClusterMO(context, morCluster); List<Pair<ManagedObjectReference, String>> lstHosts = cluster.getClusterHosts(); HostInternetScsiHbaStaticTarget target = new HostInternetScsiHbaStaticTarget(); target.setAddress(storageIpAddress); target.setPort(storagePortNumber); target.setIScsiName(iqn); HostInternetScsiHbaAuthenticationProperties auth = new HostInternetScsiHbaAuthenticationProperties(); String strAuthType = "chapRequired"; auth.setChapAuthEnabled(true); auth.setChapInherited(false); auth.setChapAuthenticationType(strAuthType); auth.setChapName(chapName); auth.setChapSecret(chapSecret); auth.setMutualChapInherited(false); auth.setMutualChapAuthenticationType(strAuthType); auth.setMutualChapName(mutualChapName); auth.setMutualChapSecret(mutualChapSecret); target.setAuthenticationProperties(auth); final List<HostInternetScsiHbaStaticTarget> lstTargets = new ArrayList<HostInternetScsiHbaStaticTarget>(); lstTargets.add(target); addRemoveInternetScsiTargetsToAllHosts(true, lstTargets, lstHosts); rescanAllHosts(lstHosts); HostMO host = new HostMO(context, lstHosts.get(0).first()); HostDatastoreSystemMO hostDatastoreSystem = host.getHostDatastoreSystemMO(); ManagedObjectReference morDs = hostDatastoreSystem.findDatastoreByName(datastoreName); if (morDs != null) { return morDs; } rescanAllHosts(lstHosts); HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO(); List<HostScsiDisk> lstHostScsiDisks = hostDatastoreSystem.queryAvailableDisksForVmfs(); HostScsiDisk hostScsiDisk = getHostScsiDisk(hostStorageSystem.getStorageDeviceInfo().getScsiTopology(), lstHostScsiDisks, iqn); if (hostScsiDisk == null) { // check to see if the datastore actually does exist already morDs = hostDatastoreSystem.findDatastoreByName(datastoreName); if (morDs != null) { return morDs; } throw new Exception("A relevant SCSI disk could not be located to use to create a datastore."); } morDs = hostDatastoreSystem.createVmfsDatastore(datastoreName, hostScsiDisk); if (morDs != null) { rescanAllHosts(lstHosts); return morDs; } throw new Exception("Unable to create a datastore"); } // the purpose of this method is to find the HostScsiDisk in the passed-in array that exists (if any) because // we added the static iqn to an iSCSI HBA private static HostScsiDisk getHostScsiDisk(HostScsiTopology hst, List<HostScsiDisk> lstHostScsiDisks, String iqn) { for (HostScsiTopologyInterface adapter : hst.getAdapter()) { if (adapter.getTarget() != null) { for (HostScsiTopologyTarget target : adapter.getTarget()) { if (target.getTransport() instanceof HostInternetScsiTargetTransport) { String iScsiName = ((HostInternetScsiTargetTransport)target.getTransport()).getIScsiName(); if (iqn.equals(iScsiName)) { for (HostScsiDisk hostScsiDisk : lstHostScsiDisks) { for (HostScsiTopologyLun hstl : target.getLun()) { if (hstl.getScsiLun().contains(hostScsiDisk.getUuid())) { return hostScsiDisk; } } } } } } } } return null; } private void deleteVmfsDatastore(VmwareHypervisorHost hyperHost, String volumeUuid, String storageIpAddress, int storagePortNumber, String iqn) throws Exception { // hyperHost.unmountDatastore(volumeUuid); VmwareContext context = getServiceContext(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO cluster = new ClusterMO(context, morCluster); List<Pair<ManagedObjectReference, String>> lstHosts = cluster.getClusterHosts(); HostInternetScsiHbaStaticTarget target = new HostInternetScsiHbaStaticTarget(); target.setAddress(storageIpAddress); target.setPort(storagePortNumber); target.setIScsiName(iqn); final List<HostInternetScsiHbaStaticTarget> lstTargets = new ArrayList<HostInternetScsiHbaStaticTarget>(); lstTargets.add(target); addRemoveInternetScsiTargetsToAllHosts(false, lstTargets, lstHosts); rescanAllHosts(lstHosts); } protected Answer execute(AttachIsoCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource AttachIsoCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo == null) { String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } String storeUrl = cmd.getStoreUrl(); if (storeUrl == null) { if (!cmd.getIsoPath().equalsIgnoreCase("vmware-tools.iso")) { String msg = "ISO store root url is not found in AttachIsoCommand"; s_logger.error(msg); throw new Exception(msg); } else { if (cmd.isAttach()) { vmMo.mountToolsInstaller(); } else { try{ vmMo.unmountToolsInstaller(); }catch(Throwable e){ vmMo.detachIso(null); } } return new Answer(cmd); } } ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl); String isoPath = cmd.getIsoPath(); if (!isoPath.startsWith(storeUrl)) { assert (false); String msg = "ISO path does not start with the secondary storage root"; s_logger.error(msg); throw new Exception(msg); } int isoNameStartPos = isoPath.lastIndexOf('/'); String isoFileName = isoPath.substring(isoNameStartPos + 1); String isoStorePathFromRoot = isoPath.substring(storeUrl.length(), isoNameStartPos); // TODO, check if iso is already attached, or if there is a previous // attachment DatastoreMO secondaryDsMo = new DatastoreMO(getServiceContext(), morSecondaryDs); String storeName = secondaryDsMo.getName(); String isoDatastorePath = String.format("[%s] %s%s", storeName, isoStorePathFromRoot, isoFileName); if (cmd.isAttach()) { vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false); } else { vmMo.detachIso(isoDatastorePath); } return new Answer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } if(cmd.isAttach()) { String msg = "AttachIsoCommand(attach) failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } else { String msg = "AttachIsoCommand(detach) failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } } public synchronized ManagedObjectReference prepareSecondaryDatastoreOnHost(String storeUrl) throws Exception { String storeName = getSecondaryDatastoreUUID(storeUrl); URI uri = new URI(storeUrl); VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ManagedObjectReference morDatastore = hyperHost.mountDatastore(false, uri.getHost(), 0, uri.getPath(), storeName.replace("-", "")); if (morDatastore == null) throw new Exception("Unable to mount secondary storage on host. storeUrl: " + storeUrl); return morDatastore; } private static String getSecondaryDatastoreUUID(String storeUrl) { return UUID.nameUUIDFromBytes(storeUrl.getBytes()).toString(); } protected Answer execute(ValidateSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ValidateSnapshotCommand: " + _gson.toJson(cmd)); } // the command is no longer available String expectedSnapshotBackupUuid = null; String actualSnapshotBackupUuid = null; String actualSnapshotUuid = null; return new ValidateSnapshotAnswer(cmd, false, "ValidateSnapshotCommand is not supported for vmware yet", expectedSnapshotBackupUuid, actualSnapshotBackupUuid, actualSnapshotUuid); } protected Answer execute(ManageSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ManageSnapshotCommand: " + _gson.toJson(cmd)); } long snapshotId = cmd.getSnapshotId(); /* * "ManageSnapshotCommand", * "{\"_commandSwitch\":\"-c\",\"_volumePath\":\"i-2-3-KY-ROOT\",\"_snapshotName\":\"i-2-3-KY_i-2-3-KY-ROOT_20101102203827\",\"_snapshotId\":1,\"_vmName\":\"i-2-3-KY\"}" */ boolean success = false; String cmdSwitch = cmd.getCommandSwitch(); String snapshotOp = "Unsupported snapshot command." + cmdSwitch; if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { snapshotOp = "create"; } else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { snapshotOp = "destroy"; } String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId; String snapshotUUID = null; // snapshot operation (create or destroy) is handled inside BackupSnapshotCommand(), we just fake // a success return here snapshotUUID = UUID.randomUUID().toString(); success = true; details = null; return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details); } protected Answer execute(BackupSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource BackupSnapshotCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "BackupSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); return new BackupSnapshotAnswer(cmd, false, details, null, true); } } protected Answer execute(CreateVMSnapshotCommand cmd) { try { VmwareContext context = getServiceContext(); VmwareManager mgr = context .getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Exception e) { e.printStackTrace(); return new CreateVMSnapshotAnswer(cmd, false, ""); } } protected Answer execute(DeleteVMSnapshotCommand cmd) { try { VmwareContext context = getServiceContext(); VmwareManager mgr = context .getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Exception e) { e.printStackTrace(); return new DeleteVMSnapshotAnswer(cmd, false, ""); } } protected Answer execute(RevertToVMSnapshotCommand cmd){ try{ VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); }catch (Exception e){ e.printStackTrace(); return new RevertToVMSnapshotAnswer(cmd,false,""); } } protected Answer execute(CreateVolumeFromSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreateVolumeFromSnapshotCommand: " + _gson.toJson(cmd)); } String details = null; boolean success = false; String newVolumeName = UUID.randomUUID().toString(); try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } details = "CreateVolumeFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); } return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName); } protected Answer execute(CreatePrivateTemplateFromVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreatePrivateTemplateFromVolumeCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "CreatePrivateTemplateFromVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); return new CreatePrivateTemplateAnswer(cmd, false, details); } } protected Answer execute(final UpgradeSnapshotCommand cmd) { return new Answer(cmd, true, "success"); } protected Answer execute(CreatePrivateTemplateFromSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreatePrivateTemplateFromSnapshotCommand: " + _gson.toJson(cmd)); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "CreatePrivateTemplateFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); return new CreatePrivateTemplateAnswer(cmd, false, details); } } protected Answer execute(GetStorageStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetStorageStatsCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, cmd.getStorageId()); if (morDs != null) { DatastoreMO datastoreMo = new DatastoreMO(context, morDs); DatastoreSummary summary = datastoreMo.getSummary(); assert (summary != null); long capacity = summary.getCapacity(); long free = summary.getFreeSpace(); long used = capacity - free; if (s_logger.isDebugEnabled()) { s_logger.debug("Datastore summary info, storageId: " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ", capacity: " + capacity + ", free: " + free + ", used: " + used); } if (summary.getCapacity() <= 0) { s_logger.warn("Something is wrong with vSphere NFS datastore, rebooting ESX(ESXi) host should help"); } return new GetStorageStatsAnswer(cmd, capacity, used); } else { String msg = "Could not find datastore for GetStorageStatsCommand storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype(); s_logger.error(msg); return new GetStorageStatsAnswer(cmd, msg); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unable to execute GetStorageStatsCommand(storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ") due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new GetStorageStatsAnswer(cmd, msg); } } protected Answer execute(GetVncPortCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetVncPortCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); assert(hyperHost instanceof HostMO); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getName()); if (vmMo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the owner VM for GetVncPortCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter"); } vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getName()); if (vmMo == null) { throw new Exception("Unable to find VM in vSphere, vm: " + cmd.getName()); } } Pair<String, Integer> portInfo = vmMo.getVncPort(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); if (s_logger.isTraceEnabled()) { s_logger.trace("Found vnc port info. vm: " + cmd.getName() + " host: " + portInfo.first() + ", vnc port: " + portInfo.second()); } return new GetVncPortAnswer(cmd, portInfo.first(), portInfo.second()); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "GetVncPortCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new GetVncPortAnswer(cmd, msg); } } protected Answer execute(SetupCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetupCommand: " + _gson.toJson(cmd)); } return new SetupAnswer(cmd, false); } protected Answer execute(MaintainCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MaintainCommand: " + _gson.toJson(cmd)); } return new MaintainAnswer(cmd, "Put host in maintaince"); } protected Answer execute(PingTestCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PingTestCommand: " + _gson.toJson(cmd)); } String controlIp = cmd.getRouterIp(); String args = " -c 1 -n -q " + cmd.getPrivateIp(); try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/bin/ping" + args); if(result.first()) return new Answer(cmd); } catch (Exception e) { s_logger.error("Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return new Answer(cmd,false,"PingTestCommand failed"); } protected Answer execute(CheckOnHostCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckOnHostCommand: " + _gson.toJson(cmd)); } return new CheckOnHostAnswer(cmd, null, "Not Implmeneted"); } protected Answer execute(ModifySshKeysCommand cmd) { //do not log the command contents for this command. do NOT log the ssh keys if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ModifySshKeysCommand."); } return new Answer(cmd); } protected Answer execute(PoolEjectCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PoolEjectCommand: " + _gson.toJson(cmd)); } return new Answer(cmd, false, "PoolEjectCommand is not available for vmware"); } @Override public PrimaryStorageDownloadAnswer execute(PrimaryStorageDownloadCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PrimaryStorageDownloadCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return (PrimaryStorageDownloadAnswer) mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "PrimaryStorageDownloadCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new PrimaryStorageDownloadAnswer(msg); } } protected Answer execute(PvlanSetupCommand cmd) { // Pvlan related operations are performed in the start/stop command paths // for vmware. This function is implemented to support mgmt layer code // that issue this command. Note that pvlan operations are supported only // in Distributed Virtual Switch environments for vmware deployments. return new Answer(cmd, true, "success"); } protected Answer execute(UnregisterVMCommand cmd){ if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource UnregisterVMCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { try { context.getService().unregisterVM(vmMo.getMor()); return new Answer(cmd, true, "unregister succeeded"); } catch(Exception e) { s_logger.warn("We are not able to unregister VM " + VmwareHelper.getExceptionMessage(e)); } String msg = "Expunge failed in vSphere. vm: " + cmd.getVmName(); s_logger.warn(msg); return new Answer(cmd, false, msg); } else { String msg = "Unable to find the VM in vSphere to unregister, assume it is already removed. VM: " + cmd.getVmName(); s_logger.warn(msg); return new Answer(cmd, true, msg); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "UnregisterVMCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } } /** * UnregisterNicCommand is used to remove a portgroup created for this * specific nic. The portgroup will have the name set to the UUID of the * nic. Introduced to cleanup the portgroups created for each nic that is * plugged into an lswitch (Nicira NVP plugin) * * @param cmd * @return */ protected Answer execute(UnregisterNicCommand cmd) { s_logger.info("Executing resource UnregisterNicCommand: " + _gson.toJson(cmd)); if (_guestTrafficInfo == null) { return new Answer(cmd, false, "No Guest Traffic Info found, unable to determine where to clean up"); } try { if (_guestTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch) { // For now we only need to cleanup the nvp specific portgroups // on the standard switches return new Answer(cmd, true, "Nothing to do"); } s_logger.debug("Cleaning up portgroup " + cmd.getNicUuid() + " on switch " + _guestTrafficInfo.getVirtualSwitchName()); VmwareContext context = getServiceContext(); VmwareHypervisorHost host = getHyperHost(context); ManagedObjectReference clusterMO = host.getHyperHostCluster(); // Get a list of all the hosts in this cluster @SuppressWarnings("unchecked") List<ManagedObjectReference> hosts = (List<ManagedObjectReference>) context.getVimClient() .getDynamicProperty(clusterMO, "host"); if (hosts == null) { return new Answer(cmd, false, "No hosts in cluster, which is pretty weird"); } for (ManagedObjectReference hostMOR : hosts) { HostMO hostMo = new HostMO(context, hostMOR); hostMo.deletePortGroup(cmd.getNicUuid().toString()); s_logger.debug("Removed portgroup " + cmd.getNicUuid() + " from host " + hostMo.getHostName()); } return new Answer(cmd, true, "Unregistered resources for NIC " + cmd.getNicUuid()); } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "UnregisterVMCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } } public Answer execute(DeleteCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DestroyCommand: " + _gson.toJson(cmd)); } /* * DestroyCommand content exafmple * * {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary", * "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType": * "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } } * * {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary", * "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem", * "poolId":0,"deviceId":0 } } */ try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); VolumeObjectTO vol = (VolumeObjectTO)cmd.getData(); PrimaryDataStoreTO store = (PrimaryDataStoreTO)vol.getDataStore(); ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, store.getUuid()); if (morDs == null) { String msg = "Unable to find datastore based on volume mount point " + store.getPath(); s_logger.error(msg); throw new Exception(msg); } DatastoreMO dsMo = new DatastoreMO(context, morDs); ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO clusterMo = new ClusterMO(context, morCluster); if (vol.getVolumeType() == Volume.Type.ROOT) { String vmName = vol.getVmName(); if (vmName != null) { VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName); if (vmMo != null) { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy root volume and VM itself. vmName " + vmName); } HostMO hostMo = vmMo.getRunningHost(); List<NetworkDetails> networks = vmMo.getNetworksWithDetails(); // tear down all devices first before we destroy the VM to avoid accidently delete disk backing files if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.destroy(); for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { cleanupNetwork(hostMo, netDetails); } } } } if (s_logger.isInfoEnabled()) s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk"); dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true); // root volume may be created via linked-clone, delete the delta disk as well if (_fullCloneFlag) { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk"); } dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true); } else { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-delta.vmdk"); } dsMo.deleteFile(vol.getPath() + "-delta.vmdk", morDc, true); } return new Answer(cmd, true, "Success"); } if (s_logger.isInfoEnabled()) { s_logger.info("Destroy root volume directly from datastore"); } } else { // evitTemplate will be converted into DestroyCommand, test if we are running in this case VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vol.getPath()); if (vmMo != null) { if (s_logger.isInfoEnabled()) s_logger.info("Destroy template volume " + vol.getPath()); vmMo.destroy(); return new Answer(cmd, true, "Success"); } } String chainInfo = vol.getChainInfo(); if (chainInfo != null && !chainInfo.isEmpty()) { s_logger.info("Destroy volume by chain info: " + chainInfo); String[] diskChain = _gson.fromJson(chainInfo, String[].class); if (diskChain != null && diskChain.length > 0) { for (String backingName : diskChain) { if (s_logger.isInfoEnabled()) { s_logger.info("Delete volume backing file: " + backingName); } dsMo.deleteFile(backingName, morDc, true); } } else { if (s_logger.isInfoEnabled()) { s_logger.info("Empty disk chain info, fall back to try to delete by original backing file name"); } dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true); if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk"); } dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true); } } else { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk"); } dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true); if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk"); } dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true); } return new Answer(cmd, true, "Success"); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "DestroyCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } } public void cleanupNetwork(HostMO hostMo, NetworkDetails netDetails) { // we will no longer cleanup VLAN networks in order to support native VMware HA /* * assert(netDetails.getName() != null); try { synchronized(this) { NetworkMO networkMo = new * NetworkMO(hostMo.getContext(), netDetails.getNetworkMor()); ManagedObjectReference[] vms = * networkMo.getVMsOnNetwork(); if(vms == null || vms.length == 0) { if(s_logger.isInfoEnabled()) { * s_logger.info("Cleanup network as it is currently not in use: " + netDetails.getName()); } * * hostMo.deletePortGroup(netDetails.getName()); } } } catch(Throwable e) { * s_logger.warn("Unable to cleanup network due to exception, skip for next time"); } */ } @Override public CopyVolumeAnswer execute(CopyVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CopyVolumeCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return (CopyVolumeAnswer) mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "CopyVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CopyVolumeAnswer(cmd, false, msg, null, null); } } @Override public CreateVolumeOVAAnswer execute(CreateVolumeOVACommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreateVolumeOVACommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return (CreateVolumeOVAAnswer) mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "CreateVolumeOVACommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CreateVolumeOVAAnswer(cmd, false, msg); } } protected Answer execute(PrepareOVAPackingCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PrepareOVAPackingCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "PrepareOVAPacking for template failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); return new PrepareOVAPackingAnswer(cmd, false, details); } } private boolean createVMFullClone(VirtualMachineMO vmTemplate, DatacenterMO dcMo, DatastoreMO dsMo, String vmdkName, ManagedObjectReference morDatastore, ManagedObjectReference morPool) throws Exception { if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName)) dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false); s_logger.info("creating full clone from template"); if (!vmTemplate.createFullClone(vmdkName, dcMo.getVmFolder(), morPool, morDatastore)) { String msg = "Unable to create full clone from the template"; s_logger.error(msg); throw new Exception(msg); } // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know // to move files s_logger.info("Move volume out of volume-wrapper VM "); dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); dsMo.moveDatastoreFile(String.format("[%s] %s/%s-flat.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s-flat.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); return true; } private boolean createVMLinkedClone(VirtualMachineMO vmTemplate, DatacenterMO dcMo, DatastoreMO dsMo, String vmdkName, ManagedObjectReference morDatastore, ManagedObjectReference morPool) throws Exception { ManagedObjectReference morBaseSnapshot = vmTemplate.getSnapshotMor("cloud.template.base"); if (morBaseSnapshot == null) { String msg = "Unable to find template base snapshot, invalid template"; s_logger.error(msg); throw new Exception(msg); } if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName)) dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false); s_logger.info("creating linked clone from template"); if (!vmTemplate.createLinkedClone(vmdkName, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) { String msg = "Unable to clone from the template"; s_logger.error(msg); throw new Exception(msg); } // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know // to move files s_logger.info("Move volume out of volume-wrapper VM "); dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s-delta.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); return true; } @Override public synchronized CreateAnswer execute(CreateCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreateCommand: " + _gson.toJson(cmd)); } StorageFilerTO pool = cmd.getPool(); DiskProfile dskch = cmd.getDiskCharacteristics(); try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, pool.getUuid()); if (morDatastore == null) throw new Exception("Unable to find datastore in vSphere"); DatastoreMO dsMo = new DatastoreMO(context, morDatastore); if (dskch.getType() == Volume.Type.ROOT) { // attach volume id to make the name unique String vmdkName = dskch.getName() + "-" + dskch.getVolumeId(); if (cmd.getTemplateUrl() == null) { // create a root volume for blank VM String dummyVmName = getWorkerName(context, cmd, 0); VirtualMachineMO vmMo = null; try { vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); if (vmMo == null) { throw new Exception("Unable to create a dummy VM for volume creation"); } String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName); synchronized (this) { s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); VmwareHelper.deleteVolumeVmdkFiles(dsMo, vmdkName, dcMo); vmMo.createDisk(volumeDatastorePath, getMBsFromBytes(dskch.getSize()), morDatastore, -1); vmMo.detachDisk(volumeDatastorePath, false); } VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } finally { vmMo.detachAllDisks(); s_logger.info("Destroy dummy VM after volume creation"); vmMo.destroy(); } } else { VirtualMachineMO vmTemplate = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(cmd.getTemplateUrl()), true); if (vmTemplate == null) { s_logger.warn("Template host in vSphere is not in connected state, request template reload"); return new CreateAnswer(cmd, "Template host in vSphere is not in connected state, request template reload", true); } ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); //createVMLinkedClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool); if (!_fullCloneFlag) { createVMLinkedClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool); } else { createVMFullClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool); } VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(vmdkName); assert (vmMo != null); s_logger.info("detach disks from volume-wrapper VM " + vmdkName); vmMo.detachAllDisks(); s_logger.info("destroy volume-wrapper VM " + vmdkName); vmMo.destroy(); String srcFile = String.format("[%s] %s/", dsMo.getName(), vmdkName); dsMo.deleteFile(srcFile, dcMo.getMor(), true); VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } } else { // create data volume VirtualMachineMO vmMo = null; String volumeUuid = UUID.randomUUID().toString().replace("-", ""); String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumeUuid); String dummyVmName = getWorkerName(context, cmd, 0); try { vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); if (vmMo == null) { throw new Exception("Unable to create a dummy VM for volume creation"); } synchronized (this) { // s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); VmwareHelper.deleteVolumeVmdkFiles(dsMo, volumeUuid.toString(), dcMo); vmMo.createDisk(volumeDatastorePath, getMBsFromBytes(dskch.getSize()), morDatastore, vmMo.getScsiDeviceControllerKey()); vmMo.detachDisk(volumeDatastorePath, false); } VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), volumeUuid, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } finally { s_logger.info("Destroy dummy VM after volume creation"); vmMo.detachAllDisks(); vmMo.destroy(); } } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "CreateCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CreateAnswer(cmd, new Exception(e)); } } private static int getMBsFromBytes(long bytes) { return (int)(bytes / (1024L * 1024L)); } protected VirtualMachineMO prepareVolumeHostDummyVm(VmwareHypervisorHost hyperHost, DatastoreMO dsMo, String vmName) throws Exception { assert (hyperHost != null); VirtualMachineMO vmMo = null; VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); vmConfig.setName(vmName); vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB vmConfig.setNumCPUs(1); vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.value()); VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); vmConfig.setFiles(fileInfo); // Scsi controller VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING); scsiController.setBusNumber(0); scsiController.setKey(1); VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); scsiControllerSpec.setDevice(scsiController); scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); vmConfig.getDeviceChange().add(scsiControllerSpec ); hyperHost.createVm(vmConfig); vmMo = hyperHost.findVmOnHyperHost(vmName); return vmMo; } @Override public void disconnected() { } @Override public IAgentControl getAgentControl() { return null; } @Override public PingCommand getCurrentStatus(long id) { HashMap<String, State> newStates = sync(); if (newStates == null) { return null; } try { // take the chance to do left-over dummy VM cleanup from previous run VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if(hyperHost.isHyperHostConnected()) { mgr.gcLeftOverVMs(context); if(_recycleHungWorker) { s_logger.info("Scan hung worker VM to recycle"); // GC worker that has been running for too long ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost( new String[] {"name", "config.template", "runtime.powerState", "runtime.bootTime"}); if(ocs != null) { for(ObjectContent oc : ocs) { List<DynamicProperty> props = oc.getPropSet(); if(props != null) { String name = null; boolean template = false; VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF; GregorianCalendar bootTime = null; for(DynamicProperty prop : props) { if(prop.getName().equals("name")) name = prop.getVal().toString(); else if(prop.getName().equals("config.template")) template = (Boolean)prop.getVal(); else if(prop.getName().equals("runtime.powerState")) powerState = (VirtualMachinePowerState)prop.getVal(); else if(prop.getName().equals("runtime.bootTime")) bootTime = (GregorianCalendar)prop.getVal(); } if(!template && name.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { boolean recycle = false; // recycle stopped worker VM and VM that has been running for too long (hard-coded 10 hours for now) if(powerState == VirtualMachinePowerState.POWERED_OFF) recycle = true; else if(bootTime != null && (new Date().getTime() - bootTime.getTimeInMillis() > 10*3600*1000)) recycle = true; if(recycle) { s_logger.info("Recycle pending worker VM: " + name); VirtualMachineMO vmMo = new VirtualMachineMO(hyperHost.getContext(), oc.getObj()); vmMo.powerOff(); vmMo.destroy(); } } } } } } } else { s_logger.error("Host is no longer connected."); return null; } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); return null; } } return new PingRoutingCommand(getType(), id, newStates); } @Override public Type getType() { return com.cloud.host.Host.Type.Routing; } @Override public StartupCommand[] initialize() { String hostApiVersion = "4.1"; VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); assert(hyperHost instanceof HostMO); if(!((HostMO)hyperHost).isHyperHostConnected()) { s_logger.info("Host " + hyperHost.getHyperHostName() + " is not in connected state"); return null; } AboutInfo aboutInfo = ((HostMO)hyperHost).getHostAboutInfo(); hostApiVersion = aboutInfo.getApiVersion(); } catch (Exception e) { String msg = "VmwareResource intialize() failed due to : " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); invalidateServiceContext(); return null; } StartupRoutingCommand cmd = new StartupRoutingCommand(); fillHostInfo(cmd); Map<String, State> changes = null; synchronized (_vms) { _vms.clear(); changes = sync(); } cmd.setHypervisorType(HypervisorType.VMware); cmd.setStateChanges(changes); cmd.setCluster(_cluster); cmd.setHypervisorVersion(hostApiVersion); List<StartupStorageCommand> storageCmds = initializeLocalStorage(); StartupCommand[] answerCmds = new StartupCommand[1 + storageCmds.size()]; answerCmds[0] = cmd; for (int i = 0; i < storageCmds.size(); i++) { answerCmds[i + 1] = storageCmds.get(i); } return answerCmds; } private List<StartupStorageCommand> initializeLocalStorage() { List<StartupStorageCommand> storageCmds = new ArrayList<StartupStorageCommand>(); VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); if (hyperHost instanceof HostMO) { HostMO hostMo = (HostMO) hyperHost; List<Pair<ManagedObjectReference, String>> dsList = hostMo.getLocalDatastoreOnHost(); for (Pair<ManagedObjectReference, String> dsPair : dsList) { DatastoreMO dsMo = new DatastoreMO(context, dsPair.first()); String poolUuid = dsMo.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID); if (poolUuid == null || poolUuid.isEmpty()) { poolUuid = UUID.randomUUID().toString(); dsMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, poolUuid); } DatastoreSummary dsSummary = dsMo.getSummary(); String address = hostMo.getHostName(); StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, dsMo.getMor().getValue(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); StartupStorageCommand cmd = new StartupStorageCommand(); cmd.setName(poolUuid); cmd.setPoolInfo(pInfo); cmd.setGuid(poolUuid); // give storage host the same UUID as the local storage pool itself cmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); cmd.setDataCenter(_dcId); cmd.setPod(_pod); cmd.setCluster(_cluster); s_logger.info("Add local storage startup command: " + _gson.toJson(cmd)); storageCmds.add(cmd); } } else { s_logger.info("Cluster host does not support local storage, skip it"); } } catch (Exception e) { String msg = "initializing local storage failed due to : " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); invalidateServiceContext(); throw new CloudRuntimeException(msg); } return storageCmds; } protected void fillHostInfo(StartupRoutingCommand cmd) { VmwareContext serviceContext = getServiceContext(); Map<String, String> details = cmd.getHostDetails(); if (details == null) { details = new HashMap<String, String>(); } try { fillHostHardwareInfo(serviceContext, cmd); fillHostNetworkInfo(serviceContext, cmd); fillHostDetailsInfo(serviceContext, details); } catch (RuntimeFaultFaultMsg e) { s_logger.error("RuntimeFault while retrieving host info: " + e.toString(), e); throw new CloudRuntimeException("RuntimeFault while retrieving host info"); } catch (RemoteException e) { s_logger.error("RemoteException while retrieving host info: " + e.toString(), e); invalidateServiceContext(); throw new CloudRuntimeException("RemoteException while retrieving host info"); } catch (Exception e) { s_logger.error("Exception while retrieving host info: " + e.toString(), e); invalidateServiceContext(); throw new CloudRuntimeException("Exception while retrieving host info: " + e.toString()); } cmd.setHostDetails(details); cmd.setName(_url); cmd.setGuid(_guid); cmd.setDataCenter(_dcId); cmd.setPod(_pod); cmd.setCluster(_cluster); cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion()); } private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException, Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VmwareHypervisorHostResourceSummary summary = hyperHost.getHyperHostResourceSummary(); if (s_logger.isInfoEnabled()) { s_logger.info("Startup report on host hardware info. " + _gson.toJson(summary)); } cmd.setCaps("hvm"); cmd.setDom0MinMemory(0); cmd.setSpeed(summary.getCpuSpeed()); cmd.setCpus((int) summary.getCpuCount()); cmd.setMemory(summary.getMemoryBytes()); } private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException { try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); assert(hyperHost instanceof HostMO); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VmwareHypervisorHostNetworkSummary summary = hyperHost.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); if (summary == null) { throw new Exception("No ESX(i) host found"); } if (s_logger.isInfoEnabled()) { s_logger.info("Startup report on host network info. " + _gson.toJson(summary)); } cmd.setPrivateIpAddress(summary.getHostIp()); cmd.setPrivateNetmask(summary.getHostNetmask()); cmd.setPrivateMacAddress(summary.getHostMacAddress()); cmd.setStorageIpAddress(summary.getHostIp()); cmd.setStorageNetmask(summary.getHostNetmask()); cmd.setStorageMacAddress(summary.getHostMacAddress()); } catch (Throwable e) { String msg = "querying host network info failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); throw new CloudRuntimeException(msg); } } private void fillHostDetailsInfo(VmwareContext serviceContext, Map<String, String> details) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ClusterDasConfigInfo dasConfig = hyperHost.getDasConfig(); if (dasConfig != null && dasConfig.isEnabled() != null && dasConfig.isEnabled().booleanValue()) { details.put("NativeHA", "true"); } } protected HashMap<String, State> sync() { HashMap<String, State> changes = new HashMap<String, State>(); HashMap<String, State> oldStates = null; try { synchronized (_vms) { HashMap<String, State> newStates = getVmStates(); oldStates = new HashMap<String, State>(_vms.size()); oldStates.putAll(_vms); for (final Map.Entry<String, State> entry : newStates.entrySet()) { final String vm = entry.getKey(); State newState = entry.getValue(); final State oldState = oldStates.remove(vm); if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + vm + ": vSphere has state " + newState + " and we have state " + (oldState != null ? oldState.toString() : "null")); } if (vm.startsWith("migrating")) { s_logger.debug("Migrating detected. Skipping"); continue; } if (oldState == null) { _vms.put(vm, newState); s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm); changes.put(vm, newState); } else if (oldState == State.Starting) { if (newState == State.Running) { _vms.put(vm, newState); } else if (newState == State.Stopped) { s_logger.debug("Ignoring vm " + vm + " because of a lag in starting the vm."); } } else if (oldState == State.Migrating) { if (newState == State.Running) { s_logger.debug("Detected that an migrating VM is now running: " + vm); _vms.put(vm, newState); } } else if (oldState == State.Stopping) { if (newState == State.Stopped) { _vms.put(vm, newState); } else if (newState == State.Running) { s_logger.debug("Ignoring vm " + vm + " because of a lag in stopping the vm. "); } } else if (oldState != newState) { _vms.put(vm, newState); if (newState == State.Stopped) { /* * if (_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. "); * newState = State.Error; } */ } changes.put(vm, newState); } } for (final Map.Entry<String, State> entry : oldStates.entrySet()) { final String vm = entry.getKey(); final State oldState = entry.getValue(); if (isVmInCluster(vm)) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + vm + " is now missing from host report but we detected that it might be migrated to other host by vCenter"); } if(oldState != State.Starting && oldState != State.Migrating) { s_logger.debug("VM " + vm + " is now missing from host report and VM is not at starting/migrating state, remove it from host VM-sync map, oldState: " + oldState); _vms.remove(vm); } else { s_logger.debug("VM " + vm + " is missing from host report, but we will ignore VM " + vm + " in transition state " + oldState); } continue; } if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + vm + " is now missing from host report"); } if (oldState == State.Stopping) { s_logger.debug("Ignoring VM " + vm + " in transition state stopping."); _vms.remove(vm); } else if (oldState == State.Starting) { s_logger.debug("Ignoring VM " + vm + " in transition state starting."); } else if (oldState == State.Stopped) { _vms.remove(vm); } else if (oldState == State.Migrating) { s_logger.debug("Ignoring VM " + vm + " in migrating state."); } else { State state = State.Stopped; changes.put(entry.getKey(), state); } } } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to perform sync information collection process at this point due to " + VmwareHelper.getExceptionMessage(e), e); return null; } return changes; } private boolean isVmInCluster(String vmName) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); return hyperHost.findVmOnPeerHyperHost(vmName) != null; } protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if(!mgr.beginExclusiveOperation(600)) throw new Exception("Unable to begin exclusive operation, lock time out"); try { int maxVncPorts = 64; int vncPort = 0; Random random = new Random(); HostMO vmOwnerHost = vmMo.getRunningHost(); ManagedObjectReference morParent = vmOwnerHost.getParentMor(); HashMap<String, Integer> portInfo; if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) { ClusterMO clusterMo = new ClusterMO(vmOwnerHost.getContext(), morParent); portInfo = clusterMo.getVmVncPortsOnCluster(); } else { portInfo = vmOwnerHost.getVmVncPortsOnHost(); } // allocate first at 5900 - 5964 range Collection<Integer> existingPorts = portInfo.values(); int val = random.nextInt(maxVncPorts); int startVal = val; do { if (!existingPorts.contains(5900 + val)) { vncPort = 5900 + val; break; } val = (++val) % maxVncPorts; } while (val != startVal); if(vncPort == 0) { s_logger.info("we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000"); Pair<Integer, Integer> additionalRange = mgr.getAddiionalVncPortRange(); maxVncPorts = additionalRange.second(); val = random.nextInt(maxVncPorts); startVal = val; do { if (!existingPorts.contains(additionalRange.first() + val)) { vncPort = additionalRange.first() + val; break; } val = (++val) % maxVncPorts; } while (val != startVal); } if (vncPort == 0) { throw new Exception("Unable to find an available VNC port on host"); } if (s_logger.isInfoEnabled()) { s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName()); } return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout); } finally { try { mgr.endExclusiveOperation(); } catch(Throwable e) { assert(false); s_logger.error("Unexpected exception ", e); } } } private VirtualMachineGuestOsIdentifier translateGuestOsIdentifier(String cpuArchitecture, String cloudGuestOs) { if (cpuArchitecture == null) { s_logger.warn("CPU arch is not set, default to i386. guest os: " + cloudGuestOs); cpuArchitecture = "i386"; } VirtualMachineGuestOsIdentifier identifier = VmwareGuestOsMapper.getGuestOsIdentifier(cloudGuestOs); if (identifier != null) { return identifier; } if (cpuArchitecture.equalsIgnoreCase("x86_64")) { return VirtualMachineGuestOsIdentifier.OTHER_GUEST_64; } return VirtualMachineGuestOsIdentifier.OTHER_GUEST; } private HashMap<String, State> getVmStates() throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] { "name", "runtime.powerState", "config.template" }); HashMap<String, State> newStates = new HashMap<String, State>(); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { List<DynamicProperty> objProps = oc.getPropSet(); if (objProps != null) { boolean isTemplate = false; String name = null; VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF; for (DynamicProperty objProp : objProps) { if (objProp.getName().equals("config.template")) { if (objProp.getVal().toString().equalsIgnoreCase("true")) { isTemplate = true; } } else if (objProp.getName().equals("name")) { name = (String) objProp.getVal(); } else if (objProp.getName().equals("runtime.powerState")) { powerState = (VirtualMachinePowerState) objProp.getVal(); } else { assert (false); } } if (!isTemplate) { newStates.put(name, convertState(powerState)); } } } } return newStates; } private HashMap<String, VmStatsEntry> getVmStats(List<String> vmNames) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); HashMap<String, VmStatsEntry> vmResponseMap = new HashMap<String, VmStatsEntry>(); ManagedObjectReference perfMgr = getServiceContext().getServiceContent().getPerfManager(); VimPortType service = getServiceContext().getService(); PerfCounterInfo rxPerfCounterInfo = null; PerfCounterInfo txPerfCounterInfo = null; List<PerfCounterInfo> cInfo = (List<PerfCounterInfo>) getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter"); for(PerfCounterInfo info : cInfo) { if ("net".equalsIgnoreCase(info.getGroupInfo().getKey())) { if ("transmitted".equalsIgnoreCase(info.getNameInfo().getKey())) { txPerfCounterInfo = info; } if ("received".equalsIgnoreCase(info.getNameInfo().getKey())) { rxPerfCounterInfo = info; } } } ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] {"name", "summary.config.numCpu", "summary.quickStats.overallCpuUsage"}); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { List<DynamicProperty> objProps = oc.getPropSet(); if (objProps != null) { String name = null; String numberCPUs = null; String maxCpuUsage = null; for (DynamicProperty objProp : objProps) { if (objProp.getName().equals("name")) { name = objProp.getVal().toString(); } else if (objProp.getName().equals("summary.config.numCpu")) { numberCPUs = objProp.getVal().toString(); } else if (objProp.getName().equals("summary.quickStats.overallCpuUsage")) { maxCpuUsage = objProp.getVal().toString(); } } if (!vmNames.contains(name)) { continue; } ManagedObjectReference vmMor = hyperHost.findVmOnHyperHost(name).getMor(); assert(vmMor!=null); ArrayList vmNetworkMetrics = new ArrayList(); // get all the metrics from the available sample period List<PerfMetricId> perfMetrics = service.queryAvailablePerfMetric(perfMgr, vmMor, null, null, null); if(perfMetrics != null) { for(int index=0; index < perfMetrics.size(); ++index) { if ( ((rxPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == rxPerfCounterInfo.getKey())) || ((txPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == txPerfCounterInfo.getKey())) ) { vmNetworkMetrics.add(perfMetrics.get(index)); } } } double networkReadKBs=0; double networkWriteKBs=0; long sampleDuration=0; if (vmNetworkMetrics.size() != 0) { PerfQuerySpec qSpec = new PerfQuerySpec(); qSpec.setEntity(vmMor); PerfMetricId[] availableMetricIds = (PerfMetricId[]) vmNetworkMetrics.toArray(new PerfMetricId[0]); qSpec.getMetricId().addAll(Arrays.asList(availableMetricIds)); List<PerfQuerySpec> qSpecs = new ArrayList<PerfQuerySpec>(); qSpecs.add(qSpec); List<PerfEntityMetricBase> values = service.queryPerf(perfMgr, qSpecs); for(int i=0; i<values.size(); ++i) { List<PerfSampleInfo> infos = ((PerfEntityMetric)values.get(i)).getSampleInfo(); int endMs = infos.get(infos.size()-1).getTimestamp().getSecond() * 1000 + infos.get(infos.size()-1).getTimestamp().getMillisecond(); int beginMs = infos.get(0).getTimestamp().getSecond() * 1000 + infos.get(0).getTimestamp().getMillisecond(); sampleDuration = (endMs - beginMs) /1000; List<PerfMetricSeries> vals = ((PerfEntityMetric)values.get(i)).getValue(); for(int vi = 0; ((vals!= null) && (vi < vals.size())); ++vi){ if(vals.get(vi) instanceof PerfMetricIntSeries) { PerfMetricIntSeries val = (PerfMetricIntSeries)vals.get(vi); List<Long> perfValues = val.getValue(); if (vals.get(vi).getId().getCounterId() == rxPerfCounterInfo.getKey()) { networkReadKBs = sampleDuration * perfValues.get(3); //get the average RX rate multiplied by sampled duration } if (vals.get(vi).getId().getCounterId() == txPerfCounterInfo.getKey()) { networkWriteKBs = sampleDuration * perfValues.get(3);//get the average TX rate multiplied by sampled duration } } } } } vmResponseMap.put(name, new VmStatsEntry(Integer.parseInt(maxCpuUsage), networkReadKBs, networkWriteKBs, Integer.parseInt(numberCPUs), "vm")); } } } return vmResponseMap; } protected String networkUsage(final String privateIpAddress, final String option, final String ethName) { String args = null; if (option.equals("get")) { args = "-g"; } else if (option.equals("create")) { args = "-c"; } else if (option.equals("reset")) { args = "-r"; } else if (option.equals("addVif")) { args = "-a"; args += ethName; } else if (option.equals("deleteVif")) { args = "-d"; args += ethName; } try { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing /opt/cloud/bin/netusage.sh " + args + " on DomR " + privateIpAddress); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/netusage.sh " + args); if (!result.first()) { return null; } return result.second(); } catch (Throwable e) { s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return null; } private long[] getNetworkStats(String privateIP) { String result = networkUsage(privateIP, "get", null); long[] stats = new long[2]; if (result != null) { try { String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += (new Long(splitResult[i++])).longValue(); stats[1] += (new Long(splitResult[i++])).longValue(); } } catch (Throwable e) { s_logger.warn("Unable to parse return from script return of network usage command: " + e.toString(), e); } } return stats; } protected String connect(final String vmName, final String ipAddress, final int port) { long startTick = System.currentTimeMillis(); // wait until we have at least been waiting for _ops_timeout time or // at least have tried _retry times, this is to coordinate with system // VM patching/rebooting time that may need int retry = _retry; while (System.currentTimeMillis() - startTick <= _ops_timeout || --retry > 0) { SocketChannel sch = null; try { s_logger.info("Trying to connect to " + ipAddress); sch = SocketChannel.open(); sch.configureBlocking(true); sch.socket().setSoTimeout(5000); InetSocketAddress addr = new InetSocketAddress(ipAddress, port); sch.connect(addr); return null; } catch (IOException e) { s_logger.info("Could not connect to " + ipAddress + " due to " + e.toString()); if (e instanceof ConnectException) { // if connection is refused because of VM is being started, // we give it more sleep time // to avoid running out of retry quota too quickly try { Thread.sleep(5000); } catch (InterruptedException ex) { } } } finally { if (sch != null) { try { sch.close(); } catch (IOException e) { } } } try { Thread.sleep(1000); } catch (InterruptedException ex) { } } s_logger.info("Unable to logon to " + ipAddress); return "Unable to connect"; } protected String connect(final String vmname, final String ipAddress) { return connect(vmname, ipAddress, 3922); } private static State convertState(VirtualMachinePowerState powerState) { return s_statesTable.get(powerState); } public static State getVmState(VirtualMachineMO vmMo) throws Exception { VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo(); return convertState(runtimeInfo.getPowerState()); } private static HostStatsEntry getHyperHostStats(VmwareHypervisorHost hyperHost) throws Exception { ComputeResourceSummary hardwareSummary = hyperHost.getHyperHostHardwareSummary(); if(hardwareSummary == null) return null; HostStatsEntry entry = new HostStatsEntry(); entry.setEntityType("host"); double cpuUtilization = ((double) (hardwareSummary.getTotalCpu() - hardwareSummary.getEffectiveCpu()) / (double) hardwareSummary.getTotalCpu() * 100); entry.setCpuUtilization(cpuUtilization); entry.setTotalMemoryKBs(hardwareSummary.getTotalMemory() / 1024); entry.setFreeMemoryKBs(hardwareSummary.getEffectiveMemory() * 1024); return entry; } private static String getRouterSshControlIp(NetworkElementCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); if(routerGuestIp != null && zoneNetworkType != null && NetworkType.valueOf(zoneNetworkType) == NetworkType.Basic) { if(s_logger.isDebugEnabled()) s_logger.debug("In Basic zone mode, use router's guest IP for SSH control. guest IP : " + routerGuestIp); return routerGuestIp; } if(s_logger.isDebugEnabled()) s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); return routerIp; } @Override public void setAgentControl(IAgentControl agentControl) { } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; _url = (String) params.get("url"); _username = (String) params.get("username"); _password = (String) params.get("password"); _dcId = (String) params.get("zone"); _pod = (String) params.get("pod"); _cluster = (String) params.get("cluster"); _guid = (String) params.get("guid"); String[] tokens = _guid.split("@"); _vCenterAddress = tokens[1]; _morHyperHost = new ManagedObjectReference(); String[] hostTokens = tokens[0].split(":"); _morHyperHost.setType(hostTokens[0]); _morHyperHost.setValue(hostTokens[1]); _guestTrafficInfo = (VmwareTrafficLabel) params.get("guestTrafficInfo"); _publicTrafficInfo = (VmwareTrafficLabel) params.get("publicTrafficInfo"); VmwareContext context = getServiceContext(); volMgr = ComponentContext.inject(VolumeManagerImpl.class); try { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); mgr.setupResourceStartupParams(params); CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(context, context.getServiceContent().getCustomFieldsManager()); cfmMo.ensureCustomFieldDef("Datastore", CustomFieldConstants.CLOUD_UUID); if (_publicTrafficInfo != null && _publicTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch || _guestTrafficInfo != null && _guestTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch) { cfmMo.ensureCustomFieldDef("DistributedVirtualPortgroup", CustomFieldConstants.CLOUD_GC_DVP); } cfmMo.ensureCustomFieldDef("Network", CustomFieldConstants.CLOUD_GC); cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_UUID); cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_NIC_MASK); VmwareHypervisorHost hostMo = this.getHyperHost(context); _hostName = hostMo.getHyperHostName(); Map<String, String> vsmCredentials; if (_guestTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch || _publicTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch) { vsmCredentials = mgr.getNexusVSMCredentialsByClusterId(Long.parseLong(_cluster)); if (vsmCredentials != null) { s_logger.info("Stocking credentials while configuring resource."); context.registerStockObject("vsmcredentials", vsmCredentials); } _privateNetworkVSwitchName = mgr.getPrivateVSwitchName(Long.parseLong(_dcId), HypervisorType.VMware); } } catch (Exception e) { s_logger.error("Unexpected Exception ", e); } if(_privateNetworkVSwitchName == null) { _privateNetworkVSwitchName = (String) params.get("private.network.vswitch.name"); } String value = (String) params.get("vmware.reserve.cpu"); if(value != null && value.equalsIgnoreCase("true")) _reserveCpu = true; value = (String) params.get("vmware.recycle.hung.wokervm"); if(value != null && value.equalsIgnoreCase("true")) _recycleHungWorker = true; value = (String) params.get("vmware.reserve.mem"); if(value != null && value.equalsIgnoreCase("true")) _reserveMem = true; value = (String)params.get("vmware.root.disk.controller"); if(value != null && value.equalsIgnoreCase("scsi")) _rootDiskController = DiskControllerType.scsi; else _rootDiskController = DiskControllerType.ide; Integer intObj = (Integer) params.get("ports.per.dvportgroup"); if (intObj != null) _portsPerDvPortGroup = intObj.intValue(); s_logger.info("VmwareResource network configuration info." + " private traffic over vSwitch: " + _privateNetworkVSwitchName + ", public traffic over " + _publicTrafficInfo.getVirtualSwitchType() + " : " + _publicTrafficInfo.getVirtualSwitchName() + ", guest traffic over " + _guestTrafficInfo.getVirtualSwitchType() + " : " + _guestTrafficInfo.getVirtualSwitchName()); value = params.get("vmware.create.full.clone").toString(); if (value != null && value.equalsIgnoreCase("true")) { _fullCloneFlag = true; } else { _fullCloneFlag = false; } value = (String)params.get("scripts.timeout"); int timeout = NumbersUtil.parseInt(value, 1440) * 1000; VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VmwareStorageProcessor storageProcessor = new VmwareStorageProcessor((VmwareHostService)this, _fullCloneFlag, (VmwareStorageMount)mgr, timeout, this, _shutdown_waitMs ); storageHandler = new StorageSubsystemCommandHandlerBase(storageProcessor); return true; } @Override public String getName() { return _name; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } public VmwareContext getServiceContext() { return getServiceContext(null); } public void invalidateServiceContext() { invalidateServiceContext(null); } public VmwareHypervisorHost getHyperHost(VmwareContext context) { return getHyperHost(context, null); } @Override public synchronized VmwareContext getServiceContext(Command cmd) { if (_serviceContext == null) { try { _serviceContext = VmwareContextFactory.create(_vCenterAddress, _username, _password); VmwareHypervisorHost hyperHost = getHyperHost(_serviceContext, cmd); assert(hyperHost instanceof HostMO); HostFirewallSystemMO firewallMo = ((HostMO)hyperHost).getHostFirewallSystemMO(); boolean bRefresh = false; if(firewallMo != null) { HostFirewallInfo firewallInfo = firewallMo.getFirewallInfo(); if(firewallInfo != null && firewallInfo.getRuleset() != null) { for(HostFirewallRuleset rule : firewallInfo.getRuleset()) { if("vncServer".equalsIgnoreCase(rule.getKey())) { bRefresh = true; firewallMo.enableRuleset("vncServer"); } else if("gdbserver".equalsIgnoreCase(rule.getKey())) { bRefresh = true; firewallMo.enableRuleset("gdbserver"); } } } if(bRefresh) firewallMo.refreshFirewall(); } } catch (Exception e) { s_logger.error("Unable to connect to vSphere server: " + _vCenterAddress, e); throw new CloudRuntimeException("Unable to connect to vSphere server: " + _vCenterAddress); } } return _serviceContext; } @Override public synchronized void invalidateServiceContext(VmwareContext context) { if (_serviceContext != null) { _serviceContext.close(); } _serviceContext = null; } @Override public VmwareHypervisorHost getHyperHost(VmwareContext context, Command cmd) { if (_morHyperHost.getType().equalsIgnoreCase("HostSystem")) { return new HostMO(context, _morHyperHost); } return new ClusterMO(context, _morHyperHost); } @Override @DB public String getWorkerName(VmwareContext context, Command cmd, int workerSequence) { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String vmName = mgr.composeWorkerName(); assert(cmd != null); context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // TODO: Fix this? long checkPointId = vmwareMgr.pushCleanupCheckpoint(this._guid, vmName); // TODO: Fix this? cmd.setContextParam("checkpoint", String.valueOf(checkPointId)); return vmName; } @Override public void setName(String name) { // TODO Auto-generated method stub } @Override public void setConfigParams(Map<String, Object> params) { // TODO Auto-generated method stub } @Override public Map<String, Object> getConfigParams() { // TODO Auto-generated method stub return null; } @Override public int getRunLevel() { // TODO Auto-generated method stub return 0; } @Override public void setRunLevel(int level) { // TODO Auto-generated method stub } @Override public Answer execute(DestroyCommand cmd) { // TODO Auto-generated method stub return null; } private boolean isVMWareToolsInstalled(VirtualMachineMO vmMo) throws Exception{ GuestInfo guestInfo = vmMo.getVmGuestInfo(); return (guestInfo != null && guestInfo.getGuestState() != null && guestInfo.getGuestState().equalsIgnoreCase("running")); } }
plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
// 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 com.cloud.hypervisor.vmware.resource; import java.io.File; import java.io.IOException; import java.net.ConnectException; import java.net.InetSocketAddress; import java.net.URI; import java.nio.channels.SocketChannel; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.concurrent.*; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Random; import java.util.Set; import java.util.TimeZone; import java.util.UUID; import javax.inject.Inject; import javax.naming.ConfigurationException; import com.cloud.agent.api.to.DhcpTO; import org.apache.log4j.Logger; import org.apache.log4j.NDC; import com.google.gson.Gson; import com.vmware.vim25.AboutInfo; import com.vmware.vim25.BoolPolicy; import com.vmware.vim25.ClusterDasConfigInfo; import com.vmware.vim25.ComputeResourceSummary; import com.vmware.vim25.DVPortConfigInfo; import com.vmware.vim25.DVPortConfigSpec; import com.vmware.vim25.DatastoreSummary; import com.vmware.vim25.DistributedVirtualPort; import com.vmware.vim25.DistributedVirtualSwitchPortConnection; import com.vmware.vim25.DistributedVirtualSwitchPortCriteria; import com.vmware.vim25.DynamicProperty; import com.vmware.vim25.GuestInfo; import com.vmware.vim25.HostCapability; import com.vmware.vim25.HostFirewallInfo; import com.vmware.vim25.HostFirewallRuleset; import com.vmware.vim25.HostHostBusAdapter; import com.vmware.vim25.HostInternetScsiHba; import com.vmware.vim25.HostInternetScsiHbaAuthenticationProperties; import com.vmware.vim25.HostInternetScsiHbaStaticTarget; import com.vmware.vim25.HostInternetScsiTargetTransport; import com.vmware.vim25.HostScsiDisk; import com.vmware.vim25.HostScsiTopology; import com.vmware.vim25.HostScsiTopologyInterface; import com.vmware.vim25.HostScsiTopologyLun; import com.vmware.vim25.HostScsiTopologyTarget; import com.vmware.vim25.ManagedObjectReference; import com.vmware.vim25.ObjectContent; import com.vmware.vim25.OptionValue; import com.vmware.vim25.PerfCounterInfo; import com.vmware.vim25.PerfEntityMetric; import com.vmware.vim25.PerfEntityMetricBase; import com.vmware.vim25.PerfMetricId; import com.vmware.vim25.PerfMetricIntSeries; import com.vmware.vim25.PerfMetricSeries; import com.vmware.vim25.PerfQuerySpec; import com.vmware.vim25.PerfSampleInfo; import com.vmware.vim25.RuntimeFaultFaultMsg; import com.vmware.vim25.ToolsUnavailableFaultMsg; import com.vmware.vim25.VMwareDVSPortSetting; import com.vmware.vim25.VimPortType; import com.vmware.vim25.VirtualDevice; import com.vmware.vim25.VirtualDeviceBackingInfo; import com.vmware.vim25.VirtualDeviceConfigSpec; import com.vmware.vim25.VirtualDeviceConfigSpecOperation; import com.vmware.vim25.VirtualDisk; import com.vmware.vim25.VirtualEthernetCard; import com.vmware.vim25.VirtualEthernetCardDistributedVirtualPortBackingInfo; import com.vmware.vim25.VirtualEthernetCardNetworkBackingInfo; import com.vmware.vim25.VirtualLsiLogicController; import com.vmware.vim25.VirtualMachineConfigSpec; import com.vmware.vim25.VirtualMachineFileInfo; import com.vmware.vim25.VirtualMachineGuestOsIdentifier; import com.vmware.vim25.VirtualMachinePowerState; import com.vmware.vim25.VirtualMachineRelocateSpec; import com.vmware.vim25.VirtualMachineRelocateSpecDiskLocator; import com.vmware.vim25.VirtualMachineRuntimeInfo; import com.vmware.vim25.VirtualSCSISharing; import com.vmware.vim25.VmwareDistributedVirtualSwitchVlanIdSpec; import com.cloud.agent.IAgentControl; import com.cloud.agent.api.Answer; import com.cloud.agent.api.AttachIsoCommand; import com.cloud.agent.api.AttachVolumeAnswer; import com.cloud.agent.api.AttachVolumeCommand; import com.cloud.agent.api.BackupSnapshotAnswer; import com.cloud.agent.api.BackupSnapshotCommand; import com.cloud.agent.api.BumpUpPriorityCommand; import com.cloud.agent.api.CheckHealthAnswer; import com.cloud.agent.api.CheckHealthCommand; import com.cloud.agent.api.CheckNetworkAnswer; import com.cloud.agent.api.CheckNetworkCommand; import com.cloud.agent.api.CheckOnHostAnswer; import com.cloud.agent.api.CheckOnHostCommand; import com.cloud.agent.api.CheckRouterAnswer; import com.cloud.agent.api.CheckRouterCommand; import com.cloud.agent.api.CheckS2SVpnConnectionsAnswer; import com.cloud.agent.api.CheckS2SVpnConnectionsCommand; import com.cloud.agent.api.CheckVirtualMachineAnswer; import com.cloud.agent.api.CheckVirtualMachineCommand; import com.cloud.agent.api.Command; import com.cloud.agent.api.CreatePrivateTemplateFromSnapshotCommand; import com.cloud.agent.api.CreatePrivateTemplateFromVolumeCommand; import com.cloud.agent.api.CreateStoragePoolCommand; import com.cloud.agent.api.CreateVMSnapshotAnswer; import com.cloud.agent.api.CreateVMSnapshotCommand; import com.cloud.agent.api.CreateVolumeFromSnapshotAnswer; import com.cloud.agent.api.CreateVolumeFromSnapshotCommand; import com.cloud.agent.api.DeleteStoragePoolCommand; import com.cloud.agent.api.DeleteVMSnapshotAnswer; import com.cloud.agent.api.DeleteVMSnapshotCommand; import com.cloud.agent.api.GetDomRVersionAnswer; import com.cloud.agent.api.GetDomRVersionCmd; import com.cloud.agent.api.GetHostStatsAnswer; import com.cloud.agent.api.GetHostStatsCommand; import com.cloud.agent.api.GetStorageStatsAnswer; import com.cloud.agent.api.GetStorageStatsCommand; import com.cloud.agent.api.GetVmStatsAnswer; import com.cloud.agent.api.GetVmStatsCommand; import com.cloud.agent.api.GetVncPortAnswer; import com.cloud.agent.api.GetVncPortCommand; import com.cloud.agent.api.HostStatsEntry; import com.cloud.agent.api.MaintainAnswer; import com.cloud.agent.api.MaintainCommand; import com.cloud.agent.api.ManageSnapshotAnswer; import com.cloud.agent.api.ManageSnapshotCommand; import com.cloud.agent.api.MigrateAnswer; import com.cloud.agent.api.MigrateCommand; import com.cloud.agent.api.MigrateWithStorageAnswer; import com.cloud.agent.api.MigrateWithStorageCommand; import com.cloud.agent.api.ModifySshKeysCommand; import com.cloud.agent.api.ModifyStoragePoolAnswer; import com.cloud.agent.api.ModifyStoragePoolCommand; import com.cloud.agent.api.NetworkUsageAnswer; import com.cloud.agent.api.NetworkUsageCommand; import com.cloud.agent.api.PingCommand; import com.cloud.agent.api.PingRoutingCommand; import com.cloud.agent.api.PingTestCommand; import com.cloud.agent.api.PlugNicAnswer; import com.cloud.agent.api.PlugNicCommand; import com.cloud.agent.api.PoolEjectCommand; import com.cloud.agent.api.PrepareForMigrationAnswer; import com.cloud.agent.api.PrepareForMigrationCommand; import com.cloud.agent.api.PvlanSetupCommand; import com.cloud.agent.api.ReadyAnswer; import com.cloud.agent.api.ReadyCommand; import com.cloud.agent.api.RebootAnswer; import com.cloud.agent.api.RebootCommand; import com.cloud.agent.api.RebootRouterCommand; import com.cloud.agent.api.RevertToVMSnapshotAnswer; import com.cloud.agent.api.RevertToVMSnapshotCommand; import com.cloud.agent.api.ScaleVmAnswer; import com.cloud.agent.api.ScaleVmCommand; import com.cloud.agent.api.SetupAnswer; import com.cloud.agent.api.SetupCommand; import com.cloud.agent.api.SetupGuestNetworkAnswer; import com.cloud.agent.api.SetupGuestNetworkCommand; import com.cloud.agent.api.StartAnswer; import com.cloud.agent.api.StartCommand; import com.cloud.agent.api.StartupCommand; import com.cloud.agent.api.StartupRoutingCommand; import com.cloud.agent.api.StartupStorageCommand; import com.cloud.agent.api.StopAnswer; import com.cloud.agent.api.StopCommand; import com.cloud.agent.api.StoragePoolInfo; import com.cloud.agent.api.UnPlugNicAnswer; import com.cloud.agent.api.UnPlugNicCommand; import com.cloud.agent.api.UnregisterNicCommand; import com.cloud.agent.api.UnregisterVMCommand; import com.cloud.agent.api.UpgradeSnapshotCommand; import com.cloud.agent.api.ValidateSnapshotAnswer; import com.cloud.agent.api.ValidateSnapshotCommand; import com.cloud.agent.api.VmStatsEntry; import com.cloud.agent.api.check.CheckSshAnswer; import com.cloud.agent.api.check.CheckSshCommand; import com.cloud.agent.api.routing.CreateIpAliasCommand; import com.cloud.agent.api.routing.DeleteIpAliasCommand; import com.cloud.agent.api.routing.DhcpEntryCommand; import com.cloud.agent.api.routing.DnsMasqConfigCommand; import com.cloud.agent.api.routing.IpAliasTO; import com.cloud.agent.api.routing.IpAssocAnswer; import com.cloud.agent.api.routing.IpAssocCommand; import com.cloud.agent.api.routing.IpAssocVpcCommand; import com.cloud.agent.api.routing.LoadBalancerConfigCommand; import com.cloud.agent.api.routing.NetworkElementCommand; import com.cloud.agent.api.routing.RemoteAccessVpnCfgCommand; import com.cloud.agent.api.routing.SavePasswordCommand; import com.cloud.agent.api.routing.SetFirewallRulesAnswer; import com.cloud.agent.api.routing.SetFirewallRulesCommand; import com.cloud.agent.api.routing.SetNetworkACLAnswer; import com.cloud.agent.api.routing.SetNetworkACLCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesAnswer; import com.cloud.agent.api.routing.SetPortForwardingRulesCommand; import com.cloud.agent.api.routing.SetPortForwardingRulesVpcCommand; import com.cloud.agent.api.routing.SetSourceNatAnswer; import com.cloud.agent.api.routing.SetSourceNatCommand; import com.cloud.agent.api.routing.SetStaticNatRulesAnswer; import com.cloud.agent.api.routing.SetStaticNatRulesCommand; import com.cloud.agent.api.routing.SetStaticRouteAnswer; import com.cloud.agent.api.routing.SetStaticRouteCommand; import com.cloud.agent.api.routing.Site2SiteVpnCfgCommand; import com.cloud.agent.api.routing.VmDataCommand; import com.cloud.agent.api.routing.VpnUsersCfgCommand; import com.cloud.agent.api.storage.CopyVolumeAnswer; import com.cloud.agent.api.storage.CopyVolumeCommand; import com.cloud.agent.api.storage.CreateAnswer; import com.cloud.agent.api.storage.CreateCommand; import com.cloud.agent.api.storage.CreatePrivateTemplateAnswer; import com.cloud.agent.api.storage.CreateVolumeOVAAnswer; import com.cloud.agent.api.storage.CreateVolumeOVACommand; import com.cloud.agent.api.storage.DestroyCommand; import com.cloud.agent.api.storage.MigrateVolumeAnswer; import com.cloud.agent.api.storage.MigrateVolumeCommand; import com.cloud.agent.api.storage.PrepareOVAPackingAnswer; import com.cloud.agent.api.storage.PrepareOVAPackingCommand; import com.cloud.agent.api.storage.PrimaryStorageDownloadAnswer; import com.cloud.agent.api.storage.PrimaryStorageDownloadCommand; import com.cloud.agent.api.storage.ResizeVolumeAnswer; import com.cloud.agent.api.storage.ResizeVolumeCommand; import com.cloud.agent.api.to.DataStoreTO; import com.cloud.agent.api.to.DiskTO; import com.cloud.agent.api.to.FirewallRuleTO; import com.cloud.agent.api.to.IpAddressTO; import com.cloud.agent.api.to.NfsTO; import com.cloud.agent.api.to.NicTO; import com.cloud.agent.api.to.PortForwardingRuleTO; import com.cloud.agent.api.to.StaticNatRuleTO; import com.cloud.agent.api.to.StorageFilerTO; import com.cloud.agent.api.to.VirtualMachineTO; import com.cloud.agent.api.to.VolumeTO; import com.cloud.dc.DataCenter.NetworkType; import com.cloud.dc.Vlan; import com.cloud.exception.InternalErrorException; import com.cloud.host.Host.Type; import com.cloud.hypervisor.Hypervisor.HypervisorType; import com.cloud.hypervisor.vmware.manager.VmwareHostService; import com.cloud.hypervisor.vmware.manager.VmwareManager; import com.cloud.hypervisor.vmware.manager.VmwareStorageMount; import com.cloud.hypervisor.vmware.mo.ClusterMO; import com.cloud.hypervisor.vmware.mo.CustomFieldConstants; import com.cloud.hypervisor.vmware.mo.CustomFieldsManagerMO; import com.cloud.hypervisor.vmware.mo.DatacenterMO; import com.cloud.hypervisor.vmware.mo.DatastoreMO; import com.cloud.hypervisor.vmware.mo.DiskControllerType; import com.cloud.hypervisor.vmware.mo.FeatureKeyConstants; import com.cloud.hypervisor.vmware.mo.HostDatastoreSystemMO; import com.cloud.hypervisor.vmware.mo.HostFirewallSystemMO; import com.cloud.hypervisor.vmware.mo.HostMO; import com.cloud.hypervisor.vmware.mo.HostStorageSystemMO; import com.cloud.hypervisor.vmware.mo.HypervisorHostHelper; import com.cloud.hypervisor.vmware.mo.NetworkDetails; import com.cloud.hypervisor.vmware.mo.VirtualEthernetCardType; import com.cloud.hypervisor.vmware.mo.VirtualMachineMO; import com.cloud.hypervisor.vmware.mo.VirtualSwitchType; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHost; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostNetworkSummary; import com.cloud.hypervisor.vmware.mo.VmwareHypervisorHostResourceSummary; import com.cloud.hypervisor.vmware.util.VmwareContext; import com.cloud.hypervisor.vmware.util.VmwareGuestOsMapper; import com.cloud.hypervisor.vmware.util.VmwareHelper; import com.cloud.network.HAProxyConfigurator; import com.cloud.network.LoadBalancerConfigurator; import com.cloud.network.Networks; import com.cloud.network.Networks.BroadcastDomainType; import com.cloud.network.Networks.TrafficType; import com.cloud.network.VmwareTrafficLabel; import com.cloud.network.rules.FirewallRule; import com.cloud.resource.ServerResource; import com.cloud.serializer.GsonHelper; import com.cloud.storage.Storage; import com.cloud.storage.Storage.StoragePoolType; import com.cloud.storage.Volume; import com.cloud.storage.VolumeManager; import com.cloud.storage.VolumeManagerImpl; import com.cloud.storage.resource.StoragePoolResource; import com.cloud.storage.resource.StorageSubsystemCommandHandler; import com.cloud.storage.resource.StorageSubsystemCommandHandlerBase; import com.cloud.storage.resource.VmwareStorageProcessor; import com.cloud.storage.template.TemplateProp; import com.cloud.utils.DateUtil; import com.cloud.utils.NumbersUtil; import com.cloud.utils.Pair; import com.cloud.utils.StringUtils; import com.cloud.utils.component.ComponentContext; import com.cloud.utils.db.DB; import com.cloud.utils.exception.CloudRuntimeException; import com.cloud.utils.exception.ExceptionUtil; import com.cloud.utils.mgmt.JmxUtil; import com.cloud.utils.mgmt.PropertyMapDynamicBean; import com.cloud.utils.net.NetUtils; import com.cloud.utils.ssh.SshHelper; import com.cloud.vm.DiskProfile; import com.cloud.vm.VirtualMachine; import com.cloud.vm.VirtualMachine.State; import com.cloud.vm.VirtualMachineName; import com.cloud.vm.VmDetailConstants; import org.apache.cloudstack.storage.command.DeleteCommand; import org.apache.cloudstack.storage.command.StorageSubSystemCommand; import org.apache.cloudstack.storage.to.PrimaryDataStoreTO; import org.apache.cloudstack.storage.to.TemplateObjectTO; import org.apache.cloudstack.storage.to.VolumeObjectTO; public class VmwareResource implements StoragePoolResource, ServerResource, VmwareHostService { private static final Logger s_logger = Logger.getLogger(VmwareResource.class); protected String _name; protected final long _ops_timeout = 900000; // 15 minutes time out to time protected final int _shutdown_waitMs = 300000; // wait up to 5 minutes for shutdown @Inject protected VolumeManager volMgr; // out an operation protected final int _retry = 24; protected final int _sleep = 10000; protected final int DEFAULT_DOMR_SSHPORT = 3922; protected final int MAX_CMD_MBEAN = 100; protected String _url; protected String _dcId; protected String _pod; protected String _cluster; protected String _username; protected String _password; protected String _guid; protected String _vCenterAddress; protected String _privateNetworkVSwitchName; protected VmwareTrafficLabel _guestTrafficInfo = new VmwareTrafficLabel(TrafficType.Guest); protected VmwareTrafficLabel _publicTrafficInfo = new VmwareTrafficLabel(TrafficType.Public); protected int _portsPerDvPortGroup; protected boolean _fullCloneFlag = false; protected boolean _reserveCpu = false; protected boolean _reserveMem = false; protected boolean _recycleHungWorker = false; protected DiskControllerType _rootDiskController = DiskControllerType.ide; protected ManagedObjectReference _morHyperHost; protected VmwareContext _serviceContext; protected String _hostName; protected HashMap<String, State> _vms = new HashMap<String, State>(71); protected List<PropertyMapDynamicBean> _cmdMBeans = new ArrayList<PropertyMapDynamicBean>(); protected Gson _gson; protected volatile long _cmdSequence = 1; protected StorageSubsystemCommandHandler storageHandler; protected static HashMap<VirtualMachinePowerState, State> s_statesTable; static { s_statesTable = new HashMap<VirtualMachinePowerState, State>(); s_statesTable.put(VirtualMachinePowerState.POWERED_ON, State.Running); s_statesTable.put(VirtualMachinePowerState.POWERED_OFF, State.Stopped); s_statesTable.put(VirtualMachinePowerState.SUSPENDED, State.Stopped); } public Gson getGson() { return _gson; } public VmwareResource() { _gson = GsonHelper.getGsonLogger(); } @Override public Answer executeRequest(Command cmd) { if(s_logger.isTraceEnabled()) s_logger.trace("Begin executeRequest(), cmd: " + cmd.getClass().getSimpleName()); Answer answer = null; NDC.push(_hostName != null ? _hostName : _guid + "(" + this.getClass().getPackage().getImplementationVersion() + ")"); try { long cmdSequence = _cmdSequence++; Date startTime = DateUtil.currentGMTTime(); PropertyMapDynamicBean mbean = new PropertyMapDynamicBean(); mbean.addProp("StartTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), startTime)); mbean.addProp("Command", _gson.toJson(cmd)); mbean.addProp("Sequence", String.valueOf(cmdSequence)); mbean.addProp("Name", cmd.getClass().getSimpleName()); Class<? extends Command> clz = cmd.getClass(); if (clz == CreateCommand.class) { answer = execute((CreateCommand) cmd); } else if (clz == SetPortForwardingRulesCommand.class) { answer = execute((SetPortForwardingRulesCommand) cmd); } else if (clz == SetStaticNatRulesCommand.class) { answer = execute((SetStaticNatRulesCommand) cmd); } else if (clz == LoadBalancerConfigCommand.class) { answer = execute((LoadBalancerConfigCommand) cmd); } else if (clz == IpAssocCommand.class) { answer = execute((IpAssocCommand) cmd); } else if (clz == SavePasswordCommand.class) { answer = execute((SavePasswordCommand) cmd); } else if (clz == DhcpEntryCommand.class) { answer = execute((DhcpEntryCommand) cmd); } else if (clz == CreateIpAliasCommand.class) { return execute((CreateIpAliasCommand) cmd); } else if (clz == DnsMasqConfigCommand.class) { return execute((DnsMasqConfigCommand) cmd); } else if (clz == DeleteIpAliasCommand.class) { return execute((DeleteIpAliasCommand) cmd); } else if (clz == VmDataCommand.class) { answer = execute((VmDataCommand) cmd); } else if (clz == ReadyCommand.class) { answer = execute((ReadyCommand) cmd); } else if (clz == GetHostStatsCommand.class) { answer = execute((GetHostStatsCommand) cmd); } else if (clz == GetVmStatsCommand.class) { answer = execute((GetVmStatsCommand) cmd); } else if (clz == CheckHealthCommand.class) { answer = execute((CheckHealthCommand) cmd); } else if (clz == StopCommand.class) { answer = execute((StopCommand) cmd); } else if (clz == RebootRouterCommand.class) { answer = execute((RebootRouterCommand) cmd); } else if (clz == RebootCommand.class) { answer = execute((RebootCommand) cmd); } else if (clz == CheckVirtualMachineCommand.class) { answer = execute((CheckVirtualMachineCommand) cmd); } else if (clz == PrepareForMigrationCommand.class) { answer = execute((PrepareForMigrationCommand) cmd); } else if (clz == MigrateCommand.class) { answer = execute((MigrateCommand) cmd); } else if (clz == MigrateWithStorageCommand.class) { answer = execute((MigrateWithStorageCommand) cmd); } else if (clz == MigrateVolumeCommand.class) { answer = execute((MigrateVolumeCommand) cmd); } else if (clz == DestroyCommand.class) { answer = execute((DestroyCommand) cmd); } else if (clz == CreateStoragePoolCommand.class) { return execute((CreateStoragePoolCommand) cmd); } else if (clz == ModifyStoragePoolCommand.class) { answer = execute((ModifyStoragePoolCommand) cmd); } else if (clz == DeleteStoragePoolCommand.class) { answer = execute((DeleteStoragePoolCommand) cmd); } else if (clz == CopyVolumeCommand.class) { answer = execute((CopyVolumeCommand) cmd); } else if (clz == CreateVolumeOVACommand.class) { answer = execute((CreateVolumeOVACommand) cmd); } else if (clz == PrepareOVAPackingCommand.class) { answer = execute((PrepareOVAPackingCommand) cmd); } else if (clz == AttachVolumeCommand.class) { answer = execute((AttachVolumeCommand) cmd); } else if (clz == AttachIsoCommand.class) { answer = execute((AttachIsoCommand) cmd); } else if (clz == ValidateSnapshotCommand.class) { answer = execute((ValidateSnapshotCommand) cmd); } else if (clz == ManageSnapshotCommand.class) { answer = execute((ManageSnapshotCommand) cmd); } else if (clz == BackupSnapshotCommand.class) { answer = execute((BackupSnapshotCommand) cmd); } else if (clz == CreateVolumeFromSnapshotCommand.class) { answer = execute((CreateVolumeFromSnapshotCommand) cmd); } else if (clz == CreatePrivateTemplateFromVolumeCommand.class) { answer = execute((CreatePrivateTemplateFromVolumeCommand) cmd); } else if (clz == CreatePrivateTemplateFromSnapshotCommand.class) { answer = execute((CreatePrivateTemplateFromSnapshotCommand) cmd); } else if (clz == UpgradeSnapshotCommand.class) { answer = execute((UpgradeSnapshotCommand) cmd); } else if (clz == GetStorageStatsCommand.class) { answer = execute((GetStorageStatsCommand) cmd); } else if (clz == PrimaryStorageDownloadCommand.class) { answer = execute((PrimaryStorageDownloadCommand) cmd); } else if (clz == GetVncPortCommand.class) { answer = execute((GetVncPortCommand) cmd); } else if (clz == SetupCommand.class) { answer = execute((SetupCommand) cmd); } else if (clz == MaintainCommand.class) { answer = execute((MaintainCommand) cmd); } else if (clz == PingTestCommand.class) { answer = execute((PingTestCommand) cmd); } else if (clz == CheckOnHostCommand.class) { answer = execute((CheckOnHostCommand) cmd); } else if (clz == ModifySshKeysCommand.class) { answer = execute((ModifySshKeysCommand) cmd); } else if (clz == PoolEjectCommand.class) { answer = execute((PoolEjectCommand) cmd); } else if (clz == NetworkUsageCommand.class) { answer = execute((NetworkUsageCommand) cmd); } else if (clz == StartCommand.class) { answer = execute((StartCommand) cmd); } else if (clz == RemoteAccessVpnCfgCommand.class) { answer = execute((RemoteAccessVpnCfgCommand) cmd); } else if (clz == VpnUsersCfgCommand.class) { answer = execute((VpnUsersCfgCommand) cmd); } else if (clz == CheckSshCommand.class) { answer = execute((CheckSshCommand) cmd); } else if (clz == CheckRouterCommand.class) { answer = execute((CheckRouterCommand) cmd); } else if (clz == SetFirewallRulesCommand.class) { answer = execute((SetFirewallRulesCommand)cmd); } else if (clz == BumpUpPriorityCommand.class) { answer = execute((BumpUpPriorityCommand)cmd); } else if (clz == GetDomRVersionCmd.class) { answer = execute((GetDomRVersionCmd)cmd); } else if (clz == CheckNetworkCommand.class) { answer = execute((CheckNetworkCommand) cmd); } else if (clz == SetupGuestNetworkCommand.class) { answer = execute((SetupGuestNetworkCommand) cmd); } else if (clz == IpAssocVpcCommand.class) { answer = execute((IpAssocVpcCommand) cmd); } else if (clz == PlugNicCommand.class) { answer = execute((PlugNicCommand) cmd); } else if (clz == UnPlugNicCommand.class) { answer = execute((UnPlugNicCommand) cmd); } else if (clz == SetSourceNatCommand.class) { answer = execute((SetSourceNatCommand) cmd); } else if (clz == SetNetworkACLCommand.class) { answer = execute((SetNetworkACLCommand) cmd); } else if (cmd instanceof CreateVMSnapshotCommand) { return execute((CreateVMSnapshotCommand)cmd); } else if(cmd instanceof DeleteVMSnapshotCommand){ return execute((DeleteVMSnapshotCommand)cmd); } else if(cmd instanceof RevertToVMSnapshotCommand){ return execute((RevertToVMSnapshotCommand)cmd); }else if (clz == SetPortForwardingRulesVpcCommand.class) { answer = execute((SetPortForwardingRulesVpcCommand) cmd); } else if (clz == Site2SiteVpnCfgCommand.class) { answer = execute((Site2SiteVpnCfgCommand) cmd); } else if (clz == CheckS2SVpnConnectionsCommand.class) { answer = execute((CheckS2SVpnConnectionsCommand) cmd); } else if (clz == ResizeVolumeCommand.class) { return execute((ResizeVolumeCommand) cmd); } else if (clz == UnregisterVMCommand.class) { return execute((UnregisterVMCommand) cmd); } else if (cmd instanceof StorageSubSystemCommand) { return storageHandler.handleStorageCommands((StorageSubSystemCommand)cmd); } else if (clz == ScaleVmCommand.class) { return execute((ScaleVmCommand) cmd); } else if (clz == PvlanSetupCommand.class) { return execute((PvlanSetupCommand) cmd); } else if (clz == SetStaticRouteCommand.class) { answer = execute((SetStaticRouteCommand) cmd); } else if (clz == UnregisterNicCommand.class) { answer = execute((UnregisterNicCommand) cmd); } else { answer = Answer.createUnsupportedCommandAnswer(cmd); } if(cmd.getContextParam("checkpoint") != null) { answer.setContextParam("checkpoint", cmd.getContextParam("checkpoint")); } Date doneTime = DateUtil.currentGMTTime(); mbean.addProp("DoneTime", DateUtil.getDateDisplayString(TimeZone.getDefault(), doneTime)); mbean.addProp("Answer", _gson.toJson(answer)); synchronized (this) { try { JmxUtil.registerMBean("VMware " + _morHyperHost.getValue(), "Command " + cmdSequence + "-" + cmd.getClass().getSimpleName(), mbean); _cmdMBeans.add(mbean); if (_cmdMBeans.size() >= MAX_CMD_MBEAN) { PropertyMapDynamicBean mbeanToRemove = _cmdMBeans.get(0); _cmdMBeans.remove(0); JmxUtil.unregisterMBean("VMware " + _morHyperHost.getValue(), "Command " + mbeanToRemove.getProp("Sequence") + "-" + mbeanToRemove.getProp("Name")); } } catch (Exception e) { if(s_logger.isTraceEnabled()) s_logger.trace("Unable to register JMX monitoring due to exception " + ExceptionUtil.toString(e)); } } } finally { NDC.pop(); } if(s_logger.isTraceEnabled()) s_logger.trace("End executeRequest(), cmd: " + cmd.getClass().getSimpleName()); return answer; } private Answer execute(ResizeVolumeCommand cmd) { String path = cmd.getPath(); String vmName = cmd.getInstanceName(); long newSize = cmd.getNewSize()/1024; try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); // find VM through datacenter (VM is not at the target host yet) VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter"; s_logger.error(msg); throw new Exception(msg); } Pair<VirtualDisk, String> vdisk = vmMo.getDiskDevice(path, false); if(vdisk == null) { if(s_logger.isTraceEnabled()) s_logger.trace("resize volume done (failed)"); throw new Exception("No such disk device: " + path); } VirtualDisk disk = vdisk.first(); long oldSize = disk.getCapacityInKB(); if (newSize < oldSize){ throw new Exception("VMware doesn't support shrinking volume from larger size: " + oldSize+ " MB to a smaller size: " + newSize + " MB"); } else if(newSize == oldSize){ return new ResizeVolumeAnswer(cmd, true, "success", newSize*1024); } disk.setCapacityInKB(newSize); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(disk); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT); vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if (!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure VM to resize disk. vmName: " + vmName); } return new ResizeVolumeAnswer(cmd, true, "success", newSize*1024); } catch (Exception e) { s_logger.error("Unable to resize volume",e); String error = "failed to resize volume:" +e; return new ResizeVolumeAnswer(cmd, false, error ); } } protected Answer execute(CheckNetworkCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckNetworkCommand " + _gson.toJson(cmd)); } // TODO setup portgroup for private network needs to be done here now return new CheckNetworkAnswer(cmd, true , "Network Setup check by names is done"); } protected Answer execute(NetworkUsageCommand cmd) { if ( cmd.isForVpc() ) { return VPCNetworkUsage(cmd); } if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource NetworkUsageCommand " + _gson.toJson(cmd)); } if(cmd.getOption()!=null && cmd.getOption().equals("create") ){ String result = networkUsage(cmd.getPrivateIP(), "create", null); NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, result, 0L, 0L); return answer; } long[] stats = getNetworkStats(cmd.getPrivateIP()); NetworkUsageAnswer answer = new NetworkUsageAnswer(cmd, "", stats[0], stats[1]); return answer; } private SetStaticRouteAnswer execute(SetStaticRouteCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetStaticRouteCommand: " + _gson.toJson(cmd)); } boolean endResult = true; String controlIp = getRouterSshControlIp(cmd); String args = ""; String[] results = new String[cmd.getStaticRoutes().length]; int i = 0; // Extract and build the arguments for the command to be sent to the VR. String [][] rules = cmd.generateSRouteRules(); StringBuilder sb = new StringBuilder(); String[] srRules = rules[0]; for (int j = 0; j < srRules.length; j++) { sb.append(srRules[j]).append(','); } args += " -a " + sb.toString(); // Send over the command for execution, via ssh, to the VR. try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticroute.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticroute.sh " + args); if (!result.first()) { s_logger.error("SetStaticRouteCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetStaticRouteCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; endResult = false; } return new SetStaticRouteAnswer(cmd, endResult, results); } protected NetworkUsageAnswer VPCNetworkUsage(NetworkUsageCommand cmd) { String privateIp = cmd.getPrivateIP(); String option = cmd.getOption(); String publicIp = cmd.getGatewayIP(); String args = "-l " + publicIp+ " "; if (option.equals("get")) { args += "-g"; } else if (option.equals("create")) { args += "-c"; String vpcCIDR = cmd.getVpcCIDR(); args += " -v " + vpcCIDR; } else if (option.equals("reset")) { args += "-r"; } else if (option.equals("vpn")) { args += "-n"; } else if (option.equals("remove")) { args += "-d"; } else { return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } try { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing /opt/cloud/bin/vpc_netusage.sh " + args + " on DomR " + privateIp); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> resultPair = SshHelper.sshExecute(privateIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_netusage.sh " + args); if (!resultPair.first()) { throw new Exception(" vpc network usage plugin call failed "); } if (option.equals("get") || option.equals("vpn")) { String result = resultPair.second(); if (result == null || result.isEmpty()) { throw new Exception(" vpc network usage get returns empty "); } long[] stats = new long[2]; if (result != null) { String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += (new Long(splitResult[i++])).longValue(); stats[1] += (new Long(splitResult[i++])).longValue(); } return new NetworkUsageAnswer(cmd, "success", stats[0], stats[1]); } } return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } catch (Throwable e) { s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return new NetworkUsageAnswer(cmd, "success", 0L, 0L); } protected Answer execute(SetPortForwardingRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetPortForwardingRulesCommand: " + _gson.toJson(cmd)); } String controlIp = getRouterSshControlIp(cmd); String args = ""; String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (PortForwardingRuleTO rule : cmd.getRules()) { args += rule.revoked() ? " -D " : " -A "; args += " -P " + rule.getProtocol().toLowerCase(); args += " -l " + rule.getSrcIp(); args += " -p " + rule.getStringSrcPortRange(); args += " -r " + rule.getDstIp(); args += " -d " + rule.getStringDstPortRange(); try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); if (!result.first()) { s_logger.error("SetPortForwardingRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetPortForwardingRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; endResult = false; } } return new SetPortForwardingRulesAnswer(cmd, results, endResult); } protected SetFirewallRulesAnswer execute(SetFirewallRulesCommand cmd) { String controlIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; FirewallRuleTO[] allrules = cmd.getRules(); FirewallRule.TrafficType trafficType = allrules[0].getTrafficType(); String egressDefault = cmd.getAccessDetail(NetworkElementCommand.FIREWALL_EGRESS_DEFAULT); String[][] rules = cmd.generateFwRules(); String args = ""; args += " -F "; if (trafficType == FirewallRule.TrafficType.Egress){ args+= " -E "; if (egressDefault.equals("true")) { args+= " -P 1 "; } else if (egressDefault.equals("System")) { args+= " -P 2 "; } else { args+= " -P 0 "; } } StringBuilder sb = new StringBuilder(); String[] fwRules = rules[0]; if (fwRules.length > 0) { for (int i = 0; i < fwRules.length; i++) { sb.append(fwRules[i]).append(','); } args += " -a " + sb.toString(); } try { VmwareManager mgr = getServiceContext().getStockObject( VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = null; if (trafficType == FirewallRule.TrafficType.Egress){ result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewallRule_egress.sh " + args); } else { result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall_rule.sh " + args); } if (s_logger.isDebugEnabled()) { if (trafficType == FirewallRule.TrafficType.Egress){ s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewallRule_egress.sh " + args); } else { s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall_rule.sh " + args); } } if (!result.first()) { s_logger.error("SetFirewallRulesCommand failure on setting one rule. args: " + args); //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails for (int i=0; i < results.length; i++) { results[i] = "Failed"; } return new SetFirewallRulesAnswer(cmd, false, results); } } catch (Throwable e) { s_logger.error("SetFirewallRulesCommand(args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); //FIXME - in the future we have to process each rule separately; now we temporarily set every rule to be false if single rule fails for (int i=0; i < results.length; i++) { results[i] = "Failed"; } return new SetFirewallRulesAnswer(cmd, false, results); } return new SetFirewallRulesAnswer(cmd, true, results); } protected SetStaticNatRulesAnswer SetVPCStaticNatRules(SetStaticNatRulesCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetVPCStaticNatRulesCommand: " + _gson.toJson(cmd)); } String[] results = new String[cmd.getRules().length]; VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); int i = 0; boolean endResult = true; for (StaticNatRuleTO rule : cmd.getRules()) { // Prepare command to be send to VPC VR String args = ""; args += rule.revoked() ? " -D" : " -A"; args += " -l " + rule.getSrcIp(); args += " -r " + rule.getDstIp(); // Invoke command on VPC VR. try { Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_staticnat.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /opt/cloud/bin/vpc_staticnat.sh " + args); if (!result.first()) { s_logger.error("SetVPCStaticNatRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetVPCStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; endResult = false; } } return new SetStaticNatRulesAnswer(cmd, results, endResult); } protected Answer execute(SetStaticNatRulesCommand cmd) { if (cmd.getVpcId() != null) { return SetVPCStaticNatRules(cmd); } if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetFirewallRuleCommand: " + _gson.toJson(cmd)); } String args = null; String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (StaticNatRuleTO rule : cmd.getRules()) { // 1:1 NAT needs instanceip;publicip;domrip;op args = rule.revoked() ? " -D " : " -A "; args += " -l " + rule.getSrcIp(); args += " -r " + rule.getDstIp(); if (rule.getProtocol() != null) { args += " -P " + rule.getProtocol().toLowerCase(); } args += " -d " + rule.getStringSrcPortRange(); args += " -G "; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/firewall.sh " + args); if (s_logger.isDebugEnabled()) s_logger.debug("Executing script on domain router " + controlIp + ": /root/firewall.sh " + args); if (!result.first()) { s_logger.error("SetStaticNatRulesCommand failure on setting one rule. args: " + args); results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch (Throwable e) { s_logger.error("SetStaticNatRulesCommand (args: " + args + ") failed on setting one rule due to " + VmwareHelper.getExceptionMessage(e), e); results[i++] = "Failed"; endResult = false; } } return new SetStaticNatRulesAnswer(cmd, results, endResult); } protected Answer execute(final LoadBalancerConfigCommand cmd) { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); File keyFile = mgr.getSystemVMKeyFile(); String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); assert(controlIp != null); LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); String[] config = cfgtr.generateConfiguration(cmd); String[][] rules = cfgtr.generateFwRules(cmd); String tmpCfgFilePath = "/tmp/" + routerIp.replace('.', '_') + ".cfg"; String tmpCfgFileContents = ""; for (int i = 0; i < config.length; i++) { tmpCfgFileContents += config[i]; tmpCfgFileContents += "\n"; } try { SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/tmp/", tmpCfgFileContents.getBytes(), routerIp.replace('.', '_') + ".cfg", null); try { String[] addRules = rules[LoadBalancerConfigurator.ADD]; String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; String[] statRules = rules[LoadBalancerConfigurator.STATS]; String args = ""; args += "-i " + routerIp; args += " -f " + tmpCfgFilePath; StringBuilder sb = new StringBuilder(); if (addRules.length > 0) { for (int i = 0; i < addRules.length; i++) { sb.append(addRules[i]).append(','); } args += " -a " + sb.toString(); } sb = new StringBuilder(); if (removeRules.length > 0) { for (int i = 0; i < removeRules.length; i++) { sb.append(removeRules[i]).append(','); } args += " -d " + sb.toString(); } sb = new StringBuilder(); if (statRules.length > 0) { for (int i = 0; i < statRules.length; i++) { sb.append(statRules[i]).append(','); } args += " -s " + sb.toString(); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "scp " + tmpCfgFilePath + " /etc/haproxy/haproxy.cfg.new"); if (!result.first()) { s_logger.error("Unable to copy haproxy configuration file"); return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to uanble to copy haproxy configuration file"); } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + routerIp + ", /root/loadbalancer.sh " + args); } result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/loadbalancer.sh " + args); if (!result.first()) { String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new Answer(cmd, false, msg); } if (s_logger.isInfoEnabled()) { s_logger.info("LoadBalancerConfigCommand on domain router " + routerIp + " completed"); } } finally { SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); } return new Answer(cmd); } catch (Throwable e) { s_logger.error("Unexpected exception: " + e.toString(), e); return new Answer(cmd, false, "LoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); } } // // list available ethx devices // ls /proc/sys/net/ipv4/conf // private int allocRouterEthDeviceIndex(String domrName, String routerIp) throws Exception { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); if(result.first()) { String[] tokens = result.second().split("\\s+"); HashMap<String, String> deviceNames = new HashMap<String, String>(); for(String token: tokens) { if(!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { deviceNames.put(token, token); } } for(int i = 1; ; i++) { if(!deviceNames.containsKey("eth" + i)) return i; } } return -1; } // // find mac address of a specified ethx device // ip address show ethx | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2 // returns // eth0:xx.xx.xx.xx // // list IP with eth devices // ifconfig ethx |grep -B1 "inet addr" | awk '{ if ( $1 == "inet" ) { print $2 } else if ( $2 == "Link" ) { printf "%s:" ,$1 } }' // | awk -F: '{ print $1 ": " $3 }' // // returns // eth0:xx.xx.xx.xx // // private int findRouterEthDeviceIndex(String domrName, String routerIp, String mac) throws Exception { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); s_logger.info("findRouterEthDeviceIndex. mac: " + mac); // TODO : this is a temporary very inefficient solution, will refactor it later Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "ls /proc/sys/net/ipv4/conf"); // when we dynamically plug in a new NIC into virtual router, it may take time to show up in guest OS // we use a waiting loop here as a workaround to synchronize activities in systems long startTick = System.currentTimeMillis(); while(System.currentTimeMillis() - startTick < 15000) { if(result.first()) { String[] tokens = result.second().split("\\s+"); for(String token : tokens) { if(!("all".equalsIgnoreCase(token) || "default".equalsIgnoreCase(token) || "lo".equalsIgnoreCase(token))) { String cmd = String.format("ip address show %s | grep link/ether | sed -e 's/^[ \t]*//' | cut -d' ' -f2", token); if(s_logger.isDebugEnabled()) s_logger.debug("Run domr script " + cmd); Pair<Boolean, String> result2 = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, // TODO need to find the dev index inside router based on IP address cmd); if(s_logger.isDebugEnabled()) s_logger.debug("result: " + result2.first() + ", output: " + result2.second()); if(result2.first() && result2.second().trim().equalsIgnoreCase(mac.trim())) return Integer.parseInt(token.substring(3)); } } } s_logger.warn("can not find intereface associated with mac: " + mac + ", guest OS may still at loading state, retry..."); try { Thread.currentThread().sleep(1000); } catch (InterruptedException e) { } } return -1; } private VirtualDevice findVirtualNicDevice(VirtualMachineMO vmMo, String mac) throws Exception { VirtualDevice[] nics = vmMo.getNicDevices(); for(VirtualDevice nic : nics) { if(nic instanceof VirtualEthernetCard) { if(((VirtualEthernetCard)nic).getMacAddress().equals(mac)) return nic; } } return null; } private SetupGuestNetworkAnswer execute(SetupGuestNetworkCommand cmd) { s_logger.info("Executing resource SetupGuestNetworkCommand " + _gson.toJson(cmd)); VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); NicTO nic = cmd.getNic(); String routerIp = getRouterSshControlIp(cmd); String domrGIP = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); String domrName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String gw = cmd.getAccessDetail(NetworkElementCommand.GUEST_NETWORK_GATEWAY); String cidr = Long.toString(NetUtils.getCidrSize(nic.getNetmask())); String domainName = cmd.getNetworkDomain(); String dns = cmd.getDefaultDns1(); if (dns == null || dns.isEmpty()) { dns = cmd.getDefaultDns2(); } else { String dns2= cmd.getDefaultDns2(); if ( dns2 != null && !dns2.isEmpty()) { dns += "," + dns2; } } try { int ethDeviceNum = findRouterEthDeviceIndex(domrName, routerIp, nic.getMac()); s_logger.info("find interface index. routerIp: " + routerIp + ", mac: " + nic.getMac() + ", index: " + ethDeviceNum); String args =(cmd.isAdd()?"-C":"-D"); String dev = "eth" + ethDeviceNum; args += " -d " + dev; args += " -i " + domrGIP; args += " -g " + gw; args += " -m " + cidr; args += " -n " + NetUtils.getSubNet(domrGIP, nic.getNetmask()); if ( dns != null && !dns.isEmpty() ) { args += " -s " + dns; } if ( domainName != null && !domainName.isEmpty() ) { args += " -e " + domainName; } Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_guestnw.sh " + args); if (!result.first()) { String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetupGuestNetworkAnswer(cmd, false, msg); } if (s_logger.isInfoEnabled()) { s_logger.info("SetupGuestNetworkCommand on domain router " + routerIp + " completed"); } return new SetupGuestNetworkAnswer(cmd, true, "success"); } catch (Exception e) { String msg = "SetupGuestNetwork failed due to " + e.toString(); s_logger.warn(msg, e); return new SetupGuestNetworkAnswer(cmd, false, msg); } } protected IpAssocAnswer execute(IpAssocVpcCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource IpAssocVpcCommand " + _gson.toJson(cmd)); } String[] results = new String[cmd.getIpAddresses().length]; int i = 0; String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIp = getRouterSshControlIp(cmd); try { IpAddressTO[] ips = cmd.getIpAddresses(); for (IpAddressTO ip : ips) { assignVPCPublicIpAddress(routerName, routerIp, ip); results[i++] = ip.getPublicIp() + " - success"; } } catch (Exception e) { s_logger.error("Ip Assoc failure on applying one ip due to exception: ", e); results[i++] = IpAssocAnswer.errorResult; } return new IpAssocAnswer(cmd, results); } protected SetSourceNatAnswer execute(SetSourceNatCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetSourceNatCommand " + _gson.toJson(cmd)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String routerIp = getRouterSshControlIp(cmd); IpAddressTO pubIp = cmd.getIpAddress(); try { int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, pubIp.getVifMacAddress()); String args = ""; args += " -A "; args += " -l "; args += pubIp.getPublicIp(); args += " -c "; args += "eth" + ethDeviceNum; Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_snat.sh " + args); if (!result.first()) { String msg = "SetupGuestNetworkCommand on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetSourceNatAnswer(cmd, false, msg); } return new SetSourceNatAnswer(cmd, true, "success"); } catch (Exception e) { String msg = "Ip SNAT failure due to " + e.toString(); s_logger.error(msg, e); return new SetSourceNatAnswer(cmd, false, msg); } } private SetNetworkACLAnswer execute(SetNetworkACLCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetNetworkACLCommand " + _gson.toJson(cmd)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String privateGw = cmd.getAccessDetail(NetworkElementCommand.VPC_PRIVATE_GATEWAY); String routerIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; try { String [][] rules = cmd.generateFwRules(); StringBuilder sb = new StringBuilder(); String[] aclRules = rules[0]; if (aclRules.length == 0) { return new SetNetworkACLAnswer(cmd, true, results); } for (int i = 0; i < aclRules.length; i++) { sb.append(aclRules[i]).append(','); } NicTO nic = cmd.getNic(); int ethDeviceNum = findRouterEthDeviceIndex(routerName, routerIp, nic.getMac()); String args = ""; Pair<Boolean, String> result; if (privateGw != null) { s_logger.debug("Private gateway configuration is set"); args += " -d " + "eth" + ethDeviceNum; args += " -a " + sb.toString(); result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_privategw_acl.sh " + args); if (!result.first()) { String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetNetworkACLAnswer(cmd, false, results); } } else { args=""; args += " -d " + "eth" + ethDeviceNum; args += " -i " + nic.getIp(); args += " -m " + Long.toString(NetUtils.getCidrSize(nic.getNetmask())); args += " -a " + sb.toString(); result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_acl.sh " + args); if (!result.first()) { String msg = "SetNetworkACLAnswer on domain router " + routerIp + " failed. message: " + result.second(); s_logger.error(msg); return new SetNetworkACLAnswer(cmd, false, results); } } return new SetNetworkACLAnswer(cmd, true, results); } catch (Exception e) { String msg = "SetNetworkACL failed due to " + e.toString(); s_logger.error(msg, e); return new SetNetworkACLAnswer(cmd, false, results); } } protected SetPortForwardingRulesAnswer execute(SetPortForwardingRulesVpcCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetPortForwardingRulesVpcCommand " + _gson.toJson(cmd)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerIp = getRouterSshControlIp(cmd); String[] results = new String[cmd.getRules().length]; int i = 0; boolean endResult = true; for (PortForwardingRuleTO rule : cmd.getRules()) { String args =""; args += rule.revoked() ? " -D" : " -A"; args += " -P " + rule.getProtocol().toLowerCase(); args += " -l " + rule.getSrcIp(); args += " -p " + rule.getStringSrcPortRange(); args += " -r " + rule.getDstIp(); args += " -d " + rule.getStringDstPortRange().replace(":", "-"); try { Pair<Boolean, String> sshResult = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_portforwarding.sh " + args); if (!sshResult.first()) { results[i++] = "Failed"; endResult = false; } else { results[i++] = null; } } catch(Exception e) { results[i++] = "Failed"; endResult = false; } } return new SetPortForwardingRulesAnswer(cmd, results, endResult); } protected Answer execute(Site2SiteVpnCfgCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource Site2SiteVpnCfgCommand " + _gson.toJson(cmd)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String routerIp = getRouterSshControlIp(cmd); String args =""; if (cmd.isCreate()) { args += " -A"; args += " -l "; args += cmd.getLocalPublicIp(); args += " -n "; args += cmd.getLocalGuestCidr(); args += " -g "; args += cmd.getLocalPublicGateway(); args += " -r "; args += cmd.getPeerGatewayIp(); args += " -N "; args += cmd.getPeerGuestCidrList(); args += " -e "; args += "\"" + cmd.getEspPolicy() + "\""; args += " -i "; args += "\"" + cmd.getIkePolicy() + "\""; args += " -t "; args += Long.toString(cmd.getIkeLifetime()); args += " -T "; args += Long.toString(cmd.getEspLifetime()); args += " -s "; args += "\"" + cmd.getIpsecPsk() + "\""; args += " -d "; if (cmd.getDpd()) { args += "1"; } else { args += "0"; } } else { args += " -D"; args += " -r "; args += cmd.getPeerGatewayIp(); args += " -n "; args += cmd.getLocalGuestCidr(); args += " -N "; args += cmd.getPeerGuestCidrList(); } Pair<Boolean, String> result; try { result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/ipsectunnel.sh " + args); if (!result.first()) { s_logger.error("Setup site2site VPN " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new Answer(cmd, false, "Setup site2site VPN falied due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("setup site 2 site vpn on router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "Setup site2site VPN falied due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, "Setup site2site VPN failed due to " + VmwareHelper.getExceptionMessage(e)); } return new Answer(cmd, true, result.second()); } private PlugNicAnswer execute(PlugNicCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PlugNicCommand " + _gson.toJson(cmd)); } getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); String vmName = cmd.getVmName(); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if(vmMo == null) { if(hyperHost instanceof HostMO) { ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO)hyperHost).getParentMor()); vmMo = clusterMo.findVmOnHyperHost(vmName); } } if (vmMo == null) { String msg = "Router " + vmName + " no longer exists to execute PlugNic command"; s_logger.error(msg); throw new Exception(msg); } if(!isVMWareToolsInstalled(vmMo)){ String errMsg = "vmware tools is not installed or not running, cannot add nic to vm " + vmName; s_logger.debug(errMsg); return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + errMsg); } // TODO need a way to specify the control of NIC device type VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.E1000; // find a usable device number in VMware environment VirtualDevice[] nicDevices = vmMo.getNicDevices(); int deviceNumber = -1; for(VirtualDevice device : nicDevices) { if(device.getUnitNumber() > deviceNumber) deviceNumber = device.getUnitNumber(); } deviceNumber++; NicTO nicTo = cmd.getNic(); VirtualDevice nic; Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, false, cmd.getVMType());; if (VmwareHelper.isDvPortGroup(networkInfo.first())) { String dvSwitchUuid; ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter(); DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor); ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first()); dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor); s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid); nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), deviceNumber, deviceNumber + 1, true, true); } else { s_logger.info("Preparing NIC device on network " + networkInfo.second()); nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), deviceNumber, deviceNumber + 1, true, true); } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(nic); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when running PlugNicCommand"); } return new PlugNicAnswer(cmd, true, "success"); } catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new PlugNicAnswer(cmd, false, "Unable to execute PlugNicCommand due to " + e.toString()); } } private UnPlugNicAnswer execute(UnPlugNicCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource UnPlugNicCommand " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); String vmName = cmd.getVmName(); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if(vmMo == null) { if(hyperHost instanceof HostMO) { ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO)hyperHost).getParentMor()); vmMo = clusterMo.findVmOnHyperHost(vmName); } } if (vmMo == null) { String msg = "VM " + vmName + " no longer exists to execute UnPlugNic command"; s_logger.error(msg); throw new Exception(msg); } if(!isVMWareToolsInstalled(vmMo)){ String errMsg = "vmware tools not installed or not running, cannot remove nic from vm " + vmName; s_logger.debug(errMsg); return new UnPlugNicAnswer(cmd, false, "Unable to execute unPlugNicCommand due to " + errMsg); } VirtualDevice nic = findVirtualNicDevice(vmMo, cmd.getNic().getMac()); if ( nic == null ) { return new UnPlugNicAnswer(cmd, true, "success"); } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(nic); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.REMOVE); vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when running unplugNicCommand"); } return new UnPlugNicAnswer(cmd, true, "success"); } catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new UnPlugNicAnswer(cmd, false, "Unable to execute unPlugNicCommand due to " + e.toString()); } } protected void assignVPCPublicIpAddress(String domrName, String routerIp, IpAddressTO ip) throws Exception { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource assignVPCPublicIpAddress. domrName: " + domrName + ", routerIp: " + routerIp + ", ip: " + _gson.toJson(ip)); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); int ethDeviceNum = findRouterEthDeviceIndex(domrName, routerIp, ip.getVifMacAddress()); if (ethDeviceNum < 0) { if (ip.isAdd()) { throw new InternalErrorException("Failed to find DomR VIF to associate/disassociate IP with."); } else { s_logger.debug("VIF to deassociate IP with does not exist, return success"); return; } } String args = ""; String snatArgs = ""; if (ip.isAdd()) { args += " -A "; snatArgs += " -A "; } else { args += " -D "; snatArgs += " -D "; } args += " -l "; args += ip.getPublicIp(); args += " -c "; args += "eth" + ethDeviceNum; args += " -g "; args += ip.getVlanGateway(); args += " -m "; args += Long.toString(NetUtils.getCidrSize(ip.getVlanNetmask())); args += " -n "; args += NetUtils.getSubNet(ip.getPublicIp(), ip.getVlanNetmask()); Pair<Boolean, String> result = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_ipassoc.sh " + args); if (!result.first()) { throw new InternalErrorException("Unable to assign public IP address"); } if (ip.isSourceNat()) { snatArgs += " -l "; snatArgs += ip.getPublicIp(); snatArgs += " -c "; snatArgs += "eth" + ethDeviceNum; Pair<Boolean, String> result_gateway = SshHelper.sshExecute(routerIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_privateGateway.sh " + snatArgs); if (!result_gateway.first()) { throw new InternalErrorException("Unable to configure source NAT for public IP address."); } } } protected void assignPublicIpAddress(VirtualMachineMO vmMo, final String vmName, final String privateIpAddress, final String publicIpAddress, final boolean add, final boolean firstIP, final boolean sourceNat, final String vlanId, final String vlanGateway, final String vlanNetmask, final String vifMacAddress) throws Exception { String publicNeworkName = HypervisorHostHelper.getPublicNetworkNamePrefix(vlanId); Pair<Integer, VirtualDevice> publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); if (s_logger.isDebugEnabled()) { s_logger.debug("Find public NIC index, public network name: " + publicNeworkName + ", index: " + publicNicInfo.first()); } boolean addVif = false; boolean removeVif = false; if (add && publicNicInfo.first().intValue() == -1) { if (s_logger.isDebugEnabled()) { s_logger.debug("Plug new NIC to associate" + privateIpAddress + " to " + publicIpAddress); } addVif = true; } else if (!add && firstIP) { removeVif = true; if (s_logger.isDebugEnabled()) { s_logger.debug("Unplug NIC " + publicNicInfo.first()); } } if (addVif) { plugPublicNic(vmMo, vlanId, vifMacAddress); publicNicInfo = vmMo.getNicDeviceIndex(publicNeworkName); if (publicNicInfo.first().intValue() >= 0) { networkUsage(privateIpAddress, "addVif", "eth" + publicNicInfo.first()); } } if (publicNicInfo.first().intValue() < 0) { String msg = "Failed to find DomR VIF to associate/disassociate IP with."; s_logger.error(msg); throw new InternalErrorException(msg); } String args = null; if (add) { args = " -A "; } else { args = " -D "; } if (sourceNat) { args += " -s "; } if (firstIP) { args += " -f "; } String cidrSize = Long.toString(NetUtils.getCidrSize(vlanNetmask)); args += " -l "; args += publicIpAddress + "/" + cidrSize; args += " -c "; args += "eth" + publicNicInfo.first(); args += " -g "; args += vlanGateway; if (addVif) { args += " -n "; } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + privateIpAddress + ", /opt/cloud/bin/ipassoc.sh " + args); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/ipassoc.sh " + args); if (!result.first()) { s_logger.error("ipassoc command on domain router " + privateIpAddress + " failed. message: " + result.second()); throw new Exception("ipassoc failed due to " + result.second()); } if (removeVif) { String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); int nicMasks = Integer.parseInt(nicMasksStr); nicMasks &= ~(1 << publicNicInfo.first().intValue()); vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); HostMO hostMo = vmMo.getRunningHost(); List<NetworkDetails> networks = vmMo.getNetworksWithDetails(); for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { cleanupNetwork(hostMo, netDetails); } } } } if (s_logger.isInfoEnabled()) { s_logger.info("ipassoc command on domain router " + privateIpAddress + " completed"); } } private void plugPublicNic(VirtualMachineMO vmMo, final String vlanId, final String vifMacAddress) throws Exception { // TODO : probably need to set traffic shaping Pair<ManagedObjectReference, String> networkInfo = null; VirtualSwitchType vSwitchType = VirtualSwitchType.StandardVirtualSwitch; if (_publicTrafficInfo != null) { vSwitchType = _publicTrafficInfo.getVirtualSwitchType(); } /** FIXME We have no clue which network this nic is on and that means that we can't figure out the BroadcastDomainType * so we assume that it's VLAN for now */ if (VirtualSwitchType.StandardVirtualSwitch == vSwitchType) { networkInfo = HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, _ops_timeout, true, BroadcastDomainType.Vlan, null); } else { networkInfo = HypervisorHostHelper.prepareNetwork(_publicTrafficInfo.getVirtualSwitchName(), "cloud.public", vmMo.getRunningHost(), vlanId, null, null, null, _ops_timeout, vSwitchType, _portsPerDvPortGroup, null, false, BroadcastDomainType.Vlan); } int nicIndex = allocPublicNicIndex(vmMo); try { VirtualDevice[] nicDevices = vmMo.getNicDevices(); VirtualEthernetCard device = (VirtualEthernetCard) nicDevices[nicIndex]; if (VirtualSwitchType.StandardVirtualSwitch == vSwitchType) { VirtualEthernetCardNetworkBackingInfo nicBacking = new VirtualEthernetCardNetworkBackingInfo(); nicBacking.setDeviceName(networkInfo.second()); nicBacking.setNetwork(networkInfo.first()); device.setBacking(nicBacking); } else { HostMO hostMo = vmMo.getRunningHost(); DatacenterMO dataCenterMo = new DatacenterMO(hostMo.getContext(), hostMo.getHyperHostDatacenter()); device.setBacking(dataCenterMo.getDvPortBackingInfo(networkInfo)); } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); //VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[1]; VirtualDeviceConfigSpec deviceConfigSpec = new VirtualDeviceConfigSpec(); deviceConfigSpec.setDevice(device); deviceConfigSpec.setOperation(VirtualDeviceConfigSpecOperation.EDIT); vmConfigSpec.getDeviceChange().add(deviceConfigSpec); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure devices when plugPublicNic"); } } catch(Exception e) { // restore allocation mask in case of exceptions String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); int nicMasks = Integer.parseInt(nicMasksStr); nicMasks &= ~(1 << nicIndex); vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); throw e; } } private int allocPublicNicIndex(VirtualMachineMO vmMo) throws Exception { String nicMasksStr = vmMo.getCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK); if(nicMasksStr == null || nicMasksStr.isEmpty()) { throw new Exception("Could not find NIC allocation info"); } int nicMasks = Integer.parseInt(nicMasksStr); VirtualDevice[] nicDevices = vmMo.getNicDevices(); for(int i = 3; i < nicDevices.length; i++) { if((nicMasks & (1 << i)) == 0) { nicMasks |= (1 << i); vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMasks)); return i; } } throw new Exception("Could not allocate a free public NIC"); } protected Answer execute(IpAssocCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource IPAssocCommand: " + _gson.toJson(cmd)); } int i = 0; String[] results = new String[cmd.getIpAddresses().length]; VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); IpAddressTO[] ips = cmd.getIpAddresses(); String routerName = cmd.getAccessDetail(NetworkElementCommand.ROUTER_NAME); String controlIp = VmwareResource.getRouterSshControlIp(cmd); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(routerName); // command may sometimes be redirect to a wrong host, we relax // the check and will try to find it within cluster if(vmMo == null) { if(hyperHost instanceof HostMO) { ClusterMO clusterMo = new ClusterMO(hyperHost.getContext(), ((HostMO)hyperHost).getParentMor()); vmMo = clusterMo.findVmOnHyperHost(routerName); } } if (vmMo == null) { String msg = "Router " + routerName + " no longer exists to execute IPAssoc command"; s_logger.error(msg); throw new Exception(msg); } for (IpAddressTO ip : ips) { assignPublicIpAddress(vmMo, routerName, controlIp, ip.getPublicIp(), ip.isAdd(), ip.isFirstIP(), ip.isSourceNat(), ip.getVlanId(), ip.getVlanGateway(), ip.getVlanNetmask(), ip.getVifMacAddress()); results[i++] = ip.getPublicIp() + " - success"; } } catch (Throwable e) { s_logger.error("Unexpected exception: " + e.toString() + " will shortcut rest of IPAssoc commands", e); for (; i < cmd.getIpAddresses().length; i++) { results[i++] = IpAssocAnswer.errorResult; } } return new IpAssocAnswer(cmd, results); } protected Answer execute(SavePasswordCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SavePasswordCommand. vmName: " + cmd.getVmName() + ", vmIp: " + cmd.getVmIpAddress() + ", password: " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } String controlIp = getRouterSshControlIp(cmd); final String password = cmd.getPassword(); final String vmIpAddress = cmd.getVmIpAddress(); // Run save_password_to_domr.sh String args = " -v " + vmIpAddress; if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + controlIp + ", /root/savepassword.sh " + args + " -p " + StringUtils.getMaskedPasswordForDisplay(cmd.getPassword())); } args += " -p " + password; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/savepassword.sh " + args); if (!result.first()) { s_logger.error("savepassword command on domain router " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "SavePassword failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("savepassword command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "SavePasswordCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(DhcpEntryCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DhcpEntryCommand: " + _gson.toJson(cmd)); } // ssh -p 3922 -o StrictHostKeyChecking=no -i $cert root@$domr "/root/edithosts.sh $mac $ip $vm $dfltrt $ns $staticrt" >/dev/null String args = " -m " + cmd.getVmMac(); if (cmd.getVmIpAddress() != null) { args += " -4 " + cmd.getVmIpAddress(); } args += " -h " + cmd.getVmName(); if (cmd.getDefaultRouter() != null) { args += " -d " + cmd.getDefaultRouter(); } if (cmd.getDefaultDns() != null) { args += " -n " + cmd.getDefaultDns(); } if (cmd.getStaticRoutes() != null) { args += " -s " + cmd.getStaticRoutes(); } if (cmd.getVmIp6Address() != null) { args += " -6 " + cmd.getVmIp6Address(); args += " -u " + cmd.getDuid(); } if (!cmd.isDefault()) { args += " -N"; } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/edithosts.sh " + args); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/edithosts.sh " + args); if (!result.first()) { s_logger.error("dhcp_entry command on domR " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "DhcpEntry failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("dhcp_entry command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "DhcpEntryCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(final CreateIpAliasCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing createipAlias command: " + _gson.toJson(cmd)); } String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); List<IpAliasTO> ipAliasTOs = cmd.getIpAliasList(); String args=routerIp+" "; for (IpAliasTO ipaliasto : ipAliasTOs) { args = args + ipaliasto.getAlias_count()+":"+ipaliasto.getRouterip()+":"+ipaliasto.getNetmask()+"-"; } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/createipAlias " + args); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/createipAlias.sh " + args); if (!result.first()) { s_logger.error("ipAlias command on domr " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "createipAlias failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("createipAlias command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "createipAlias failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(final DeleteIpAliasCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); List<IpAliasTO> revokedIpAliasTOs = cmd.getDeleteIpAliasTos(); List<IpAliasTO> activeIpAliasTOs = cmd.getCreateIpAliasTos(); if (s_logger.isInfoEnabled()) { s_logger.info("Executing deleteipAlias command: " + _gson.toJson(cmd)); } String args=routerIp+" "; for (IpAliasTO ipAliasTO : revokedIpAliasTOs) { args = args + ipAliasTO.getAlias_count()+":"+ipAliasTO.getRouterip()+":"+ipAliasTO.getNetmask()+"-"; } args = args + "- " ; for (IpAliasTO ipAliasTO : activeIpAliasTOs) { args = args + ipAliasTO.getAlias_count()+":"+ipAliasTO.getRouterip()+":"+ipAliasTO.getNetmask()+"-"; } if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/deleteipAlias " + args); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/deleteipAlias.sh " + args); if (!result.first()) { s_logger.error("ipAlias command on domr " + controlIp + " failed, message: " + result.second()); return new Answer(cmd, false, "deleteipAlias failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("deleteipAlias command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "deleteipAlias failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected Answer execute(final DnsMasqConfigCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing dnsmasqConfig command: " + _gson.toJson(cmd)); } String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); assert(controlIp != null); List<DhcpTO> dhcpTos = cmd.getIps(); String args =""; for(DhcpTO dhcpTo : dhcpTos) { args = args + dhcpTo.getRouterIp()+":"+dhcpTo.getGateway()+":"+dhcpTo.getNetmask()+":"+dhcpTo.getStartIpOfSubnet()+"-"; } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); File keyFile = mgr.getSystemVMKeyFile(); try { Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/dnsmasq.sh " + args); if (s_logger.isDebugEnabled()) { s_logger.debug("Run command on domain router " + routerIp + ", /root/dnsmasq.sh"); } if (!result.first()) { s_logger.error("Unable update dnsmasq config file"); return new Answer(cmd, false, "dnsmasq config update failed due to: " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("dnsmasq config command on domain router " + routerIp + " completed"); } }catch (Throwable e) { String msg = "Dnsmasqconfig command failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected CheckS2SVpnConnectionsAnswer execute(CheckS2SVpnConnectionsCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckS2SVpnConnectionsCommand: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkbatchs2svpn.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); String cmdline = "/opt/cloud/bin/checkbatchs2svpn.sh "; for (String ip : cmd.getVpnIps()) { cmdline += " " + ip; } result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, cmdline); if (!result.first()) { s_logger.error("check site-to-site vpn connections command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new CheckS2SVpnConnectionsAnswer(cmd, false, result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("check site-to-site vpn connections command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "CheckS2SVpnConnectionsCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CheckS2SVpnConnectionsAnswer(cmd, false, "CheckS2SVpnConneciontsCommand failed"); } return new CheckS2SVpnConnectionsAnswer(cmd, true, result.second()); } protected Answer execute(CheckRouterCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource CheckRouterCommand: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/checkrouter.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/checkrouter.sh "); if (!result.first()) { s_logger.error("check router command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new CheckRouterAnswer(cmd, "CheckRouter failed due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("check router command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "CheckRouterCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CheckRouterAnswer(cmd, msg); } return new CheckRouterAnswer(cmd, result.second(), true); } protected Answer execute(GetDomRVersionCmd cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource GetDomRVersionCmd: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /opt/cloud/bin/get_template_version.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/get_template_version.sh "); if (!result.first()) { s_logger.error("GetDomRVersionCmd on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new GetDomRVersionAnswer(cmd, "GetDomRVersionCmd failed due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("GetDomRVersionCmd on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "GetDomRVersionCmd failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new GetDomRVersionAnswer(cmd, msg); } String[] lines = result.second().split("&"); if (lines.length != 2) { return new GetDomRVersionAnswer(cmd, result.second()); } return new GetDomRVersionAnswer(cmd, result.second(), lines[0], lines[1]); } protected Answer execute(BumpUpPriorityCommand cmd) { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing resource BumpUpPriorityCommand: " + _gson.toJson(cmd)); s_logger.debug("Run command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", /root/bumpup_priority.sh "); } Pair<Boolean, String> result; try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/bumpup_priority.sh "); if (!result.first()) { s_logger.error("BumpUpPriority command on domR " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " failed, message: " + result.second()); return new Answer(cmd, false, "BumpUpPriorityCommand failed due to " + result.second()); } if (s_logger.isDebugEnabled()) { s_logger.debug("BumpUpPriorityCommand on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + " completed"); } } catch (Throwable e) { String msg = "BumpUpPriorityCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } if (result.second() == null || result.second().isEmpty()) { return new Answer(cmd, true, result.second()); } return new Answer(cmd, false, result.second()); } protected Answer execute(VmDataCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource VmDataCommand: " + _gson.toJson(cmd)); } String routerPrivateIpAddress = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String controlIp = getRouterSshControlIp(cmd); String vmIpAddress = cmd.getVmIpAddress(); List<String[]> vmData = cmd.getVmData(); String[] vmDataArgs = new String[vmData.size() * 2 + 4]; vmDataArgs[0] = "routerIP"; vmDataArgs[1] = routerPrivateIpAddress; vmDataArgs[2] = "vmIP"; vmDataArgs[3] = vmIpAddress; int i = 4; for (String[] vmDataEntry : vmData) { String folder = vmDataEntry[0]; String file = vmDataEntry[1]; String contents = (vmDataEntry[2] != null) ? vmDataEntry[2] : "none"; vmDataArgs[i] = folder + "," + file; vmDataArgs[i + 1] = contents; i += 2; } String content = encodeDataArgs(vmDataArgs); String tmpFileName = UUID.randomUUID().toString(); if (s_logger.isDebugEnabled()) { s_logger.debug("Run vm_data command on domain router " + cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP) + ", data: " + content); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/tmp", content.getBytes(), tmpFileName, null); try { Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/root/userdata.py " + tmpFileName); if (!result.first()) { s_logger.error("vm_data command on domain router " + controlIp + " failed. messge: " + result.second()); return new Answer(cmd, false, "VmDataCommand failed due to " + result.second()); } } finally { SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm /tmp/" + tmpFileName); } if (s_logger.isInfoEnabled()) { s_logger.info("vm_data command on domain router " + controlIp + " completed"); } } catch (Throwable e) { String msg = "VmDataCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } private String encodeDataArgs(String[] dataArgs) { StringBuilder sb = new StringBuilder(); for (String arg : dataArgs) { sb.append(arg); sb.append("\n"); } return sb.toString(); } protected CheckSshAnswer execute(CheckSshCommand cmd) { String vmName = cmd.getName(); String privateIp = cmd.getIp(); int cmdPort = cmd.getPort(); if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port, " + privateIp + ":" + cmdPort); } try { String result = connect(cmd.getName(), privateIp, cmdPort); if (result != null) { s_logger.error("Can not ping System vm " + vmName + "due to:" + result); return new CheckSshAnswer(cmd, "Can not ping System vm " + vmName + "due to:" + result); } } catch (Exception e) { s_logger.error("Can not ping System vm " + vmName + "due to exception"); return new CheckSshAnswer(cmd, e); } if (s_logger.isDebugEnabled()) { s_logger.debug("Ping command port succeeded for vm " + vmName); } if (VirtualMachineName.isValidRouterName(vmName)) { if (s_logger.isDebugEnabled()) { s_logger.debug("Execute network usage setup command on " + vmName); } networkUsage(privateIp, "create", null); } return new CheckSshAnswer(cmd); } private DiskTO[] validateDisks(DiskTO[] disks) { List<DiskTO> validatedDisks = new ArrayList<DiskTO>(); for (DiskTO vol : disks) { if (vol.getType() != Volume.Type.ISO) { VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); if (primaryStore.getUuid() != null && !primaryStore.getUuid().isEmpty()) { validatedDisks.add(vol); } } else if (vol.getType() == Volume.Type.ISO) { TemplateObjectTO templateTO = (TemplateObjectTO)vol.getData(); if (templateTO.getPath() != null && !templateTO.getPath().isEmpty()) { validatedDisks.add(vol); } } else { if (s_logger.isDebugEnabled()) { s_logger.debug("Drop invalid disk option, volumeTO: " + _gson.toJson(vol)); } } } return validatedDisks.toArray(new DiskTO[0]); } protected ScaleVmAnswer execute(ScaleVmCommand cmd) { VmwareContext context = getServiceContext(); VirtualMachineTO vmSpec = cmd.getVirtualMachine(); try{ VmwareHypervisorHost hyperHost = getHyperHost(context); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); int ramMb = (int) (vmSpec.getMinRam()/(1024 * 1024)); long hotaddIncrementSizeInMb; long hotaddMemoryLimitInMb; long requestedMaxMemoryInMb = vmSpec.getMaxRam() / (1024 * 1024); // Check if VM is really running on hypervisor host if (getVmState(vmMo) != State.Running) { throw new CloudRuntimeException("Found that the VM " + vmMo.getVmName() + " is not running. Unable to scale-up this VM"); } // Check max hot add limit hotaddIncrementSizeInMb = vmMo.getHotAddMemoryIncrementSizeInMb(); hotaddMemoryLimitInMb = vmMo.getHotAddMemoryLimitInMb(); if (requestedMaxMemoryInMb > hotaddMemoryLimitInMb) { throw new CloudRuntimeException("Memory of VM " + vmMo.getVmName() + " cannot be scaled to " + requestedMaxMemoryInMb + "MB." + " Requested memory limit is beyond the hotadd memory limit for this VM at the moment is " + hotaddMemoryLimitInMb + "MB."); } // Check increment is multiple of increment size long reminder = requestedMaxMemoryInMb % hotaddIncrementSizeInMb; if (reminder != 0) { requestedMaxMemoryInMb = requestedMaxMemoryInMb + hotaddIncrementSizeInMb - reminder; } // Check if license supports the feature VmwareHelper.isFeatureLicensed(hyperHost, FeatureKeyConstants.HOTPLUG); VmwareHelper .setVmScaleUpConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), vmSpec.getMinSpeed(), (int)requestedMaxMemoryInMb, ramMb, vmSpec.getLimitCpuUse()); if(!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Unable to execute ScaleVmCommand"); } }catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new ScaleVmAnswer(cmd, false, "Unable to execute ScaleVmCommand due to " + e.toString()); } return new ScaleVmAnswer(cmd, true, null); } protected StartAnswer execute(StartCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource StartCommand: " + _gson.toJson(cmd)); } VirtualMachineTO vmSpec = cmd.getVirtualMachine(); String vmName = vmSpec.getName(); State state = State.Stopped; VmwareContext context = getServiceContext(); try { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // mark VM as starting state so that sync() can know not to report stopped too early synchronized (_vms) { _vms.put(vmName, State.Starting); } VirtualEthernetCardType nicDeviceType = VirtualEthernetCardType.valueOf(vmSpec.getDetails().get(VmDetailConstants.NIC_ADAPTER)); if(s_logger.isDebugEnabled()) s_logger.debug("VM " + vmName + " will be started with NIC device type: " + nicDeviceType); VmwareHypervisorHost hyperHost = getHyperHost(context); DiskTO[] disks = validateDisks(vmSpec.getDisks()); assert (disks.length > 0); NicTO[] nics = vmSpec.getNics(); HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> dataStoresDetails = inferDatastoreDetailsFromDiskInfo(hyperHost, context, disks); if ((dataStoresDetails == null) || (dataStoresDetails.isEmpty()) ){ String msg = "Unable to locate datastore details of the volumes to be attached"; s_logger.error(msg); throw new Exception(msg); } VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo != null) { s_logger.info("VM " + vmName + " already exists, tear down devices for reconfiguration"); if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.ensureScsiDeviceController(); } else { ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); assert (morDc != null); vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo != null) { if (s_logger.isInfoEnabled()) { s_logger.info("Found vm " + vmName + " at other host, relocate to " + hyperHost.getHyperHostName()); } takeVmFromOtherHyperHost(hyperHost, vmName); if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.ensureScsiDeviceController(); } else { int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); Pair<ManagedObjectReference, DatastoreMO> rootDiskDataStoreDetails = null; for (DiskTO vol : disks) { if (vol.getType() == Volume.Type.ROOT) { PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)vol.getData().getDataStore(); rootDiskDataStoreDetails = dataStoresDetails.get(primaryStore.getUuid()); } } assert (vmSpec.getMinSpeed() != null) && (rootDiskDataStoreDetails != null); if (!hyperHost.createBlankVm(vmName, vmSpec.getCpus(), vmSpec.getMaxSpeed().intValue(), vmSpec.getMinSpeed(), vmSpec.getLimitCpuUse(),(int)(vmSpec.getMaxRam()/(1024*1024)), ramMb, translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), rootDiskDataStoreDetails.first(), false)) { throw new Exception("Failed to create VM. vmName: " + vmName); } } vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo == null) { throw new Exception("Failed to find the newly create or relocated VM. vmName: " + vmName); } } int totalChangeDevices = disks.length + nics.length; DiskTO volIso = null; if (vmSpec.getType() != VirtualMachine.Type.User) { // system VM needs a patch ISO totalChangeDevices++; } else { for (DiskTO vol : disks) { if (vol.getType() == Volume.Type.ISO) { volIso = vol; break; } } if (volIso == null) totalChangeDevices++; } VirtualMachineConfigSpec vmConfigSpec = new VirtualMachineConfigSpec(); int ramMb = (int) (vmSpec.getMinRam() / (1024 * 1024)); VmwareHelper.setBasicVmConfig(vmConfigSpec, vmSpec.getCpus(), vmSpec.getMaxSpeed(), vmSpec.getMinSpeed(),(int) (vmSpec.getMaxRam()/(1024*1024)), ramMb, translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(), vmSpec.getLimitCpuUse()); String guestOsId = translateGuestOsIdentifier(vmSpec.getArch(), vmSpec.getOs()).value(); // Check for hotadd settings vmConfigSpec.setMemoryHotAddEnabled(vmMo.isMemoryHotAddSupported(guestOsId)); vmConfigSpec.setCpuHotAddEnabled(vmMo.isCpuHotAddSupported(guestOsId)); if ("true".equals(vmSpec.getDetails().get(VmDetailConstants.NESTED_VIRTUALIZATION_FLAG))) { s_logger.debug("Nested Virtualization enabled in configuration, checking hypervisor capability"); ManagedObjectReference hostMor = vmMo.getRunningHost().getMor(); ManagedObjectReference computeMor = context.getVimClient().getMoRefProp(hostMor, "parent"); ManagedObjectReference environmentBrowser = context.getVimClient().getMoRefProp(computeMor, "environmentBrowser"); HostCapability hostCapability = context.getService().queryTargetCapabilities(environmentBrowser, hostMor); if (hostCapability.isNestedHVSupported()) { s_logger.debug("Hypervisor supports nested virtualization, enabling for VM " + vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(true); } else { s_logger.warn("Hypervisor doesn't support nested virtualization, unable to set config for VM " +vmSpec.getName()); vmConfigSpec.setNestedHVEnabled(false); } } VirtualDeviceConfigSpec[] deviceConfigSpecArray = new VirtualDeviceConfigSpec[totalChangeDevices]; int i = 0; int ideUnitNumber = 0; int scsiUnitNumber =0; int nicUnitNumber = 0; int ideControllerKey = vmMo.getIDEDeviceControllerKey(); int scsiControllerKey = vmMo.getScsiDeviceControllerKey(); int controllerKey; String datastoreDiskPath; // prepare systemvm patch ISO if (vmSpec.getType() != VirtualMachine.Type.User) { // attach ISO (for patching of system VM) String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); if(secStoreUrl == null) { String msg = "secondary storage for dc " + _dcId + " is not ready yet?"; throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; throw new Exception(msg); } DatastoreMO secDsMo = new DatastoreMO(hyperHost.getContext(), morSecDs); deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, String.format("[%s] systemvm/%s", secDsMo.getName(), mgr.getSystemVMIsoFileNameOnDatastore()), secDsMo.getMor(), true, true, ideUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } } else { // we will always plugin a CDROM device if (volIso != null) { TemplateObjectTO iso = (TemplateObjectTO)volIso.getData(); if (iso.getPath() != null && !iso.getPath().isEmpty()) { DataStoreTO imageStore = iso.getDataStore(); if (!(imageStore instanceof NfsTO)) { s_logger.debug("unsupported protocol"); throw new Exception("unsupported protocol"); } NfsTO nfsImageStore = (NfsTO)imageStore; String isoPath = nfsImageStore.getUrl() + File.separator + iso.getPath(); Pair<String, ManagedObjectReference> isoDatastoreInfo = getIsoDatastoreInfo(hyperHost, isoPath); assert (isoDatastoreInfo != null); assert (isoDatastoreInfo.second() != null); deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, isoDatastoreInfo.first(), isoDatastoreInfo.second(), true, true, ideUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at new device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } } } else { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); Pair<VirtualDevice, Boolean> isoInfo = VmwareHelper.prepareIsoDevice(vmMo, null, null, true, true, ideUnitNumber++, i + 1); deviceConfigSpecArray[i].setDevice(isoInfo.first()); if (isoInfo.second()) { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); } else { if(s_logger.isDebugEnabled()) s_logger.debug("Prepare ISO volume at existing device " + _gson.toJson(isoInfo.first())); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.EDIT); } } } i++; for (DiskTO vol : sortVolumesByDeviceId(disks)) { deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); if (vol.getType() == Volume.Type.ISO) { controllerKey = ideControllerKey; } else { if(vol.getType() == Volume.Type.ROOT) { if(vmSpec.getDetails() != null && vmSpec.getDetails().get(VmDetailConstants.ROOK_DISK_CONTROLLER) != null) { if(vmSpec.getDetails().get(VmDetailConstants.ROOK_DISK_CONTROLLER).equalsIgnoreCase("scsi")) controllerKey = scsiControllerKey; else controllerKey = ideControllerKey; } else { controllerKey = scsiControllerKey; } } else { // DATA volume always use SCSI device controllerKey = scsiControllerKey; } } if (vol.getType() != Volume.Type.ISO) { VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); Pair<ManagedObjectReference, DatastoreMO> volumeDsDetails = dataStoresDetails.get(primaryStore.getUuid()); assert (volumeDsDetails != null); VirtualDevice device; datastoreDiskPath = String.format("[%s] %s.vmdk", volumeDsDetails.second().getName(), volumeTO.getPath()); String chainInfo = volumeTO.getChainInfo(); if (chainInfo != null && !chainInfo.isEmpty()) { String[] diskChain = _gson.fromJson(chainInfo, String[].class); if (diskChain == null || diskChain.length < 1) { s_logger.warn("Empty previously-saved chain info, fall back to the original"); device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), (controllerKey==ideControllerKey)?ideUnitNumber++:scsiUnitNumber++, i + 1); } else { s_logger.info("Attach the disk with stored chain info: " + chainInfo); for (int j = 0; j < diskChain.length; j++) { diskChain[j] = String.format("[%s] %s", volumeDsDetails.second().getName(), diskChain[j]); } device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, diskChain, volumeDsDetails.first(), (controllerKey==ideControllerKey)?ideUnitNumber++:scsiUnitNumber++, i + 1); } } else { device = VmwareHelper.prepareDiskDevice(vmMo, controllerKey, new String[] { datastoreDiskPath }, volumeDsDetails.first(), (controllerKey==ideControllerKey)?ideUnitNumber++:scsiUnitNumber++, i + 1); } deviceConfigSpecArray[i].setDevice(device); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); if(s_logger.isDebugEnabled()) s_logger.debug("Prepare volume at new device " + _gson.toJson(device)); i++; } } VirtualDevice nic; int nicMask = 0; int nicCount = 0; for (NicTO nicTo : sortNicsByDeviceId(nics)) { s_logger.info("Prepare NIC device based on NicTO: " + _gson.toJson(nicTo)); boolean configureVServiceInNexus = (nicTo.getType() == TrafficType.Guest) && (vmSpec.getDetails().containsKey("ConfigureVServiceInNexus")); VirtualMachine.Type vmType = cmd.getVirtualMachine().getType(); Pair<ManagedObjectReference, String> networkInfo = prepareNetworkFromNicInfo(vmMo.getRunningHost(), nicTo, configureVServiceInNexus, vmType); if (VmwareHelper.isDvPortGroup(networkInfo.first())) { String dvSwitchUuid; ManagedObjectReference dcMor = hyperHost.getHyperHostDatacenter(); DatacenterMO dataCenterMo = new DatacenterMO(context, dcMor); ManagedObjectReference dvsMor = dataCenterMo.getDvSwitchMor(networkInfo.first()); dvSwitchUuid = dataCenterMo.getDvSwitchUuid(dvsMor); s_logger.info("Preparing NIC device on dvSwitch : " + dvSwitchUuid); nic = VmwareHelper.prepareDvNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), dvSwitchUuid, nicTo.getMac(), nicUnitNumber++, i + 1, true, true); } else { s_logger.info("Preparing NIC device on network " + networkInfo.second()); nic = VmwareHelper.prepareNicDevice(vmMo, networkInfo.first(), nicDeviceType, networkInfo.second(), nicTo.getMac(), nicUnitNumber++, i + 1, true, true); } deviceConfigSpecArray[i] = new VirtualDeviceConfigSpec(); deviceConfigSpecArray[i].setDevice(nic); deviceConfigSpecArray[i].setOperation(VirtualDeviceConfigSpecOperation.ADD); if(s_logger.isDebugEnabled()) s_logger.debug("Prepare NIC at new device " + _gson.toJson(deviceConfigSpecArray[i])); // this is really a hacking for DomR, upon DomR startup, we will reset all the NIC allocation after eth3 if(nicCount < 3) nicMask |= (1 << nicCount); i++; nicCount++; } vmConfigSpec.getDeviceChange().addAll(Arrays.asList(deviceConfigSpecArray)); // pass boot arguments through machine.id & perform customized options to VMX ArrayList<OptionValue> extraOptions = new ArrayList<OptionValue>(); OptionValue newVal = new OptionValue(); newVal.setKey("machine.id"); newVal.setValue(vmSpec.getBootArgs()); extraOptions.add(newVal); newVal = new OptionValue(); newVal.setKey("devices.hotplug"); newVal.setValue("true"); extraOptions.add(newVal); /** * Extra Config : nvp.vm-uuid = uuid * - Required for Nicira NVP integration */ newVal = new OptionValue(); newVal.setKey("nvp.vm-uuid"); newVal.setValue(vmSpec.getUuid()); extraOptions.add(newVal); /** * Extra Config : nvp.iface-id.<num> = uuid * - Required for Nicira NVP integration */ int nicNum = 0; for (NicTO nicTo : sortNicsByDeviceId(nics)) { if (nicTo.getUuid() != null) { newVal = new OptionValue(); newVal.setKey("nvp.iface-id." + nicNum); newVal.setValue(nicTo.getUuid()); extraOptions.add(newVal); } nicNum++; } for(Map.Entry<String, String> entry : validateVmDetails(vmSpec.getDetails()).entrySet()) { newVal = new OptionValue(); newVal.setKey(entry.getKey()); newVal.setValue(entry.getValue()); extraOptions.add(newVal); } String keyboardLayout = null; if(vmSpec.getDetails() != null) keyboardLayout = vmSpec.getDetails().get(VmDetailConstants.KEYBOARD); vmConfigSpec.getExtraConfig().addAll(Arrays.asList(configureVnc(extraOptions.toArray(new OptionValue[0]), hyperHost, vmName, vmSpec.getVncPassword(), keyboardLayout))); if (!vmMo.configureVm(vmConfigSpec)) { throw new Exception("Failed to configure VM before start. vmName: " + vmName); } vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, String.valueOf(nicMask)); /** * We need to configure the port on the DV switch after the host is * connected. So make this happen between the configure and start of * the VM */ int nicIndex = 0; for (NicTO nicTo : sortNicsByDeviceId(nics)) { if (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch) { // We need to create a port with a unique vlan and pass the key to the nic device s_logger.trace("Nic " + nicTo.toString() + " is connected to an NVP logicalswitch"); VirtualDevice nicVirtualDevice = vmMo.getNicDeviceByIndex(nicIndex); if (nicVirtualDevice == null) { throw new Exception("Failed to find a VirtualDevice for nic " + nicIndex); //FIXME Generic exceptions are bad } VirtualDeviceBackingInfo backing = nicVirtualDevice.getBacking(); if (backing instanceof VirtualEthernetCardDistributedVirtualPortBackingInfo) { // This NIC is connected to a Distributed Virtual Switch VirtualEthernetCardDistributedVirtualPortBackingInfo portInfo = (VirtualEthernetCardDistributedVirtualPortBackingInfo) backing; DistributedVirtualSwitchPortConnection port = portInfo.getPort(); String portKey = port.getPortKey(); String portGroupKey = port.getPortgroupKey(); String dvSwitchUuid = port.getSwitchUuid(); s_logger.debug("NIC " + nicTo.toString() + " is connected to dvSwitch " + dvSwitchUuid + " pg " + portGroupKey + " port " + portKey); ManagedObjectReference dvSwitchManager = vmMo.getContext().getVimClient().getServiceContent().getDvSwitchManager(); ManagedObjectReference dvSwitch = vmMo.getContext().getVimClient().getService().queryDvsByUuid(dvSwitchManager, dvSwitchUuid); // Get all ports DistributedVirtualSwitchPortCriteria criteria = new DistributedVirtualSwitchPortCriteria(); criteria.setInside(true); criteria.getPortgroupKey().add(portGroupKey); List<DistributedVirtualPort> dvPorts = vmMo.getContext().getVimClient().getService().fetchDVPorts(dvSwitch, criteria); DistributedVirtualPort vmDvPort = null; List<Integer> usedVlans = new ArrayList<Integer>(); for (DistributedVirtualPort dvPort : dvPorts) { // Find the port for this NIC by portkey if (portKey.equals(dvPort.getKey())) { vmDvPort = dvPort; } VMwareDVSPortSetting settings = (VMwareDVSPortSetting) dvPort .getConfig().getSetting(); VmwareDistributedVirtualSwitchVlanIdSpec vlanId = (VmwareDistributedVirtualSwitchVlanIdSpec) settings .getVlan(); s_logger.trace("Found port " + dvPort.getKey() + " with vlan " + vlanId.getVlanId()); if (vlanId.getVlanId() > 0 && vlanId.getVlanId() < 4095) { usedVlans.add(vlanId.getVlanId()); } } if (vmDvPort == null) { throw new Exception("Empty port list from dvSwitch for nic " + nicTo.toString()); } DVPortConfigInfo dvPortConfigInfo = vmDvPort .getConfig(); VMwareDVSPortSetting settings = (VMwareDVSPortSetting) dvPortConfigInfo.getSetting(); VmwareDistributedVirtualSwitchVlanIdSpec vlanId = (VmwareDistributedVirtualSwitchVlanIdSpec) settings.getVlan(); BoolPolicy blocked = settings.getBlocked(); if (blocked.isValue() == Boolean.TRUE) { s_logger.trace("Port is blocked, set a vlanid and unblock"); DVPortConfigSpec dvPortConfigSpec = new DVPortConfigSpec(); VMwareDVSPortSetting edittedSettings = new VMwareDVSPortSetting(); // Unblock blocked.setValue(Boolean.FALSE); blocked.setInherited(Boolean.FALSE); edittedSettings.setBlocked(blocked); // Set vlan for (i = 1; i < 4095; i++) { if (!usedVlans.contains(i)) break; } vlanId.setVlanId(i); // FIXME should be a determined // based on usage vlanId.setInherited(false); edittedSettings.setVlan(vlanId); dvPortConfigSpec.setSetting(edittedSettings); dvPortConfigSpec.setOperation("edit"); dvPortConfigSpec.setKey(portKey); List<DVPortConfigSpec> dvPortConfigSpecs = new ArrayList<DVPortConfigSpec>(); dvPortConfigSpecs.add(dvPortConfigSpec); ManagedObjectReference task = vmMo.getContext().getVimClient().getService().reconfigureDVPortTask(dvSwitch, dvPortConfigSpecs); if (!vmMo.getContext().getVimClient().waitForTask(task)) { throw new Exception( "Failed to configure the dvSwitch port for nic " + nicTo.toString()); } s_logger.debug("NIC " + nicTo.toString() + " connected to vlan " + i); } else { s_logger.trace("Port already configured and set to vlan " + vlanId.getVlanId()); } } else if (backing instanceof VirtualEthernetCardNetworkBackingInfo) { // This NIC is connected to a Virtual Switch // Nothing to do } else { s_logger.error("nic device backing is of type " + backing.getClass().getName()); throw new Exception("Incompatible backing for a VirtualDevice for nic " + nicIndex); //FIXME Generic exceptions are bad } } nicIndex++; } if (!vmMo.powerOn()) { throw new Exception("Failed to start VM. vmName: " + vmName); } state = State.Running; return new StartAnswer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "StartCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new StartAnswer(cmd, msg); } finally { synchronized (_vms) { if (state != State.Stopped) { _vms.put(vmName, state); } else { _vms.remove(vmName); } } } } private Map<String, String> validateVmDetails(Map<String, String> vmDetails) { Map<String, String> validatedDetails = new HashMap<String, String>(); if(vmDetails != null && vmDetails.size() > 0) { for(Map.Entry<String, String> entry : vmDetails.entrySet()) { if("machine.id".equalsIgnoreCase(entry.getKey())) continue; else if("devices.hotplug".equalsIgnoreCase(entry.getKey())) continue; else if("RemoteDisplay.vnc.enabled".equalsIgnoreCase(entry.getKey())) continue; else if("RemoteDisplay.vnc.password".equalsIgnoreCase(entry.getKey())) continue; else if("RemoteDisplay.vnc.port".equalsIgnoreCase(entry.getKey())) continue; else if("RemoteDisplay.vnc.keymap".equalsIgnoreCase(entry.getKey())) continue; else validatedDetails.put(entry.getKey(), entry.getValue()); } } return validatedDetails; } private NicTO[] sortNicsByDeviceId(NicTO[] nics) { List<NicTO> listForSort = new ArrayList<NicTO>(); for (NicTO nic : nics) { listForSort.add(nic); } Collections.sort(listForSort, new Comparator<NicTO>() { @Override public int compare(NicTO arg0, NicTO arg1) { if (arg0.getDeviceId() < arg1.getDeviceId()) { return -1; } else if (arg0.getDeviceId() == arg1.getDeviceId()) { return 0; } return 1; } }); return listForSort.toArray(new NicTO[0]); } private DiskTO[] sortVolumesByDeviceId(DiskTO[] volumes) { List<DiskTO> listForSort = new ArrayList<DiskTO>(); for (DiskTO vol : volumes) { listForSort.add(vol); } Collections.sort(listForSort, new Comparator<DiskTO>() { @Override public int compare(DiskTO arg0, DiskTO arg1) { if (arg0.getDiskSeq() < arg1.getDiskSeq()) { return -1; } else if (arg0.getDiskSeq() == arg1.getDiskSeq()) { return 0; } return 1; } }); return listForSort.toArray(new DiskTO[0]); } private HashMap<String, Pair<ManagedObjectReference, DatastoreMO>> inferDatastoreDetailsFromDiskInfo(VmwareHypervisorHost hyperHost, VmwareContext context, DiskTO[] disks) throws Exception { HashMap<String ,Pair<ManagedObjectReference, DatastoreMO>> poolMors = new HashMap<String, Pair<ManagedObjectReference, DatastoreMO>>(); assert (hyperHost != null) && (context != null); for (DiskTO vol : disks) { if (vol.getType() != Volume.Type.ISO) { VolumeObjectTO volumeTO = (VolumeObjectTO)vol.getData(); PrimaryDataStoreTO primaryStore = (PrimaryDataStoreTO)volumeTO.getDataStore(); String poolUuid = primaryStore.getUuid(); if(poolMors.get(poolUuid) == null) { ManagedObjectReference morDataStore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, poolUuid); if (morDataStore == null) { String msg = "Failed to get the mounted datastore for the volume's pool " + poolUuid; s_logger.error(msg); throw new Exception(msg); } poolMors.put(poolUuid, new Pair<ManagedObjectReference, DatastoreMO> (morDataStore, new DatastoreMO(context, morDataStore))); } } } return poolMors; } private String getPvlanInfo(NicTO nicTo) { if (nicTo.getBroadcastType() == BroadcastDomainType.Pvlan) { return NetUtils.getIsolatedPvlanFromUri(nicTo.getBroadcastUri()); } return null; } private String getVlanInfo(NicTO nicTo, String defaultVlan) { if (nicTo.getBroadcastType() == BroadcastDomainType.Native) { return defaultVlan; } else if (nicTo.getBroadcastType() == BroadcastDomainType.Vlan || nicTo.getBroadcastType() == BroadcastDomainType.Pvlan) { if (nicTo.getBroadcastUri() != null) { if (nicTo.getBroadcastType() == BroadcastDomainType.Vlan) // For vlan, the broadcast uri is of the form vlan://<vlanid> return nicTo.getBroadcastUri().getHost(); else // for pvlan, the broacast uri will be of the form pvlan://<vlanid>-i<pvlanid> return NetUtils.getPrimaryPvlanFromUri(nicTo.getBroadcastUri()); } else { s_logger.warn("BroadcastType is not claimed as VLAN or PVLAN, but without vlan info in broadcast URI. Use vlan info from labeling: " + defaultVlan); return defaultVlan; } } else if (nicTo.getBroadcastType() == BroadcastDomainType.Lswitch) { // We don't need to set any VLAN id for an NVP logical switch return null; } s_logger.warn("Unrecognized broadcast type in VmwareResource, type: " + nicTo.getBroadcastType().toString() + ". Use vlan info from labeling: " + defaultVlan); return defaultVlan; } private Pair<ManagedObjectReference, String> prepareNetworkFromNicInfo(HostMO hostMo, NicTO nicTo, boolean configureVServiceInNexus, VirtualMachine.Type vmType) throws Exception { Pair<String, String> switchName; TrafficType trafficType; VirtualSwitchType switchType; switchName = getTargetSwitch(nicTo); trafficType = nicTo.getType(); // Get switch type from resource property which is dictated by cluster property // If a virtual switch type is specified while adding cluster that will be used. // Else If virtual switch type is specified in physical traffic label that will be used // Else use standard vSwitch switchType = VirtualSwitchType.StandardVirtualSwitch; if (trafficType == TrafficType.Guest && _guestTrafficInfo != null) { switchType = _guestTrafficInfo.getVirtualSwitchType(); } else if (trafficType == TrafficType.Public && _publicTrafficInfo != null) { switchType = _publicTrafficInfo.getVirtualSwitchType(); } String namePrefix = getNetworkNamePrefix(nicTo); Pair<ManagedObjectReference, String> networkInfo = null; s_logger.info("Prepare network on " + switchType + " " + switchName + " with name prefix: " + namePrefix); if (VirtualSwitchType.StandardVirtualSwitch == switchType) { networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, getVlanInfo(nicTo, switchName.second()), nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _ops_timeout, !namePrefix.startsWith("cloud.private"), nicTo.getBroadcastType(), nicTo.getUuid()); } else { String vlanId = getVlanInfo(nicTo, switchName.second()); String svlanId = null; boolean pvlannetwork = (getPvlanInfo(nicTo) == null)?false:true; if (vmType != null && vmType.equals(VirtualMachine.Type.DomainRouter) && pvlannetwork) { // plumb this network to the promiscuous vlan. svlanId = vlanId; } else { // plumb this network to the isolated vlan. svlanId = getPvlanInfo(nicTo); } networkInfo = HypervisorHostHelper.prepareNetwork(switchName.first(), namePrefix, hostMo, vlanId, svlanId, nicTo.getNetworkRateMbps(), nicTo.getNetworkRateMulticastMbps(), _ops_timeout, switchType, _portsPerDvPortGroup, nicTo.getGateway(), configureVServiceInNexus, nicTo.getBroadcastType()); } return networkInfo; } // return Pair<switch name, vlan tagging> private Pair<String, String> getTargetSwitch(NicTO nicTo) throws Exception { if(nicTo.getName() != null && !nicTo.getName().isEmpty()) { String[] tokens = nicTo.getName().split(","); // Format of network traffic label is <VSWITCH>,<VLANID>,<VSWITCHTYPE> // If all 3 fields are mentioned then number of tokens would be 3. // If only <VSWITCH>,<VLANID> are mentioned then number of tokens would be 2. if(tokens.length == 2 || tokens.length == 3) { String vlanToken = tokens[1]; if (vlanToken.isEmpty()) { vlanToken = Vlan.UNTAGGED; } return new Pair<String, String>(tokens[0], vlanToken); } else { return new Pair<String, String>(nicTo.getName(), Vlan.UNTAGGED); } } if (nicTo.getType() == Networks.TrafficType.Guest) { return new Pair<String, String>(_guestTrafficInfo.getVirtualSwitchName(), Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management) { return new Pair<String, String>(_privateNetworkVSwitchName, Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Public) { return new Pair<String, String>(_publicTrafficInfo.getVirtualSwitchName(), Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Storage) { return new Pair<String, String>(_privateNetworkVSwitchName, Vlan.UNTAGGED); } else if (nicTo.getType() == Networks.TrafficType.Vpn) { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } else { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } } private String getNetworkNamePrefix(NicTO nicTo) throws Exception { if (nicTo.getType() == Networks.TrafficType.Guest) { return "cloud.guest"; } else if (nicTo.getType() == Networks.TrafficType.Control || nicTo.getType() == Networks.TrafficType.Management) { return "cloud.private"; } else if (nicTo.getType() == Networks.TrafficType.Public) { return "cloud.public"; } else if (nicTo.getType() == Networks.TrafficType.Storage) { return "cloud.storage"; } else if (nicTo.getType() == Networks.TrafficType.Vpn) { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } else { throw new Exception("Unsupported traffic type: " + nicTo.getType().toString()); } } protected synchronized Answer execute(final RemoteAccessVpnCfgCommand cmd) { String controlIp = getRouterSshControlIp(cmd); StringBuffer argsBuf = new StringBuffer(); if (cmd.isCreate()) { argsBuf.append(" -r ").append(cmd.getIpRange()).append(" -p ").append(cmd.getPresharedKey()).append(" -s ").append(cmd.getVpnServerIp()).append(" -l ").append(cmd.getLocalIp()) .append(" -c "); } else { argsBuf.append(" -d ").append(" -s ").append(cmd.getVpnServerIp()); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if (s_logger.isDebugEnabled()) { s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); if (!result.first()) { s_logger.error("RemoteAccessVpnCfg command on domR failed, message: " + result.second()); return new Answer(cmd, false, "RemoteAccessVpnCfg command failed due to " + result.second()); } if (s_logger.isInfoEnabled()) { s_logger.info("RemoteAccessVpnCfg command on domain router " + argsBuf.toString() + " completed"); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "RemoteAccessVpnCfg command failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } return new Answer(cmd); } protected synchronized Answer execute(final VpnUsersCfgCommand cmd) { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String controlIp = getRouterSshControlIp(cmd); for (VpnUsersCfgCommand.UsernamePassword userpwd : cmd.getUserpwds()) { StringBuffer argsBuf = new StringBuffer(); if (!userpwd.isAdd()) { argsBuf.append(" -U ").append(userpwd.getUsername()); } else { argsBuf.append(" -u ").append(userpwd.getUsernamePassword()); } try { if (s_logger.isDebugEnabled()) { s_logger.debug("Executing /opt/cloud/bin/vpn_lt2p.sh "); } Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpn_l2tp.sh " + argsBuf.toString()); if (!result.first()) { s_logger.error("VpnUserCfg command on domR failed, message: " + result.second()); return new Answer(cmd, false, "VpnUserCfg command failed due to " + result.second()); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "VpnUserCfg command failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } } return new Answer(cmd); } private VirtualMachineMO takeVmFromOtherHyperHost(VmwareHypervisorHost hyperHost, String vmName) throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo != null) { ManagedObjectReference morTargetPhysicalHost = hyperHost.findMigrationTarget(vmMo); if (morTargetPhysicalHost == null) { String msg = "VM " + vmName + " is on other host and we have no resource available to migrate and start it here"; s_logger.error(msg); throw new Exception(msg); } if (!vmMo.relocate(morTargetPhysicalHost)) { String msg = "VM " + vmName + " is on other host and we failed to relocate it here"; s_logger.error(msg); throw new Exception(msg); } return vmMo; } return null; } // isoUrl sample content : // nfs://192.168.10.231/export/home/kelven/vmware-test/secondary/template/tmpl/2/200//200-2-80f7ee58-6eff-3a2d-bcb0-59663edf6d26.iso private Pair<String, ManagedObjectReference> getIsoDatastoreInfo(VmwareHypervisorHost hyperHost, String isoUrl) throws Exception { assert (isoUrl != null); int isoFileNameStartPos = isoUrl.lastIndexOf("/"); if (isoFileNameStartPos < 0) { throw new Exception("Invalid ISO path info"); } String isoFileName = isoUrl.substring(isoFileNameStartPos); int templateRootPos = isoUrl.indexOf("template/tmpl"); if (templateRootPos < 0) { throw new Exception("Invalid ISO path info"); } String storeUrl = isoUrl.substring(0, templateRootPos - 1); String isoPath = isoUrl.substring(templateRootPos, isoFileNameStartPos); ManagedObjectReference morDs = prepareSecondaryDatastoreOnHost(storeUrl); DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); return new Pair<String, ManagedObjectReference>(String.format("[%s] %s%s", dsMo.getName(), isoPath, isoFileName), morDs); } protected Answer execute(ReadyCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ReadyCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); if(hyperHost.isHyperHostConnected()) { return new ReadyAnswer(cmd); } else { return new ReadyAnswer(cmd, "Host is not in connect state"); } } catch(Exception e) { s_logger.error("Unexpected exception: ", e); return new ReadyAnswer(cmd, VmwareHelper.getExceptionMessage(e)); } } protected Answer execute(GetHostStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetHostStatsCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); HostStatsEntry hostStats = new HostStatsEntry(cmd.getHostId(), 0, 0, 0, "host", 0, 0, 0, 0); Answer answer = new GetHostStatsAnswer(cmd, hostStats); try { HostStatsEntry entry = getHyperHostStats(hyperHost); if(entry != null) { entry.setHostId(cmd.getHostId()); answer = new GetHostStatsAnswer(cmd, entry); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unable to execute GetHostStatsCommand due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); } if (s_logger.isTraceEnabled()) { s_logger.trace("GetHostStats Answer: " + _gson.toJson(answer)); } return answer; } protected Answer execute(GetVmStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetVmStatsCommand: " + _gson.toJson(cmd)); } HashMap<String, VmStatsEntry> vmStatsMap = null; try { HashMap<String, State> newStates = getVmStates(); List<String> requestedVmNames = cmd.getVmNames(); List<String> vmNames = new ArrayList<String>(); if (requestedVmNames != null) { for (String vmName : requestedVmNames) { if (newStates.get(vmName) != null) { vmNames.add(vmName); } } } if (vmNames != null) { vmStatsMap = getVmStats(vmNames); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to execute GetVmStatsCommand due to : " + VmwareHelper.getExceptionMessage(e), e); } Answer answer = new GetVmStatsAnswer(cmd, vmStatsMap); if (s_logger.isTraceEnabled()) { s_logger.trace("Report GetVmStatsAnswer: " + _gson.toJson(answer)); } return answer; } protected Answer execute(CheckHealthCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckHealthCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); if (hyperHost.isHyperHostConnected()) { return new CheckHealthAnswer(cmd, true); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to execute CheckHealthCommand due to " + VmwareHelper.getExceptionMessage(e), e); } return new CheckHealthAnswer(cmd, false); } protected Answer execute(StopCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource StopCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { State state = null; synchronized (_vms) { state = _vms.get(cmd.getVmName()); _vms.put(cmd.getVmName(), State.Stopping); } try { vmMo.setCustomFieldValue(CustomFieldConstants.CLOUD_NIC_MASK, "0"); if (getVmState(vmMo) != State.Stopped) { if (vmMo.safePowerOff(_shutdown_waitMs)) { state = State.Stopped; return new StopAnswer(cmd, "Stop VM " + cmd.getVmName() + " Succeed", 0, true); } else { String msg = "Have problem in powering off VM " + cmd.getVmName() + ", let the process continue"; s_logger.warn(msg); return new StopAnswer(cmd, msg, 0, true); } } else { state = State.Stopped; } String msg = "VM " + cmd.getVmName() + " is already in stopped state"; s_logger.info(msg); return new StopAnswer(cmd, msg, 0, true); } finally { synchronized (_vms) { _vms.put(cmd.getVmName(), state); } } } else { synchronized (_vms) { _vms.remove(cmd.getVmName()); } String msg = "VM " + cmd.getVmName() + " is no longer in vSphere"; s_logger.info(msg); return new StopAnswer(cmd, msg, 0, true); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "StopCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new StopAnswer(cmd, msg, false); } } protected Answer execute(RebootRouterCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource RebootRouterCommand: " + _gson.toJson(cmd)); } RebootAnswer answer = (RebootAnswer) execute((RebootCommand) cmd); if (answer.getResult()) { String connectResult = connect(cmd.getVmName(), cmd.getPrivateIpAddress()); networkUsage(cmd.getPrivateIpAddress(), "create", null); if (connectResult == null) { return answer; } else { return new Answer(cmd, false, connectResult); } } return answer; } protected Answer execute(RebootCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource RebootCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { try { vmMo.rebootGuest(); return new RebootAnswer(cmd, "reboot succeeded", true); } catch(ToolsUnavailableFaultMsg e) { s_logger.warn("VMware tools is not installed at guest OS, we will perform hard reset for reboot"); } catch(Exception e) { s_logger.warn("We are not able to perform gracefull guest reboot due to " + VmwareHelper.getExceptionMessage(e)); } // continue to try with hard-reset if (vmMo.reset()) { return new RebootAnswer(cmd, "reboot succeeded", true); } String msg = "Reboot failed in vSphere. vm: " + cmd.getVmName(); s_logger.warn(msg); return new RebootAnswer(cmd, msg, false); } else { String msg = "Unable to find the VM in vSphere to reboot. vm: " + cmd.getVmName(); s_logger.warn(msg); return new RebootAnswer(cmd, msg, false); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "RebootCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new RebootAnswer(cmd, msg, false); } } protected Answer execute(CheckVirtualMachineCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckVirtualMachineCommand: " + _gson.toJson(cmd)); } final String vmName = cmd.getVmName(); State state = State.Unknown; Integer vncPort = null; VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); if (vmMo != null) { state = getVmState(vmMo); if (state == State.Running) { synchronized (_vms) { _vms.put(vmName, State.Running); } } return new CheckVirtualMachineAnswer(cmd, state, vncPort); } else { s_logger.warn("Can not find vm " + vmName + " to execute CheckVirtualMachineCommand"); return new CheckVirtualMachineAnswer(cmd, state, vncPort); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unexpected exception: " + VmwareHelper.getExceptionMessage(e), e); return new CheckVirtualMachineAnswer(cmd, state, vncPort); } } protected Answer execute(PrepareForMigrationCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PrepareForMigrationCommand: " + _gson.toJson(cmd)); } VirtualMachineTO vm = cmd.getVirtualMachine(); if (s_logger.isDebugEnabled()) { s_logger.debug("Preparing host for migrating " + vm); } final String vmName = vm.getName(); try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // find VM through datacenter (VM is not at the target host yet) VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter"; s_logger.error(msg); throw new Exception(msg); } NicTO[] nics = vm.getNics(); for (NicTO nic : nics) { // prepare network on the host prepareNetworkFromNicInfo(new HostMO(getServiceContext(), _morHyperHost), nic, false, cmd.getVirtualMachine().getType()); } String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); if(secStoreUrl == null) { String msg = "secondary storage for dc " + _dcId + " is not ready yet?"; throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; throw new Exception(msg); } synchronized (_vms) { _vms.put(vm.getName(), State.Migrating); } return new PrepareForMigrationAnswer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unexcpeted exception " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new PrepareForMigrationAnswer(cmd, msg); } } protected Answer execute(MigrateCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MigrateCommand: " + _gson.toJson(cmd)); } final String vmName = cmd.getVmName(); State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); // find VM through datacenter (VM is not at the target host yet) VirtualMachineMO vmMo = hyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter"; s_logger.error(msg); throw new Exception(msg); } VmwareHypervisorHost destHyperHost = getTargetHyperHost(new DatacenterMO(hyperHost.getContext(), morDc), cmd.getDestinationIp()); ManagedObjectReference morTargetPhysicalHost = destHyperHost.findMigrationTarget(vmMo); if (morTargetPhysicalHost == null) { throw new Exception("Unable to find a target capable physical host"); } if (!vmMo.migrate(destHyperHost.getHyperHostOwnerResourcePool(), morTargetPhysicalHost)) { throw new Exception("Migration failed"); } state = State.Stopping; return new MigrateAnswer(cmd, true, "migration succeeded", null); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new MigrateAnswer(cmd, false, msg, null); } finally { synchronized (_vms) { _vms.put(vmName, state); } } } protected Answer execute(MigrateWithStorageCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MigrateWithStorageCommand: " + _gson.toJson(cmd)); } VirtualMachineTO vmTo = cmd.getVirtualMachine(); final String vmName = vmTo.getName(); State state = null; synchronized (_vms) { state = _vms.get(vmName); _vms.put(vmName, State.Stopping); } VmwareHypervisorHost srcHyperHost = null; VmwareHypervisorHost tgtHyperHost = null; VirtualMachineMO vmMo = null; ManagedObjectReference morDsAtTarget = null; ManagedObjectReference morDsAtSource = null; ManagedObjectReference morDc = null; ManagedObjectReference morDcOfTargetHost = null; ManagedObjectReference morTgtHost = new ManagedObjectReference(); VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec(); List<VirtualMachineRelocateSpecDiskLocator> diskLocators = new ArrayList<VirtualMachineRelocateSpecDiskLocator>(); VirtualMachineRelocateSpecDiskLocator diskLocator = null; boolean isFirstDs = true; String srcDiskName = ""; String srcDsName = ""; String tgtDsName = ""; String tgtDsNfsHost; String tgtDsNfsPath; int tgtDsNfsPort; VolumeTO volume; StorageFilerTO filerTo; Set<String> mountedDatastoresAtSource = new HashSet<String>(); Map<VolumeTO, StorageFilerTO> volToFiler = cmd.getVolumeToFiler(); String tgtHost = cmd.getTargetHost(); String tgtHostMorInfo = tgtHost.split("@")[0]; morTgtHost.setType(tgtHostMorInfo.split(":")[0]); morTgtHost.setValue(tgtHostMorInfo.split(":")[1]); try { srcHyperHost = getHyperHost(getServiceContext()); tgtHyperHost = new HostMO(getServiceContext(), morTgtHost); morDc = srcHyperHost.getHyperHostDatacenter(); morDcOfTargetHost = tgtHyperHost.getHyperHostDatacenter(); if (!morDc.getValue().equalsIgnoreCase(morDcOfTargetHost.getValue())) { String msg = "Source host & target host are in different datacentesr"; throw new CloudRuntimeException(msg); } VmwareManager mgr = tgtHyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // find VM through datacenter (VM is not at the target host yet) vmMo = srcHyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter " + morDc.getValue(); s_logger.error(msg); throw new Exception(msg); } // Get details of each target datastore & attach to source host. for (Entry<VolumeTO, StorageFilerTO> entry : volToFiler.entrySet()) { volume = entry.getKey(); filerTo = entry.getValue(); srcDsName = volume.getPoolUuid().replace("-", ""); tgtDsName = filerTo.getUuid().replace("-", ""); tgtDsNfsHost = filerTo.getHost(); tgtDsNfsPath = filerTo.getPath(); tgtDsNfsPort = filerTo.getPort(); s_logger.debug("Preparing spec for volume : " + volume.getName()); morDsAtTarget = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(tgtHyperHost, filerTo.getUuid()); if (morDsAtTarget == null) { String msg = "Unable to find the mounted datastore with uuid " + morDsAtTarget + " to execute MigrateWithStorageCommand"; s_logger.error(msg); throw new Exception(msg); } morDsAtSource = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(srcHyperHost, filerTo.getUuid()); if (morDsAtSource == null) { morDsAtSource = srcHyperHost.mountDatastore(false, tgtDsNfsHost, tgtDsNfsPort, tgtDsNfsPath, tgtDsName); if (morDsAtSource == null) { throw new Exception("Unable to mount datastore " + tgtDsNfsHost + ":/" + tgtDsNfsPath + " on " + _hostName); } mountedDatastoresAtSource.add(tgtDsName); s_logger.debug("Mounted datastore " + tgtDsNfsHost + ":/" + tgtDsNfsPath + " on " + _hostName); } if (isFirstDs) { relocateSpec.setDatastore(morDsAtSource); isFirstDs = false; } srcDiskName = String.format("[%s] %s.vmdk", srcDsName, volume.getPath()); diskLocator = new VirtualMachineRelocateSpecDiskLocator(); diskLocator.setDatastore(morDsAtSource); diskLocator.setDiskId(getVirtualDiskInfo(vmMo, srcDiskName)); diskLocators.add(diskLocator); } relocateSpec.getDisk().addAll(diskLocators); // Prepare network at target before migration NicTO[] nics = vmTo.getNics(); for (NicTO nic : nics) { // prepare network on the host prepareNetworkFromNicInfo(new HostMO(getServiceContext(), morTgtHost), nic, false, vmTo.getType()); } // Ensure secondary storage mounted on target host String secStoreUrl = mgr.getSecondaryStorageStoreUrl(Long.parseLong(_dcId)); if(secStoreUrl == null) { String msg = "secondary storage for dc " + _dcId + " is not ready yet?"; throw new Exception(msg); } mgr.prepareSecondaryStorageStore(secStoreUrl); ManagedObjectReference morSecDs = prepareSecondaryDatastoreOnHost(secStoreUrl); if (morSecDs == null) { String msg = "Failed to prepare secondary storage on host, secondary store url: " + secStoreUrl; throw new Exception(msg); } // Change datastore if (!vmMo.changeDatastore(relocateSpec)) { throw new Exception("Change datastore operation failed during storage migration"); } else { s_logger.debug("Successfully migrated storage of VM " + vmName + " to target datastore(s)"); } // Change host ManagedObjectReference morPool = tgtHyperHost.getHyperHostOwnerResourcePool(); if (!vmMo.migrate(morPool, tgtHyperHost.getMor())) { throw new Exception("Change datastore operation failed during storage migration"); } else { s_logger.debug("Successfully relocated VM " + vmName + " from " + _hostName + " to " + tgtHyperHost.getHyperHostName()); } state = State.Stopping; List<VolumeObjectTO> volumeToList = null; return new MigrateWithStorageAnswer(cmd, volumeToList); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encountered remote exception at vCenter, invalidating VMware session context"); invalidateServiceContext(); } String msg = "MigrationCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new MigrateWithStorageAnswer(cmd, (Exception) e); } finally { // Cleanup datastores mounted on source host for(String mountedDatastore : mountedDatastoresAtSource) { s_logger.debug("Attempting to unmount datastore " + mountedDatastore + " at " + _hostName); try { srcHyperHost.unmountDatastore(mountedDatastore); } catch (Exception unmountEx) { s_logger.debug("Failed to unmount datastore " + mountedDatastore + " at " + _hostName + ". Seems the datastore is still being used by " + _hostName + ". Please unmount manually to cleanup."); } s_logger.debug("Successfully unmounted datastore " + mountedDatastore + " at " + _hostName); } synchronized (_vms) { _vms.put(vmName, state); } } } private Answer execute(MigrateVolumeCommand cmd) { String volumePath = cmd.getVolumePath(); StorageFilerTO poolTo = cmd.getPool(); if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MigrateVolumeCommand: " + _gson.toJson(cmd)); } final String vmName = volMgr.getVmNameFromVolumeId(cmd.getVolumeId()); VirtualMachineMO vmMo = null; VmwareHypervisorHost srcHyperHost = null; ManagedObjectReference morDs = null; ManagedObjectReference morDc = null; VirtualMachineRelocateSpec relocateSpec = new VirtualMachineRelocateSpec(); List<VirtualMachineRelocateSpecDiskLocator> diskLocators = new ArrayList<VirtualMachineRelocateSpecDiskLocator>(); VirtualMachineRelocateSpecDiskLocator diskLocator = null; String srcDiskName = ""; String srcDsName = ""; String tgtDsName = ""; try { srcHyperHost = getHyperHost(getServiceContext()); morDc = srcHyperHost.getHyperHostDatacenter(); srcDsName = volMgr.getStoragePoolOfVolume(cmd.getVolumeId()); tgtDsName = poolTo.getUuid().replace("-", ""); // find VM through datacenter (VM is not at the target host yet) vmMo = srcHyperHost.findVmOnPeerHyperHost(vmName); if (vmMo == null) { String msg = "VM " + vmName + " does not exist in VMware datacenter " + morDc.getValue(); s_logger.error(msg); throw new Exception(msg); } morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(srcHyperHost, tgtDsName); if (morDs == null) { String msg = "Unable to find the mounted datastore with name " + tgtDsName + " to execute MigrateVolumeCommand"; s_logger.error(msg); throw new Exception(msg); } srcDiskName = String.format("[%s] %s.vmdk", srcDsName, volumePath); diskLocator = new VirtualMachineRelocateSpecDiskLocator(); diskLocator.setDatastore(morDs); diskLocator.setDiskId(getVirtualDiskInfo(vmMo, srcDiskName)); diskLocators.add(diskLocator); relocateSpec.getDisk().add(diskLocator); // Change datastore if (!vmMo.changeDatastore(relocateSpec)) { throw new Exception("Change datastore operation failed during volume migration"); } else { s_logger.debug("Successfully migrated volume " + volumePath + " to target datastore " + tgtDsName); } return new MigrateVolumeAnswer(cmd, true, null, volumePath); } catch (Exception e) { String msg = "Catch Exception " + e.getClass().getName() + " due to " + e.toString(); s_logger.error(msg, e); return new MigrateVolumeAnswer(cmd, false, msg, null); } } private int getVirtualDiskInfo(VirtualMachineMO vmMo, String srcDiskName) throws Exception { Pair<VirtualDisk, String> deviceInfo = vmMo.getDiskDevice(srcDiskName, false); if(deviceInfo == null) { throw new Exception("No such disk device: " + srcDiskName); } return deviceInfo.first().getKey(); } private VmwareHypervisorHost getTargetHyperHost(DatacenterMO dcMo, String destIp) throws Exception { VmwareManager mgr = dcMo.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); List<ObjectContent> ocs = dcMo.getHostPropertiesOnDatacenterHostFolder(new String[] { "name", "parent" }); if (ocs != null && ocs.size() > 0) { for (ObjectContent oc : ocs) { HostMO hostMo = new HostMO(dcMo.getContext(), oc.getObj()); VmwareHypervisorHostNetworkSummary netSummary = hostMo.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost(hostMo)); if (destIp.equalsIgnoreCase(netSummary.getHostIp())) { return new HostMO(dcMo.getContext(), oc.getObj()); } } } throw new Exception("Unable to locate dest host by " + destIp); } protected Answer execute(CreateStoragePoolCommand cmd) { return new Answer(cmd, true, "success"); } protected Answer execute(ModifyStoragePoolCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ModifyStoragePoolCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); StorageFilerTO pool = cmd.getPool(); if (pool.getType() != StoragePoolType.NetworkFilesystem && pool.getType() != StoragePoolType.VMFS) { throw new Exception("Unsupported storage pool type " + pool.getType()); } ManagedObjectReference morDatastore = null; morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, pool.getUuid()); if(morDatastore == null) morDatastore = hyperHost.mountDatastore(pool.getType() == StoragePoolType.VMFS, pool.getHost(), pool.getPort(), pool.getPath(), pool.getUuid().replace("-", "")); assert (morDatastore != null); DatastoreSummary summary = new DatastoreMO(getServiceContext(), morDatastore).getSummary(); long capacity = summary.getCapacity(); long available = summary.getFreeSpace(); Map<String, TemplateProp> tInfo = new HashMap<String, TemplateProp>(); ModifyStoragePoolAnswer answer = new ModifyStoragePoolAnswer(cmd, capacity, available, tInfo); return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "ModifyStoragePoolCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } } protected Answer execute(DeleteStoragePoolCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DeleteStoragePoolCommand: " + _gson.toJson(cmd)); } StorageFilerTO pool = cmd.getPool(); try { // We will leave datastore cleanup management to vCenter. Since for cluster VMFS datastore, it will always // be mounted by vCenter. // VmwareHypervisorHost hyperHost = this.getHyperHost(getServiceContext()); // hyperHost.unmountDatastore(pool.getUuid()); Answer answer = new Answer(cmd, true, "success"); return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "DeleteStoragePoolCommand (pool: " + pool.getHost() + ", path: " + pool.getPath() + ") failed due to " + VmwareHelper.getExceptionMessage(e); return new Answer(cmd, false, msg); } } public static String getDatastoreName(String str) { return str.replace('/', '-'); } // This methd can be used to determine if the datastore is active yet. // When an iSCSI target is created on a host and that target already contains // the metadata that represents a datastore, the datastore shows up within // vCenter as existent, but not necessarily active. // Call this method and pass in the datastore's name to wait, if necessary, // for the datastore to become active. private boolean datastoreFileExists(DatastoreMO dsMo, String volumeDatastorePath) { for (int i = 0; i < 10; i++) { try { return dsMo.fileExists(volumeDatastorePath); } catch (Exception e) { if (!e.getMessage().contains("is not accessible")) { break; } } try { Thread.sleep(5000); } catch (Exception e) { } } return false; } public ManagedObjectReference handleDatastoreAndVmdkAttach(Command cmd, String iqn, String storageHost, int storagePort, String initiatorUsername, String initiatorPassword, String targetUsername, String targetPassword) throws Exception { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); ManagedObjectReference morDs = createVmfsDatastore(hyperHost, getDatastoreName(iqn), storageHost, storagePort, iqn, initiatorUsername, initiatorPassword, targetUsername, targetPassword); DatastoreMO dsMo = new DatastoreMO(context, morDs); String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), dsMo.getName()); if (!dsMo.fileExists(volumeDatastorePath)) { String dummyVmName = getWorkerName(context, cmd, 0); VirtualMachineMO vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); if (vmMo == null) { throw new Exception("Unable to create a dummy VM for volume creation"); } vmMo.createDisk(volumeDatastorePath, getMBsFromBytes(dsMo.getSummary().getFreeSpace()), morDs, vmMo.getScsiDeviceControllerKey()); vmMo.detachDisk(volumeDatastorePath, false); vmMo.destroy(); } return morDs; } public void handleDatastoreAndVmdkDetach(String iqn, String storageHost, int storagePort) throws Exception { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); deleteVmfsDatastore(hyperHost, getDatastoreName(iqn), storageHost, storagePort, iqn); } protected Answer execute(AttachVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource AttachVolumeCommand: " + _gson.toJson(cmd)); } /* * AttachVolumeCommand { "attach":true,"vmName":"i-2-1-KY","pooltype":"NetworkFilesystem", * "volumeFolder":"/export/home/kelven/vmware-test/primary", "volumePath":"uuid", * "volumeName":"volume name","deviceId":1 } */ try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo == null) { String msg = "Unable to find the VM to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } ManagedObjectReference morDs = null; if (cmd.getAttach() && cmd.isManaged()) { morDs = handleDatastoreAndVmdkAttach(cmd, cmd.get_iScsiName(), cmd.getStorageHost(), cmd.getStoragePort(), cmd.getChapInitiatorUsername(), cmd.getChapInitiatorPassword(), cmd.getChapTargetUsername(), cmd.getChapTargetPassword()); } else { morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, cmd.getPoolUuid()); } if (morDs == null) { String msg = "Unable to find the mounted datastore to execute AttachVolumeCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } DatastoreMO dsMo = new DatastoreMO(getServiceContext(), morDs); String datastoreVolumePath = dsMo.searchFileInSubFolders(cmd.getVolumePath() + ".vmdk", true); assert (datastoreVolumePath != null) : "Virtual disk file must exist in specified datastore for attach/detach operations."; AttachVolumeAnswer answer = new AttachVolumeAnswer(cmd, cmd.getDeviceId(), datastoreVolumePath); if (cmd.getAttach()) { vmMo.attachDisk(new String[] { datastoreVolumePath }, morDs); } else { vmMo.removeAllSnapshots(); vmMo.detachDisk(datastoreVolumePath, false); if (cmd.isManaged()) { handleDatastoreAndVmdkDetach(cmd.get_iScsiName(), cmd.getStorageHost(), cmd.getStoragePort()); } } return answer; } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "AttachVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new AttachVolumeAnswer(cmd, msg); } } private void addRemoveInternetScsiTargetsToAllHosts(final boolean add, final List<HostInternetScsiHbaStaticTarget> lstTargets, final List<Pair<ManagedObjectReference, String>> lstHosts) throws Exception { VmwareContext context = getServiceContext(); ExecutorService executorService = Executors.newFixedThreadPool(lstHosts.size()); final List<Exception> exceptions = new ArrayList<Exception>(); for (Pair<ManagedObjectReference, String> hostPair : lstHosts) { HostMO host = new HostMO(context, hostPair.first()); HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO(); boolean iScsiHbaConfigured = false; for (HostHostBusAdapter hba : hostStorageSystem.getStorageDeviceInfo().getHostBusAdapter()) { if (hba instanceof HostInternetScsiHba) { // just finding an instance of HostInternetScsiHba means that we have found at least one configured iSCSI HBA // at least one iSCSI HBA must be configured before a CloudStack user can use this host for iSCSI storage iScsiHbaConfigured = true; final String iScsiHbaDevice = hba.getDevice(); final HostStorageSystemMO hss = hostStorageSystem; executorService.submit(new Thread() { @Override public void run() { try { if (add) { hss.addInternetScsiStaticTargets(iScsiHbaDevice, lstTargets); } else { hss.removeInternetScsiStaticTargets(iScsiHbaDevice, lstTargets); } hss.rescanHba(iScsiHbaDevice); hss.rescanVmfs(); } catch (Exception ex) { synchronized (exceptions) { exceptions.add(ex); } } } }); } } if (!iScsiHbaConfigured) { throw new Exception("An iSCSI HBA must be configured before a host can use iSCSI storage."); } } executorService.shutdown(); if (!executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES)) { throw new Exception("The system timed out before completing the task 'rescanAllHosts'."); } if (exceptions.size() > 0) { throw new Exception(exceptions.get(0).getMessage()); } } private void rescanAllHosts(final List<Pair<ManagedObjectReference, String>> lstHosts) throws Exception { VmwareContext context = getServiceContext(); ExecutorService executorService = Executors.newFixedThreadPool(lstHosts.size()); final List<Exception> exceptions = new ArrayList<Exception>(); for (Pair<ManagedObjectReference, String> hostPair : lstHosts) { HostMO host = new HostMO(context, hostPair.first()); HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO(); boolean iScsiHbaConfigured = false; for (HostHostBusAdapter hba : hostStorageSystem.getStorageDeviceInfo().getHostBusAdapter()) { if (hba instanceof HostInternetScsiHba) { // just finding an instance of HostInternetScsiHba means that we have found at least one configured iSCSI HBA // at least one iSCSI HBA must be configured before a CloudStack user can use this host for iSCSI storage iScsiHbaConfigured = true; final String iScsiHbaDevice = hba.getDevice(); final HostStorageSystemMO hss = hostStorageSystem; executorService.submit(new Thread() { @Override public void run() { try { hss.rescanHba(iScsiHbaDevice); hss.rescanVmfs(); } catch (Exception ex) { synchronized (exceptions) { exceptions.add(ex); } } } }); } } if (!iScsiHbaConfigured) { throw new Exception("An iSCSI HBA must be configured before a host can use iSCSI storage."); } } executorService.shutdown(); if (!executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES)) { throw new Exception("The system timed out before completing the task 'rescanAllHosts'."); } if (exceptions.size() > 0) { throw new Exception(exceptions.get(0).getMessage()); } } private ManagedObjectReference createVmfsDatastore(VmwareHypervisorHost hyperHost, String datastoreName, String storageIpAddress, int storagePortNumber, String iqn, String chapName, String chapSecret, String mutualChapName, String mutualChapSecret) throws Exception { VmwareContext context = getServiceContext(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO cluster = new ClusterMO(context, morCluster); List<Pair<ManagedObjectReference, String>> lstHosts = cluster.getClusterHosts(); HostInternetScsiHbaStaticTarget target = new HostInternetScsiHbaStaticTarget(); target.setAddress(storageIpAddress); target.setPort(storagePortNumber); target.setIScsiName(iqn); HostInternetScsiHbaAuthenticationProperties auth = new HostInternetScsiHbaAuthenticationProperties(); String strAuthType = "chapRequired"; auth.setChapAuthEnabled(true); auth.setChapInherited(false); auth.setChapAuthenticationType(strAuthType); auth.setChapName(chapName); auth.setChapSecret(chapSecret); auth.setMutualChapInherited(false); auth.setMutualChapAuthenticationType(strAuthType); auth.setMutualChapName(mutualChapName); auth.setMutualChapSecret(mutualChapSecret); target.setAuthenticationProperties(auth); final List<HostInternetScsiHbaStaticTarget> lstTargets = new ArrayList<HostInternetScsiHbaStaticTarget>(); lstTargets.add(target); addRemoveInternetScsiTargetsToAllHosts(true, lstTargets, lstHosts); rescanAllHosts(lstHosts); HostMO host = new HostMO(context, lstHosts.get(0).first()); HostDatastoreSystemMO hostDatastoreSystem = host.getHostDatastoreSystemMO(); ManagedObjectReference morDs = hostDatastoreSystem.findDatastoreByName(datastoreName); if (morDs != null) { return morDs; } rescanAllHosts(lstHosts); HostStorageSystemMO hostStorageSystem = host.getHostStorageSystemMO(); List<HostScsiDisk> lstHostScsiDisks = hostDatastoreSystem.queryAvailableDisksForVmfs(); HostScsiDisk hostScsiDisk = getHostScsiDisk(hostStorageSystem.getStorageDeviceInfo().getScsiTopology(), lstHostScsiDisks, iqn); if (hostScsiDisk == null) { // check to see if the datastore actually does exist already morDs = hostDatastoreSystem.findDatastoreByName(datastoreName); if (morDs != null) { return morDs; } throw new Exception("A relevant SCSI disk could not be located to use to create a datastore."); } morDs = hostDatastoreSystem.createVmfsDatastore(datastoreName, hostScsiDisk); if (morDs != null) { rescanAllHosts(lstHosts); return morDs; } throw new Exception("Unable to create a datastore"); } // the purpose of this method is to find the HostScsiDisk in the passed-in array that exists (if any) because // we added the static iqn to an iSCSI HBA private static HostScsiDisk getHostScsiDisk(HostScsiTopology hst, List<HostScsiDisk> lstHostScsiDisks, String iqn) { for (HostScsiTopologyInterface adapter : hst.getAdapter()) { if (adapter.getTarget() != null) { for (HostScsiTopologyTarget target : adapter.getTarget()) { if (target.getTransport() instanceof HostInternetScsiTargetTransport) { String iScsiName = ((HostInternetScsiTargetTransport)target.getTransport()).getIScsiName(); if (iqn.equals(iScsiName)) { for (HostScsiDisk hostScsiDisk : lstHostScsiDisks) { for (HostScsiTopologyLun hstl : target.getLun()) { if (hstl.getScsiLun().contains(hostScsiDisk.getUuid())) { return hostScsiDisk; } } } } } } } } return null; } private void deleteVmfsDatastore(VmwareHypervisorHost hyperHost, String volumeUuid, String storageIpAddress, int storagePortNumber, String iqn) throws Exception { // hyperHost.unmountDatastore(volumeUuid); VmwareContext context = getServiceContext(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO cluster = new ClusterMO(context, morCluster); List<Pair<ManagedObjectReference, String>> lstHosts = cluster.getClusterHosts(); HostInternetScsiHbaStaticTarget target = new HostInternetScsiHbaStaticTarget(); target.setAddress(storageIpAddress); target.setPort(storagePortNumber); target.setIScsiName(iqn); final List<HostInternetScsiHbaStaticTarget> lstTargets = new ArrayList<HostInternetScsiHbaStaticTarget>(); lstTargets.add(target); addRemoveInternetScsiTargetsToAllHosts(false, lstTargets, lstHosts); rescanAllHosts(lstHosts); } protected Answer execute(AttachIsoCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource AttachIsoCommand: " + _gson.toJson(cmd)); } try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo == null) { String msg = "Unable to find VM in vSphere to execute AttachIsoCommand, vmName: " + cmd.getVmName(); s_logger.error(msg); throw new Exception(msg); } String storeUrl = cmd.getStoreUrl(); if (storeUrl == null) { if (!cmd.getIsoPath().equalsIgnoreCase("vmware-tools.iso")) { String msg = "ISO store root url is not found in AttachIsoCommand"; s_logger.error(msg); throw new Exception(msg); } else { if (cmd.isAttach()) { vmMo.mountToolsInstaller(); } else { try{ vmMo.unmountToolsInstaller(); }catch(Throwable e){ vmMo.detachIso(null); } } return new Answer(cmd); } } ManagedObjectReference morSecondaryDs = prepareSecondaryDatastoreOnHost(storeUrl); String isoPath = cmd.getIsoPath(); if (!isoPath.startsWith(storeUrl)) { assert (false); String msg = "ISO path does not start with the secondary storage root"; s_logger.error(msg); throw new Exception(msg); } int isoNameStartPos = isoPath.lastIndexOf('/'); String isoFileName = isoPath.substring(isoNameStartPos + 1); String isoStorePathFromRoot = isoPath.substring(storeUrl.length(), isoNameStartPos); // TODO, check if iso is already attached, or if there is a previous // attachment DatastoreMO secondaryDsMo = new DatastoreMO(getServiceContext(), morSecondaryDs); String storeName = secondaryDsMo.getName(); String isoDatastorePath = String.format("[%s] %s%s", storeName, isoStorePathFromRoot, isoFileName); if (cmd.isAttach()) { vmMo.attachIso(isoDatastorePath, morSecondaryDs, true, false); } else { vmMo.detachIso(isoDatastorePath); } return new Answer(cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } if(cmd.isAttach()) { String msg = "AttachIsoCommand(attach) failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } else { String msg = "AttachIsoCommand(detach) failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.warn(msg, e); return new Answer(cmd, false, msg); } } } public synchronized ManagedObjectReference prepareSecondaryDatastoreOnHost(String storeUrl) throws Exception { String storeName = getSecondaryDatastoreUUID(storeUrl); URI uri = new URI(storeUrl); VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ManagedObjectReference morDatastore = hyperHost.mountDatastore(false, uri.getHost(), 0, uri.getPath(), storeName.replace("-", "")); if (morDatastore == null) throw new Exception("Unable to mount secondary storage on host. storeUrl: " + storeUrl); return morDatastore; } private static String getSecondaryDatastoreUUID(String storeUrl) { return UUID.nameUUIDFromBytes(storeUrl.getBytes()).toString(); } protected Answer execute(ValidateSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ValidateSnapshotCommand: " + _gson.toJson(cmd)); } // the command is no longer available String expectedSnapshotBackupUuid = null; String actualSnapshotBackupUuid = null; String actualSnapshotUuid = null; return new ValidateSnapshotAnswer(cmd, false, "ValidateSnapshotCommand is not supported for vmware yet", expectedSnapshotBackupUuid, actualSnapshotBackupUuid, actualSnapshotUuid); } protected Answer execute(ManageSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ManageSnapshotCommand: " + _gson.toJson(cmd)); } long snapshotId = cmd.getSnapshotId(); /* * "ManageSnapshotCommand", * "{\"_commandSwitch\":\"-c\",\"_volumePath\":\"i-2-3-KY-ROOT\",\"_snapshotName\":\"i-2-3-KY_i-2-3-KY-ROOT_20101102203827\",\"_snapshotId\":1,\"_vmName\":\"i-2-3-KY\"}" */ boolean success = false; String cmdSwitch = cmd.getCommandSwitch(); String snapshotOp = "Unsupported snapshot command." + cmdSwitch; if (cmdSwitch.equals(ManageSnapshotCommand.CREATE_SNAPSHOT)) { snapshotOp = "create"; } else if (cmdSwitch.equals(ManageSnapshotCommand.DESTROY_SNAPSHOT)) { snapshotOp = "destroy"; } String details = "ManageSnapshotCommand operation: " + snapshotOp + " Failed for snapshotId: " + snapshotId; String snapshotUUID = null; // snapshot operation (create or destroy) is handled inside BackupSnapshotCommand(), we just fake // a success return here snapshotUUID = UUID.randomUUID().toString(); success = true; details = null; return new ManageSnapshotAnswer(cmd, snapshotId, snapshotUUID, success, details); } protected Answer execute(BackupSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource BackupSnapshotCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "BackupSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); return new BackupSnapshotAnswer(cmd, false, details, null, true); } } protected Answer execute(CreateVMSnapshotCommand cmd) { try { VmwareContext context = getServiceContext(); VmwareManager mgr = context .getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Exception e) { e.printStackTrace(); return new CreateVMSnapshotAnswer(cmd, false, ""); } } protected Answer execute(DeleteVMSnapshotCommand cmd) { try { VmwareContext context = getServiceContext(); VmwareManager mgr = context .getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Exception e) { e.printStackTrace(); return new DeleteVMSnapshotAnswer(cmd, false, ""); } } protected Answer execute(RevertToVMSnapshotCommand cmd){ try{ VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); }catch (Exception e){ e.printStackTrace(); return new RevertToVMSnapshotAnswer(cmd,false,""); } } protected Answer execute(CreateVolumeFromSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreateVolumeFromSnapshotCommand: " + _gson.toJson(cmd)); } String details = null; boolean success = false; String newVolumeName = UUID.randomUUID().toString(); try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } details = "CreateVolumeFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); } return new CreateVolumeFromSnapshotAnswer(cmd, success, details, newVolumeName); } protected Answer execute(CreatePrivateTemplateFromVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreatePrivateTemplateFromVolumeCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "CreatePrivateTemplateFromVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); return new CreatePrivateTemplateAnswer(cmd, false, details); } } protected Answer execute(final UpgradeSnapshotCommand cmd) { return new Answer(cmd, true, "success"); } protected Answer execute(CreatePrivateTemplateFromSnapshotCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreatePrivateTemplateFromSnapshotCommand: " + _gson.toJson(cmd)); } try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "CreatePrivateTemplateFromSnapshotCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); return new CreatePrivateTemplateAnswer(cmd, false, details); } } protected Answer execute(GetStorageStatsCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetStorageStatsCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, cmd.getStorageId()); if (morDs != null) { DatastoreMO datastoreMo = new DatastoreMO(context, morDs); DatastoreSummary summary = datastoreMo.getSummary(); assert (summary != null); long capacity = summary.getCapacity(); long free = summary.getFreeSpace(); long used = capacity - free; if (s_logger.isDebugEnabled()) { s_logger.debug("Datastore summary info, storageId: " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ", capacity: " + capacity + ", free: " + free + ", used: " + used); } if (summary.getCapacity() <= 0) { s_logger.warn("Something is wrong with vSphere NFS datastore, rebooting ESX(ESXi) host should help"); } return new GetStorageStatsAnswer(cmd, capacity, used); } else { String msg = "Could not find datastore for GetStorageStatsCommand storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype(); s_logger.error(msg); return new GetStorageStatsAnswer(cmd, msg); } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "Unable to execute GetStorageStatsCommand(storageId : " + cmd.getStorageId() + ", localPath: " + cmd.getLocalPath() + ", poolType: " + cmd.getPooltype() + ") due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new GetStorageStatsAnswer(cmd, msg); } } protected Answer execute(GetVncPortCommand cmd) { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing resource GetVncPortCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); assert(hyperHost instanceof HostMO); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getName()); if (vmMo == null) { if (s_logger.isDebugEnabled()) { s_logger.debug("Unable to find the owner VM for GetVncPortCommand on host " + hyperHost.getHyperHostName() + ", try within datacenter"); } vmMo = hyperHost.findVmOnPeerHyperHost(cmd.getName()); if (vmMo == null) { throw new Exception("Unable to find VM in vSphere, vm: " + cmd.getName()); } } Pair<String, Integer> portInfo = vmMo.getVncPort(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); if (s_logger.isTraceEnabled()) { s_logger.trace("Found vnc port info. vm: " + cmd.getName() + " host: " + portInfo.first() + ", vnc port: " + portInfo.second()); } return new GetVncPortAnswer(cmd, portInfo.first(), portInfo.second()); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "GetVncPortCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new GetVncPortAnswer(cmd, msg); } } protected Answer execute(SetupCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource SetupCommand: " + _gson.toJson(cmd)); } return new SetupAnswer(cmd, false); } protected Answer execute(MaintainCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource MaintainCommand: " + _gson.toJson(cmd)); } return new MaintainAnswer(cmd, "Put host in maintaince"); } protected Answer execute(PingTestCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PingTestCommand: " + _gson.toJson(cmd)); } String controlIp = cmd.getRouterIp(); String args = " -c 1 -n -q " + cmd.getPrivateIp(); try { VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/bin/ping" + args); if(result.first()) return new Answer(cmd); } catch (Exception e) { s_logger.error("Unable to execute ping command on DomR (" + controlIp + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return new Answer(cmd,false,"PingTestCommand failed"); } protected Answer execute(CheckOnHostCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CheckOnHostCommand: " + _gson.toJson(cmd)); } return new CheckOnHostAnswer(cmd, null, "Not Implmeneted"); } protected Answer execute(ModifySshKeysCommand cmd) { //do not log the command contents for this command. do NOT log the ssh keys if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource ModifySshKeysCommand."); } return new Answer(cmd); } protected Answer execute(PoolEjectCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PoolEjectCommand: " + _gson.toJson(cmd)); } return new Answer(cmd, false, "PoolEjectCommand is not available for vmware"); } @Override public PrimaryStorageDownloadAnswer execute(PrimaryStorageDownloadCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PrimaryStorageDownloadCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return (PrimaryStorageDownloadAnswer) mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "PrimaryStorageDownloadCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new PrimaryStorageDownloadAnswer(msg); } } protected Answer execute(PvlanSetupCommand cmd) { // Pvlan related operations are performed in the start/stop command paths // for vmware. This function is implemented to support mgmt layer code // that issue this command. Note that pvlan operations are supported only // in Distributed Virtual Switch environments for vmware deployments. return new Answer(cmd, true, "success"); } protected Answer execute(UnregisterVMCommand cmd){ if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource UnregisterVMCommand: " + _gson.toJson(cmd)); } VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); try { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(cmd.getVmName()); if (vmMo != null) { try { context.getService().unregisterVM(vmMo.getMor()); return new Answer(cmd, true, "unregister succeeded"); } catch(Exception e) { s_logger.warn("We are not able to unregister VM " + VmwareHelper.getExceptionMessage(e)); } String msg = "Expunge failed in vSphere. vm: " + cmd.getVmName(); s_logger.warn(msg); return new Answer(cmd, false, msg); } else { String msg = "Unable to find the VM in vSphere to unregister, assume it is already removed. VM: " + cmd.getVmName(); s_logger.warn(msg); return new Answer(cmd, true, msg); } } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "UnregisterVMCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } } /** * UnregisterNicCommand is used to remove a portgroup created for this * specific nic. The portgroup will have the name set to the UUID of the * nic. Introduced to cleanup the portgroups created for each nic that is * plugged into an lswitch (Nicira NVP plugin) * * @param cmd * @return */ protected Answer execute(UnregisterNicCommand cmd) { s_logger.info("Executing resource UnregisterNicCommand: " + _gson.toJson(cmd)); if (_guestTrafficInfo == null) { return new Answer(cmd, false, "No Guest Traffic Info found, unable to determine where to clean up"); } try { if (_guestTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch) { // For now we only need to cleanup the nvp specific portgroups // on the standard switches return new Answer(cmd, true, "Nothing to do"); } s_logger.debug("Cleaning up portgroup " + cmd.getNicUuid() + " on switch " + _guestTrafficInfo.getVirtualSwitchName()); VmwareContext context = getServiceContext(); VmwareHypervisorHost host = getHyperHost(context); ManagedObjectReference clusterMO = host.getHyperHostCluster(); // Get a list of all the hosts in this cluster @SuppressWarnings("unchecked") List<ManagedObjectReference> hosts = (List<ManagedObjectReference>) context.getVimClient() .getDynamicProperty(clusterMO, "host"); if (hosts == null) { return new Answer(cmd, false, "No hosts in cluster, which is pretty weird"); } for (ManagedObjectReference hostMOR : hosts) { HostMO hostMo = new HostMO(context, hostMOR); hostMo.deletePortGroup(cmd.getNicUuid().toString()); s_logger.debug("Removed portgroup " + cmd.getNicUuid() + " from host " + hostMo.getHostName()); } return new Answer(cmd, true, "Unregistered resources for NIC " + cmd.getNicUuid()); } catch (Exception e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "UnregisterVMCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); return new Answer(cmd, false, msg); } } public Answer execute(DeleteCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource DestroyCommand: " + _gson.toJson(cmd)); } /* * DestroyCommand content exafmple * * {"volume": {"id":5,"name":"Volume1", "mountPoint":"/export/home/kelven/vmware-test/primary", * "path":"6bb8762f-c34c-453c-8e03-26cc246ceec4", "size":0,"type":"DATADISK","resourceType": * "STORAGE_POOL","storagePoolType":"NetworkFilesystem", "poolId":0,"deviceId":0 } } * * {"volume": {"id":1, "name":"i-2-1-KY-ROOT", "mountPoint":"/export/home/kelven/vmware-test/primary", * "path":"i-2-1-KY-ROOT","size":0,"type":"ROOT", "resourceType":"STORAGE_POOL", "storagePoolType":"NetworkFilesystem", * "poolId":0,"deviceId":0 } } */ try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); VolumeObjectTO vol = (VolumeObjectTO)cmd.getData(); PrimaryDataStoreTO store = (PrimaryDataStoreTO)vol.getDataStore(); ManagedObjectReference morDs = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, store.getUuid()); if (morDs == null) { String msg = "Unable to find datastore based on volume mount point " + store.getPath(); s_logger.error(msg); throw new Exception(msg); } DatastoreMO dsMo = new DatastoreMO(context, morDs); ManagedObjectReference morDc = hyperHost.getHyperHostDatacenter(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); ClusterMO clusterMo = new ClusterMO(context, morCluster); if (vol.getVolumeType() == Volume.Type.ROOT) { String vmName = vol.getVmName(); if (vmName != null) { VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vmName); if (vmMo != null) { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy root volume and VM itself. vmName " + vmName); } HostMO hostMo = vmMo.getRunningHost(); List<NetworkDetails> networks = vmMo.getNetworksWithDetails(); // tear down all devices first before we destroy the VM to avoid accidently delete disk backing files if (getVmState(vmMo) != State.Stopped) vmMo.safePowerOff(_shutdown_waitMs); vmMo.tearDownDevices(new Class<?>[] { VirtualDisk.class, VirtualEthernetCard.class }); vmMo.destroy(); for (NetworkDetails netDetails : networks) { if (netDetails.getGCTag() != null && netDetails.getGCTag().equalsIgnoreCase("true")) { if (netDetails.getVMMorsOnNetwork() == null || netDetails.getVMMorsOnNetwork().length == 1) { cleanupNetwork(hostMo, netDetails); } } } } if (s_logger.isInfoEnabled()) s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk"); dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true); // root volume may be created via linked-clone, delete the delta disk as well if (_fullCloneFlag) { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk"); } dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true); } else { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-delta.vmdk"); } dsMo.deleteFile(vol.getPath() + "-delta.vmdk", morDc, true); } return new Answer(cmd, true, "Success"); } if (s_logger.isInfoEnabled()) { s_logger.info("Destroy root volume directly from datastore"); } } else { // evitTemplate will be converted into DestroyCommand, test if we are running in this case VirtualMachineMO vmMo = clusterMo.findVmOnHyperHost(vol.getPath()); if (vmMo != null) { if (s_logger.isInfoEnabled()) s_logger.info("Destroy template volume " + vol.getPath()); vmMo.destroy(); return new Answer(cmd, true, "Success"); } } String chainInfo = vol.getChainInfo(); if (chainInfo != null && !chainInfo.isEmpty()) { s_logger.info("Destroy volume by chain info: " + chainInfo); String[] diskChain = _gson.fromJson(chainInfo, String[].class); if (diskChain != null && diskChain.length > 0) { for (String backingName : diskChain) { if (s_logger.isInfoEnabled()) { s_logger.info("Delete volume backing file: " + backingName); } dsMo.deleteFile(backingName, morDc, true); } } else { if (s_logger.isInfoEnabled()) { s_logger.info("Empty disk chain info, fall back to try to delete by original backing file name"); } dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true); if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk"); } dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true); } } else { if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by original name: " + vol.getPath() + ".vmdk"); } dsMo.deleteFile(vol.getPath() + ".vmdk", morDc, true); if (s_logger.isInfoEnabled()) { s_logger.info("Destroy volume by derived name: " + vol.getPath() + "-flat.vmdk"); } dsMo.deleteFile(vol.getPath() + "-flat.vmdk", morDc, true); } return new Answer(cmd, true, "Success"); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "DestroyCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new Answer(cmd, false, msg); } } public void cleanupNetwork(HostMO hostMo, NetworkDetails netDetails) { // we will no longer cleanup VLAN networks in order to support native VMware HA /* * assert(netDetails.getName() != null); try { synchronized(this) { NetworkMO networkMo = new * NetworkMO(hostMo.getContext(), netDetails.getNetworkMor()); ManagedObjectReference[] vms = * networkMo.getVMsOnNetwork(); if(vms == null || vms.length == 0) { if(s_logger.isInfoEnabled()) { * s_logger.info("Cleanup network as it is currently not in use: " + netDetails.getName()); } * * hostMo.deletePortGroup(netDetails.getName()); } } } catch(Throwable e) { * s_logger.warn("Unable to cleanup network due to exception, skip for next time"); } */ } @Override public CopyVolumeAnswer execute(CopyVolumeCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CopyVolumeCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return (CopyVolumeAnswer) mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "CopyVolumeCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CopyVolumeAnswer(cmd, false, msg, null, null); } } @Override public CreateVolumeOVAAnswer execute(CreateVolumeOVACommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreateVolumeOVACommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return (CreateVolumeOVAAnswer) mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "CreateVolumeOVACommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CreateVolumeOVAAnswer(cmd, false, msg); } } protected Answer execute(PrepareOVAPackingCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource PrepareOVAPackingCommand: " + _gson.toJson(cmd)); } try { VmwareContext context = getServiceContext(); VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); return mgr.getStorageManager().execute(this, cmd); } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String details = "PrepareOVAPacking for template failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(details, e); return new PrepareOVAPackingAnswer(cmd, false, details); } } private boolean createVMFullClone(VirtualMachineMO vmTemplate, DatacenterMO dcMo, DatastoreMO dsMo, String vmdkName, ManagedObjectReference morDatastore, ManagedObjectReference morPool) throws Exception { if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName)) dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false); s_logger.info("creating full clone from template"); if (!vmTemplate.createFullClone(vmdkName, dcMo.getVmFolder(), morPool, morDatastore)) { String msg = "Unable to create full clone from the template"; s_logger.error(msg); throw new Exception(msg); } // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know // to move files s_logger.info("Move volume out of volume-wrapper VM "); dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); dsMo.moveDatastoreFile(String.format("[%s] %s/%s-flat.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s-flat.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); return true; } private boolean createVMLinkedClone(VirtualMachineMO vmTemplate, DatacenterMO dcMo, DatastoreMO dsMo, String vmdkName, ManagedObjectReference morDatastore, ManagedObjectReference morPool) throws Exception { ManagedObjectReference morBaseSnapshot = vmTemplate.getSnapshotMor("cloud.template.base"); if (morBaseSnapshot == null) { String msg = "Unable to find template base snapshot, invalid template"; s_logger.error(msg); throw new Exception(msg); } if(dsMo.folderExists(String.format("[%s]", dsMo.getName()), vmdkName)) dsMo.deleteFile(String.format("[%s] %s/", dsMo.getName(), vmdkName), dcMo.getMor(), false); s_logger.info("creating linked clone from template"); if (!vmTemplate.createLinkedClone(vmdkName, morBaseSnapshot, dcMo.getVmFolder(), morPool, morDatastore)) { String msg = "Unable to clone from the template"; s_logger.error(msg); throw new Exception(msg); } // we can't rely on un-offical API (VirtualMachineMO.moveAllVmDiskFiles() any more, use hard-coded disk names that we know // to move files s_logger.info("Move volume out of volume-wrapper VM "); dsMo.moveDatastoreFile(String.format("[%s] %s/%s.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); dsMo.moveDatastoreFile(String.format("[%s] %s/%s-delta.vmdk", dsMo.getName(), vmdkName, vmdkName), dcMo.getMor(), dsMo.getMor(), String.format("[%s] %s-delta.vmdk", dsMo.getName(), vmdkName), dcMo.getMor(), true); return true; } @Override public synchronized CreateAnswer execute(CreateCommand cmd) { if (s_logger.isInfoEnabled()) { s_logger.info("Executing resource CreateCommand: " + _gson.toJson(cmd)); } StorageFilerTO pool = cmd.getPool(); DiskProfile dskch = cmd.getDiskCharacteristics(); try { VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); DatacenterMO dcMo = new DatacenterMO(context, hyperHost.getHyperHostDatacenter()); ManagedObjectReference morDatastore = HypervisorHostHelper.findDatastoreWithBackwardsCompatibility(hyperHost, pool.getUuid()); if (morDatastore == null) throw new Exception("Unable to find datastore in vSphere"); DatastoreMO dsMo = new DatastoreMO(context, morDatastore); if (dskch.getType() == Volume.Type.ROOT) { // attach volume id to make the name unique String vmdkName = dskch.getName() + "-" + dskch.getVolumeId(); if (cmd.getTemplateUrl() == null) { // create a root volume for blank VM String dummyVmName = getWorkerName(context, cmd, 0); VirtualMachineMO vmMo = null; try { vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); if (vmMo == null) { throw new Exception("Unable to create a dummy VM for volume creation"); } String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), vmdkName); synchronized (this) { s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); VmwareHelper.deleteVolumeVmdkFiles(dsMo, vmdkName, dcMo); vmMo.createDisk(volumeDatastorePath, getMBsFromBytes(dskch.getSize()), morDatastore, -1); vmMo.detachDisk(volumeDatastorePath, false); } VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } finally { vmMo.detachAllDisks(); s_logger.info("Destroy dummy VM after volume creation"); vmMo.destroy(); } } else { VirtualMachineMO vmTemplate = VmwareHelper.pickOneVmOnRunningHost(dcMo.findVmByNameAndLabel(cmd.getTemplateUrl()), true); if (vmTemplate == null) { s_logger.warn("Template host in vSphere is not in connected state, request template reload"); return new CreateAnswer(cmd, "Template host in vSphere is not in connected state, request template reload", true); } ManagedObjectReference morPool = hyperHost.getHyperHostOwnerResourcePool(); ManagedObjectReference morCluster = hyperHost.getHyperHostCluster(); //createVMLinkedClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool); if (!_fullCloneFlag) { createVMLinkedClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool); } else { createVMFullClone(vmTemplate, dcMo, dsMo, vmdkName, morDatastore, morPool); } VirtualMachineMO vmMo = new ClusterMO(context, morCluster).findVmOnHyperHost(vmdkName); assert (vmMo != null); s_logger.info("detach disks from volume-wrapper VM " + vmdkName); vmMo.detachAllDisks(); s_logger.info("destroy volume-wrapper VM " + vmdkName); vmMo.destroy(); String srcFile = String.format("[%s] %s/", dsMo.getName(), vmdkName); dsMo.deleteFile(srcFile, dcMo.getMor(), true); VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), vmdkName, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } } else { // create data volume VirtualMachineMO vmMo = null; String volumeUuid = UUID.randomUUID().toString().replace("-", ""); String volumeDatastorePath = String.format("[%s] %s.vmdk", dsMo.getName(), volumeUuid); String dummyVmName = getWorkerName(context, cmd, 0); try { vmMo = prepareVolumeHostDummyVm(hyperHost, dsMo, dummyVmName); if (vmMo == null) { throw new Exception("Unable to create a dummy VM for volume creation"); } synchronized (this) { // s_logger.info("Delete file if exists in datastore to clear the way for creating the volume. file: " + volumeDatastorePath); VmwareHelper.deleteVolumeVmdkFiles(dsMo, volumeUuid.toString(), dcMo); vmMo.createDisk(volumeDatastorePath, getMBsFromBytes(dskch.getSize()), morDatastore, vmMo.getScsiDeviceControllerKey()); vmMo.detachDisk(volumeDatastorePath, false); } VolumeTO vol = new VolumeTO(cmd.getVolumeId(), dskch.getType(), pool.getType(), pool.getUuid(), dskch.getName(), pool.getPath(), volumeUuid, dskch.getSize(), null); return new CreateAnswer(cmd, vol); } finally { s_logger.info("Destroy dummy VM after volume creation"); vmMo.detachAllDisks(); vmMo.destroy(); } } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } String msg = "CreateCommand failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); return new CreateAnswer(cmd, new Exception(e)); } } private static int getMBsFromBytes(long bytes) { return (int)(bytes / (1024L * 1024L)); } protected VirtualMachineMO prepareVolumeHostDummyVm(VmwareHypervisorHost hyperHost, DatastoreMO dsMo, String vmName) throws Exception { assert (hyperHost != null); VirtualMachineMO vmMo = null; VirtualMachineConfigSpec vmConfig = new VirtualMachineConfigSpec(); vmConfig.setName(vmName); vmConfig.setMemoryMB((long) 4); // vmware request minimum of 4 MB vmConfig.setNumCPUs(1); vmConfig.setGuestId(VirtualMachineGuestOsIdentifier.OTHER_GUEST.value()); VirtualMachineFileInfo fileInfo = new VirtualMachineFileInfo(); fileInfo.setVmPathName(String.format("[%s]", dsMo.getName())); vmConfig.setFiles(fileInfo); // Scsi controller VirtualLsiLogicController scsiController = new VirtualLsiLogicController(); scsiController.setSharedBus(VirtualSCSISharing.NO_SHARING); scsiController.setBusNumber(0); scsiController.setKey(1); VirtualDeviceConfigSpec scsiControllerSpec = new VirtualDeviceConfigSpec(); scsiControllerSpec.setDevice(scsiController); scsiControllerSpec.setOperation(VirtualDeviceConfigSpecOperation.ADD); vmConfig.getDeviceChange().add(scsiControllerSpec ); hyperHost.createVm(vmConfig); vmMo = hyperHost.findVmOnHyperHost(vmName); return vmMo; } @Override public void disconnected() { } @Override public IAgentControl getAgentControl() { return null; } @Override public PingCommand getCurrentStatus(long id) { HashMap<String, State> newStates = sync(); if (newStates == null) { return null; } try { // take the chance to do left-over dummy VM cleanup from previous run VmwareContext context = getServiceContext(); VmwareHypervisorHost hyperHost = getHyperHost(context); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if(hyperHost.isHyperHostConnected()) { mgr.gcLeftOverVMs(context); if(_recycleHungWorker) { s_logger.info("Scan hung worker VM to recycle"); // GC worker that has been running for too long ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost( new String[] {"name", "config.template", "runtime.powerState", "runtime.bootTime"}); if(ocs != null) { for(ObjectContent oc : ocs) { List<DynamicProperty> props = oc.getPropSet(); if(props != null) { String name = null; boolean template = false; VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF; GregorianCalendar bootTime = null; for(DynamicProperty prop : props) { if(prop.getName().equals("name")) name = prop.getVal().toString(); else if(prop.getName().equals("config.template")) template = (Boolean)prop.getVal(); else if(prop.getName().equals("runtime.powerState")) powerState = (VirtualMachinePowerState)prop.getVal(); else if(prop.getName().equals("runtime.bootTime")) bootTime = (GregorianCalendar)prop.getVal(); } if(!template && name.matches("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")) { boolean recycle = false; // recycle stopped worker VM and VM that has been running for too long (hard-coded 10 hours for now) if(powerState == VirtualMachinePowerState.POWERED_OFF) recycle = true; else if(bootTime != null && (new Date().getTime() - bootTime.getTimeInMillis() > 10*3600*1000)) recycle = true; if(recycle) { s_logger.info("Recycle pending worker VM: " + name); VirtualMachineMO vmMo = new VirtualMachineMO(hyperHost.getContext(), oc.getObj()); vmMo.powerOff(); vmMo.destroy(); } } } } } } } else { s_logger.error("Host is no longer connected."); return null; } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); return null; } } return new PingRoutingCommand(getType(), id, newStates); } @Override public Type getType() { return com.cloud.host.Host.Type.Routing; } @Override public StartupCommand[] initialize() { String hostApiVersion = "4.1"; VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); assert(hyperHost instanceof HostMO); if(!((HostMO)hyperHost).isHyperHostConnected()) { s_logger.info("Host " + hyperHost.getHyperHostName() + " is not in connected state"); return null; } AboutInfo aboutInfo = ((HostMO)hyperHost).getHostAboutInfo(); hostApiVersion = aboutInfo.getApiVersion(); } catch (Exception e) { String msg = "VmwareResource intialize() failed due to : " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); invalidateServiceContext(); return null; } StartupRoutingCommand cmd = new StartupRoutingCommand(); fillHostInfo(cmd); Map<String, State> changes = null; synchronized (_vms) { _vms.clear(); changes = sync(); } cmd.setHypervisorType(HypervisorType.VMware); cmd.setStateChanges(changes); cmd.setCluster(_cluster); cmd.setHypervisorVersion(hostApiVersion); List<StartupStorageCommand> storageCmds = initializeLocalStorage(); StartupCommand[] answerCmds = new StartupCommand[1 + storageCmds.size()]; answerCmds[0] = cmd; for (int i = 0; i < storageCmds.size(); i++) { answerCmds[i + 1] = storageCmds.get(i); } return answerCmds; } private List<StartupStorageCommand> initializeLocalStorage() { List<StartupStorageCommand> storageCmds = new ArrayList<StartupStorageCommand>(); VmwareContext context = getServiceContext(); try { VmwareHypervisorHost hyperHost = getHyperHost(context); if (hyperHost instanceof HostMO) { HostMO hostMo = (HostMO) hyperHost; List<Pair<ManagedObjectReference, String>> dsList = hostMo.getLocalDatastoreOnHost(); for (Pair<ManagedObjectReference, String> dsPair : dsList) { DatastoreMO dsMo = new DatastoreMO(context, dsPair.first()); String poolUuid = dsMo.getCustomFieldValue(CustomFieldConstants.CLOUD_UUID); if (poolUuid == null || poolUuid.isEmpty()) { poolUuid = UUID.randomUUID().toString(); dsMo.setCustomFieldValue(CustomFieldConstants.CLOUD_UUID, poolUuid); } DatastoreSummary dsSummary = dsMo.getSummary(); String address = hostMo.getHostName(); StoragePoolInfo pInfo = new StoragePoolInfo(poolUuid, address, dsMo.getMor().getValue(), "", StoragePoolType.LVM, dsSummary.getCapacity(), dsSummary.getFreeSpace()); StartupStorageCommand cmd = new StartupStorageCommand(); cmd.setName(poolUuid); cmd.setPoolInfo(pInfo); cmd.setGuid(poolUuid); // give storage host the same UUID as the local storage pool itself cmd.setResourceType(Storage.StorageResourceType.STORAGE_POOL); cmd.setDataCenter(_dcId); cmd.setPod(_pod); cmd.setCluster(_cluster); s_logger.info("Add local storage startup command: " + _gson.toJson(cmd)); storageCmds.add(cmd); } } else { s_logger.info("Cluster host does not support local storage, skip it"); } } catch (Exception e) { String msg = "initializing local storage failed due to : " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg); invalidateServiceContext(); throw new CloudRuntimeException(msg); } return storageCmds; } protected void fillHostInfo(StartupRoutingCommand cmd) { VmwareContext serviceContext = getServiceContext(); Map<String, String> details = cmd.getHostDetails(); if (details == null) { details = new HashMap<String, String>(); } try { fillHostHardwareInfo(serviceContext, cmd); fillHostNetworkInfo(serviceContext, cmd); fillHostDetailsInfo(serviceContext, details); } catch (RuntimeFaultFaultMsg e) { s_logger.error("RuntimeFault while retrieving host info: " + e.toString(), e); throw new CloudRuntimeException("RuntimeFault while retrieving host info"); } catch (RemoteException e) { s_logger.error("RemoteException while retrieving host info: " + e.toString(), e); invalidateServiceContext(); throw new CloudRuntimeException("RemoteException while retrieving host info"); } catch (Exception e) { s_logger.error("Exception while retrieving host info: " + e.toString(), e); invalidateServiceContext(); throw new CloudRuntimeException("Exception while retrieving host info: " + e.toString()); } cmd.setHostDetails(details); cmd.setName(_url); cmd.setGuid(_guid); cmd.setDataCenter(_dcId); cmd.setPod(_pod); cmd.setCluster(_cluster); cmd.setVersion(VmwareResource.class.getPackage().getImplementationVersion()); } private void fillHostHardwareInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException, Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); VmwareHypervisorHostResourceSummary summary = hyperHost.getHyperHostResourceSummary(); if (s_logger.isInfoEnabled()) { s_logger.info("Startup report on host hardware info. " + _gson.toJson(summary)); } cmd.setCaps("hvm"); cmd.setDom0MinMemory(0); cmd.setSpeed(summary.getCpuSpeed()); cmd.setCpus((int) summary.getCpuCount()); cmd.setMemory(summary.getMemoryBytes()); } private void fillHostNetworkInfo(VmwareContext serviceContext, StartupRoutingCommand cmd) throws RuntimeFaultFaultMsg, RemoteException { try { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); assert(hyperHost instanceof HostMO); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VmwareHypervisorHostNetworkSummary summary = hyperHost.getHyperHostNetworkSummary(mgr.getManagementPortGroupByHost((HostMO)hyperHost)); if (summary == null) { throw new Exception("No ESX(i) host found"); } if (s_logger.isInfoEnabled()) { s_logger.info("Startup report on host network info. " + _gson.toJson(summary)); } cmd.setPrivateIpAddress(summary.getHostIp()); cmd.setPrivateNetmask(summary.getHostNetmask()); cmd.setPrivateMacAddress(summary.getHostMacAddress()); cmd.setStorageIpAddress(summary.getHostIp()); cmd.setStorageNetmask(summary.getHostNetmask()); cmd.setStorageMacAddress(summary.getHostMacAddress()); } catch (Throwable e) { String msg = "querying host network info failed due to " + VmwareHelper.getExceptionMessage(e); s_logger.error(msg, e); throw new CloudRuntimeException(msg); } } private void fillHostDetailsInfo(VmwareContext serviceContext, Map<String, String> details) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ClusterDasConfigInfo dasConfig = hyperHost.getDasConfig(); if (dasConfig != null && dasConfig.isEnabled() != null && dasConfig.isEnabled().booleanValue()) { details.put("NativeHA", "true"); } } protected HashMap<String, State> sync() { HashMap<String, State> changes = new HashMap<String, State>(); HashMap<String, State> oldStates = null; try { synchronized (_vms) { HashMap<String, State> newStates = getVmStates(); oldStates = new HashMap<String, State>(_vms.size()); oldStates.putAll(_vms); for (final Map.Entry<String, State> entry : newStates.entrySet()) { final String vm = entry.getKey(); State newState = entry.getValue(); final State oldState = oldStates.remove(vm); if (s_logger.isTraceEnabled()) { s_logger.trace("VM " + vm + ": vSphere has state " + newState + " and we have state " + (oldState != null ? oldState.toString() : "null")); } if (vm.startsWith("migrating")) { s_logger.debug("Migrating detected. Skipping"); continue; } if (oldState == null) { _vms.put(vm, newState); s_logger.debug("Detecting a new state but couldn't find a old state so adding it to the changes: " + vm); changes.put(vm, newState); } else if (oldState == State.Starting) { if (newState == State.Running) { _vms.put(vm, newState); } else if (newState == State.Stopped) { s_logger.debug("Ignoring vm " + vm + " because of a lag in starting the vm."); } } else if (oldState == State.Migrating) { if (newState == State.Running) { s_logger.debug("Detected that an migrating VM is now running: " + vm); _vms.put(vm, newState); } } else if (oldState == State.Stopping) { if (newState == State.Stopped) { _vms.put(vm, newState); } else if (newState == State.Running) { s_logger.debug("Ignoring vm " + vm + " because of a lag in stopping the vm. "); } } else if (oldState != newState) { _vms.put(vm, newState); if (newState == State.Stopped) { /* * if (_vmsKilled.remove(vm)) { s_logger.debug("VM " + vm + " has been killed for storage. "); * newState = State.Error; } */ } changes.put(vm, newState); } } for (final Map.Entry<String, State> entry : oldStates.entrySet()) { final String vm = entry.getKey(); final State oldState = entry.getValue(); if (isVmInCluster(vm)) { if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + vm + " is now missing from host report but we detected that it might be migrated to other host by vCenter"); } if(oldState != State.Starting && oldState != State.Migrating) { s_logger.debug("VM " + vm + " is now missing from host report and VM is not at starting/migrating state, remove it from host VM-sync map, oldState: " + oldState); _vms.remove(vm); } else { s_logger.debug("VM " + vm + " is missing from host report, but we will ignore VM " + vm + " in transition state " + oldState); } continue; } if (s_logger.isDebugEnabled()) { s_logger.debug("VM " + vm + " is now missing from host report"); } if (oldState == State.Stopping) { s_logger.debug("Ignoring VM " + vm + " in transition state stopping."); _vms.remove(vm); } else if (oldState == State.Starting) { s_logger.debug("Ignoring VM " + vm + " in transition state starting."); } else if (oldState == State.Stopped) { _vms.remove(vm); } else if (oldState == State.Migrating) { s_logger.debug("Ignoring VM " + vm + " in migrating state."); } else { State state = State.Stopped; changes.put(entry.getKey(), state); } } } } catch (Throwable e) { if (e instanceof RemoteException) { s_logger.warn("Encounter remote exception to vCenter, invalidate VMware session context"); invalidateServiceContext(); } s_logger.error("Unable to perform sync information collection process at this point due to " + VmwareHelper.getExceptionMessage(e), e); return null; } return changes; } private boolean isVmInCluster(String vmName) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); return hyperHost.findVmOnPeerHyperHost(vmName) != null; } protected OptionValue[] configureVnc(OptionValue[] optionsToMerge, VmwareHypervisorHost hyperHost, String vmName, String vncPassword, String keyboardLayout) throws Exception { VirtualMachineMO vmMo = hyperHost.findVmOnHyperHost(vmName); VmwareManager mgr = hyperHost.getContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); if(!mgr.beginExclusiveOperation(600)) throw new Exception("Unable to begin exclusive operation, lock time out"); try { int maxVncPorts = 64; int vncPort = 0; Random random = new Random(); HostMO vmOwnerHost = vmMo.getRunningHost(); ManagedObjectReference morParent = vmOwnerHost.getParentMor(); HashMap<String, Integer> portInfo; if(morParent.getType().equalsIgnoreCase("ClusterComputeResource")) { ClusterMO clusterMo = new ClusterMO(vmOwnerHost.getContext(), morParent); portInfo = clusterMo.getVmVncPortsOnCluster(); } else { portInfo = vmOwnerHost.getVmVncPortsOnHost(); } // allocate first at 5900 - 5964 range Collection<Integer> existingPorts = portInfo.values(); int val = random.nextInt(maxVncPorts); int startVal = val; do { if (!existingPorts.contains(5900 + val)) { vncPort = 5900 + val; break; } val = (++val) % maxVncPorts; } while (val != startVal); if(vncPort == 0) { s_logger.info("we've run out of range for ports between 5900-5964 for the cluster, we will try port range at 59000-60000"); Pair<Integer, Integer> additionalRange = mgr.getAddiionalVncPortRange(); maxVncPorts = additionalRange.second(); val = random.nextInt(maxVncPorts); startVal = val; do { if (!existingPorts.contains(additionalRange.first() + val)) { vncPort = additionalRange.first() + val; break; } val = (++val) % maxVncPorts; } while (val != startVal); } if (vncPort == 0) { throw new Exception("Unable to find an available VNC port on host"); } if (s_logger.isInfoEnabled()) { s_logger.info("Configure VNC port for VM " + vmName + ", port: " + vncPort + ", host: " + vmOwnerHost.getHyperHostName()); } return VmwareHelper.composeVncOptions(optionsToMerge, true, vncPassword, vncPort, keyboardLayout); } finally { try { mgr.endExclusiveOperation(); } catch(Throwable e) { assert(false); s_logger.error("Unexpected exception ", e); } } } private VirtualMachineGuestOsIdentifier translateGuestOsIdentifier(String cpuArchitecture, String cloudGuestOs) { if (cpuArchitecture == null) { s_logger.warn("CPU arch is not set, default to i386. guest os: " + cloudGuestOs); cpuArchitecture = "i386"; } VirtualMachineGuestOsIdentifier identifier = VmwareGuestOsMapper.getGuestOsIdentifier(cloudGuestOs); if (identifier != null) { return identifier; } if (cpuArchitecture.equalsIgnoreCase("x86_64")) { return VirtualMachineGuestOsIdentifier.OTHER_GUEST_64; } return VirtualMachineGuestOsIdentifier.OTHER_GUEST; } private HashMap<String, State> getVmStates() throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] { "name", "runtime.powerState", "config.template" }); HashMap<String, State> newStates = new HashMap<String, State>(); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { List<DynamicProperty> objProps = oc.getPropSet(); if (objProps != null) { boolean isTemplate = false; String name = null; VirtualMachinePowerState powerState = VirtualMachinePowerState.POWERED_OFF; for (DynamicProperty objProp : objProps) { if (objProp.getName().equals("config.template")) { if (objProp.getVal().toString().equalsIgnoreCase("true")) { isTemplate = true; } } else if (objProp.getName().equals("name")) { name = (String) objProp.getVal(); } else if (objProp.getName().equals("runtime.powerState")) { powerState = (VirtualMachinePowerState) objProp.getVal(); } else { assert (false); } } if (!isTemplate) { newStates.put(name, convertState(powerState)); } } } } return newStates; } private HashMap<String, VmStatsEntry> getVmStats(List<String> vmNames) throws Exception { VmwareHypervisorHost hyperHost = getHyperHost(getServiceContext()); HashMap<String, VmStatsEntry> vmResponseMap = new HashMap<String, VmStatsEntry>(); ManagedObjectReference perfMgr = getServiceContext().getServiceContent().getPerfManager(); VimPortType service = getServiceContext().getService(); PerfCounterInfo rxPerfCounterInfo = null; PerfCounterInfo txPerfCounterInfo = null; List<PerfCounterInfo> cInfo = (List<PerfCounterInfo>) getServiceContext().getVimClient().getDynamicProperty(perfMgr, "perfCounter"); for(PerfCounterInfo info : cInfo) { if ("net".equalsIgnoreCase(info.getGroupInfo().getKey())) { if ("transmitted".equalsIgnoreCase(info.getNameInfo().getKey())) { txPerfCounterInfo = info; } if ("received".equalsIgnoreCase(info.getNameInfo().getKey())) { rxPerfCounterInfo = info; } } } ObjectContent[] ocs = hyperHost.getVmPropertiesOnHyperHost(new String[] {"name", "summary.config.numCpu", "summary.quickStats.overallCpuUsage"}); if (ocs != null && ocs.length > 0) { for (ObjectContent oc : ocs) { List<DynamicProperty> objProps = oc.getPropSet(); if (objProps != null) { String name = null; String numberCPUs = null; String maxCpuUsage = null; for (DynamicProperty objProp : objProps) { if (objProp.getName().equals("name")) { name = objProp.getVal().toString(); } else if (objProp.getName().equals("summary.config.numCpu")) { numberCPUs = objProp.getVal().toString(); } else if (objProp.getName().equals("summary.quickStats.overallCpuUsage")) { maxCpuUsage = objProp.getVal().toString(); } } if (!vmNames.contains(name)) { continue; } ManagedObjectReference vmMor = hyperHost.findVmOnHyperHost(name).getMor(); assert(vmMor!=null); ArrayList vmNetworkMetrics = new ArrayList(); // get all the metrics from the available sample period List<PerfMetricId> perfMetrics = service.queryAvailablePerfMetric(perfMgr, vmMor, null, null, null); if(perfMetrics != null) { for(int index=0; index < perfMetrics.size(); ++index) { if ( ((rxPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == rxPerfCounterInfo.getKey())) || ((txPerfCounterInfo != null) && (perfMetrics.get(index).getCounterId() == txPerfCounterInfo.getKey())) ) { vmNetworkMetrics.add(perfMetrics.get(index)); } } } double networkReadKBs=0; double networkWriteKBs=0; long sampleDuration=0; if (vmNetworkMetrics.size() != 0) { PerfQuerySpec qSpec = new PerfQuerySpec(); qSpec.setEntity(vmMor); PerfMetricId[] availableMetricIds = (PerfMetricId[]) vmNetworkMetrics.toArray(new PerfMetricId[0]); qSpec.getMetricId().addAll(Arrays.asList(availableMetricIds)); List<PerfQuerySpec> qSpecs = new ArrayList<PerfQuerySpec>(); qSpecs.add(qSpec); List<PerfEntityMetricBase> values = service.queryPerf(perfMgr, qSpecs); for(int i=0; i<values.size(); ++i) { List<PerfSampleInfo> infos = ((PerfEntityMetric)values.get(i)).getSampleInfo(); int endMs = infos.get(infos.size()-1).getTimestamp().getSecond() * 1000 + infos.get(infos.size()-1).getTimestamp().getMillisecond(); int beginMs = infos.get(0).getTimestamp().getSecond() * 1000 + infos.get(0).getTimestamp().getMillisecond(); sampleDuration = (endMs - beginMs) /1000; List<PerfMetricSeries> vals = ((PerfEntityMetric)values.get(i)).getValue(); for(int vi = 0; ((vals!= null) && (vi < vals.size())); ++vi){ if(vals.get(vi) instanceof PerfMetricIntSeries) { PerfMetricIntSeries val = (PerfMetricIntSeries)vals.get(vi); List<Long> perfValues = val.getValue(); if (vals.get(vi).getId().getCounterId() == rxPerfCounterInfo.getKey()) { networkReadKBs = sampleDuration * perfValues.get(3); //get the average RX rate multiplied by sampled duration } if (vals.get(vi).getId().getCounterId() == txPerfCounterInfo.getKey()) { networkWriteKBs = sampleDuration * perfValues.get(3);//get the average TX rate multiplied by sampled duration } } } } } vmResponseMap.put(name, new VmStatsEntry(Integer.parseInt(maxCpuUsage), networkReadKBs, networkWriteKBs, Integer.parseInt(numberCPUs), "vm")); } } } return vmResponseMap; } protected String networkUsage(final String privateIpAddress, final String option, final String ethName) { String args = null; if (option.equals("get")) { args = "-g"; } else if (option.equals("create")) { args = "-c"; } else if (option.equals("reset")) { args = "-r"; } else if (option.equals("addVif")) { args = "-a"; args += ethName; } else if (option.equals("deleteVif")) { args = "-d"; args += ethName; } try { if (s_logger.isTraceEnabled()) { s_logger.trace("Executing /opt/cloud/bin/netusage.sh " + args + " on DomR " + privateIpAddress); } VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); Pair<Boolean, String> result = SshHelper.sshExecute(privateIpAddress, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/netusage.sh " + args); if (!result.first()) { return null; } return result.second(); } catch (Throwable e) { s_logger.error("Unable to execute NetworkUsage command on DomR (" + privateIpAddress + "), domR may not be ready yet. failure due to " + VmwareHelper.getExceptionMessage(e), e); } return null; } private long[] getNetworkStats(String privateIP) { String result = networkUsage(privateIP, "get", null); long[] stats = new long[2]; if (result != null) { try { String[] splitResult = result.split(":"); int i = 0; while (i < splitResult.length - 1) { stats[0] += (new Long(splitResult[i++])).longValue(); stats[1] += (new Long(splitResult[i++])).longValue(); } } catch (Throwable e) { s_logger.warn("Unable to parse return from script return of network usage command: " + e.toString(), e); } } return stats; } protected String connect(final String vmName, final String ipAddress, final int port) { long startTick = System.currentTimeMillis(); // wait until we have at least been waiting for _ops_timeout time or // at least have tried _retry times, this is to coordinate with system // VM patching/rebooting time that may need int retry = _retry; while (System.currentTimeMillis() - startTick <= _ops_timeout || --retry > 0) { SocketChannel sch = null; try { s_logger.info("Trying to connect to " + ipAddress); sch = SocketChannel.open(); sch.configureBlocking(true); sch.socket().setSoTimeout(5000); InetSocketAddress addr = new InetSocketAddress(ipAddress, port); sch.connect(addr); return null; } catch (IOException e) { s_logger.info("Could not connect to " + ipAddress + " due to " + e.toString()); if (e instanceof ConnectException) { // if connection is refused because of VM is being started, // we give it more sleep time // to avoid running out of retry quota too quickly try { Thread.sleep(5000); } catch (InterruptedException ex) { } } } finally { if (sch != null) { try { sch.close(); } catch (IOException e) { } } } try { Thread.sleep(1000); } catch (InterruptedException ex) { } } s_logger.info("Unable to logon to " + ipAddress); return "Unable to connect"; } protected String connect(final String vmname, final String ipAddress) { return connect(vmname, ipAddress, 3922); } private static State convertState(VirtualMachinePowerState powerState) { return s_statesTable.get(powerState); } public static State getVmState(VirtualMachineMO vmMo) throws Exception { VirtualMachineRuntimeInfo runtimeInfo = vmMo.getRuntimeInfo(); return convertState(runtimeInfo.getPowerState()); } private static HostStatsEntry getHyperHostStats(VmwareHypervisorHost hyperHost) throws Exception { ComputeResourceSummary hardwareSummary = hyperHost.getHyperHostHardwareSummary(); if(hardwareSummary == null) return null; HostStatsEntry entry = new HostStatsEntry(); entry.setEntityType("host"); double cpuUtilization = ((double) (hardwareSummary.getTotalCpu() - hardwareSummary.getEffectiveCpu()) / (double) hardwareSummary.getTotalCpu() * 100); entry.setCpuUtilization(cpuUtilization); entry.setTotalMemoryKBs(hardwareSummary.getTotalMemory() / 1024); entry.setFreeMemoryKBs(hardwareSummary.getEffectiveMemory() * 1024); return entry; } private static String getRouterSshControlIp(NetworkElementCommand cmd) { String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); String routerGuestIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_GUEST_IP); String zoneNetworkType = cmd.getAccessDetail(NetworkElementCommand.ZONE_NETWORK_TYPE); if(routerGuestIp != null && zoneNetworkType != null && NetworkType.valueOf(zoneNetworkType) == NetworkType.Basic) { if(s_logger.isDebugEnabled()) s_logger.debug("In Basic zone mode, use router's guest IP for SSH control. guest IP : " + routerGuestIp); return routerGuestIp; } if(s_logger.isDebugEnabled()) s_logger.debug("Use router's private IP for SSH control. IP : " + routerIp); return routerIp; } @Override public void setAgentControl(IAgentControl agentControl) { } @Override public boolean configure(String name, Map<String, Object> params) throws ConfigurationException { _name = name; _url = (String) params.get("url"); _username = (String) params.get("username"); _password = (String) params.get("password"); _dcId = (String) params.get("zone"); _pod = (String) params.get("pod"); _cluster = (String) params.get("cluster"); _guid = (String) params.get("guid"); String[] tokens = _guid.split("@"); _vCenterAddress = tokens[1]; _morHyperHost = new ManagedObjectReference(); String[] hostTokens = tokens[0].split(":"); _morHyperHost.setType(hostTokens[0]); _morHyperHost.setValue(hostTokens[1]); _guestTrafficInfo = (VmwareTrafficLabel) params.get("guestTrafficInfo"); _publicTrafficInfo = (VmwareTrafficLabel) params.get("publicTrafficInfo"); VmwareContext context = getServiceContext(); volMgr = ComponentContext.inject(VolumeManagerImpl.class); try { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); mgr.setupResourceStartupParams(params); CustomFieldsManagerMO cfmMo = new CustomFieldsManagerMO(context, context.getServiceContent().getCustomFieldsManager()); cfmMo.ensureCustomFieldDef("Datastore", CustomFieldConstants.CLOUD_UUID); if (_publicTrafficInfo != null && _publicTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch || _guestTrafficInfo != null && _guestTrafficInfo.getVirtualSwitchType() != VirtualSwitchType.StandardVirtualSwitch) { cfmMo.ensureCustomFieldDef("DistributedVirtualPortgroup", CustomFieldConstants.CLOUD_GC_DVP); } cfmMo.ensureCustomFieldDef("Network", CustomFieldConstants.CLOUD_GC); cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_UUID); cfmMo.ensureCustomFieldDef("VirtualMachine", CustomFieldConstants.CLOUD_NIC_MASK); VmwareHypervisorHost hostMo = this.getHyperHost(context); _hostName = hostMo.getHyperHostName(); Map<String, String> vsmCredentials; if (_guestTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch || _publicTrafficInfo.getVirtualSwitchType() == VirtualSwitchType.NexusDistributedVirtualSwitch) { vsmCredentials = mgr.getNexusVSMCredentialsByClusterId(Long.parseLong(_cluster)); if (vsmCredentials != null) { s_logger.info("Stocking credentials while configuring resource."); context.registerStockObject("vsmcredentials", vsmCredentials); } _privateNetworkVSwitchName = mgr.getPrivateVSwitchName(Long.parseLong(_dcId), HypervisorType.VMware); } } catch (Exception e) { s_logger.error("Unexpected Exception ", e); } if(_privateNetworkVSwitchName == null) { _privateNetworkVSwitchName = (String) params.get("private.network.vswitch.name"); } String value = (String) params.get("vmware.reserve.cpu"); if(value != null && value.equalsIgnoreCase("true")) _reserveCpu = true; value = (String) params.get("vmware.recycle.hung.wokervm"); if(value != null && value.equalsIgnoreCase("true")) _recycleHungWorker = true; value = (String) params.get("vmware.reserve.mem"); if(value != null && value.equalsIgnoreCase("true")) _reserveMem = true; value = (String)params.get("vmware.root.disk.controller"); if(value != null && value.equalsIgnoreCase("scsi")) _rootDiskController = DiskControllerType.scsi; else _rootDiskController = DiskControllerType.ide; Integer intObj = (Integer) params.get("ports.per.dvportgroup"); if (intObj != null) _portsPerDvPortGroup = intObj.intValue(); s_logger.info("VmwareResource network configuration info." + " private traffic over vSwitch: " + _privateNetworkVSwitchName + ", public traffic over " + _publicTrafficInfo.getVirtualSwitchType() + " : " + _publicTrafficInfo.getVirtualSwitchName() + ", guest traffic over " + _guestTrafficInfo.getVirtualSwitchType() + " : " + _guestTrafficInfo.getVirtualSwitchName()); value = params.get("vmware.create.full.clone").toString(); if (value != null && value.equalsIgnoreCase("true")) { _fullCloneFlag = true; } else { _fullCloneFlag = false; } value = (String)params.get("scripts.timeout"); int timeout = NumbersUtil.parseInt(value, 1440) * 1000; VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); VmwareStorageProcessor storageProcessor = new VmwareStorageProcessor((VmwareHostService)this, _fullCloneFlag, (VmwareStorageMount)mgr, timeout, this, _shutdown_waitMs ); storageHandler = new StorageSubsystemCommandHandlerBase(storageProcessor); return true; } @Override public String getName() { return _name; } @Override public boolean start() { return true; } @Override public boolean stop() { return true; } public VmwareContext getServiceContext() { return getServiceContext(null); } public void invalidateServiceContext() { invalidateServiceContext(null); } public VmwareHypervisorHost getHyperHost(VmwareContext context) { return getHyperHost(context, null); } @Override public synchronized VmwareContext getServiceContext(Command cmd) { if (_serviceContext == null) { try { _serviceContext = VmwareContextFactory.create(_vCenterAddress, _username, _password); VmwareHypervisorHost hyperHost = getHyperHost(_serviceContext, cmd); assert(hyperHost instanceof HostMO); HostFirewallSystemMO firewallMo = ((HostMO)hyperHost).getHostFirewallSystemMO(); boolean bRefresh = false; if(firewallMo != null) { HostFirewallInfo firewallInfo = firewallMo.getFirewallInfo(); if(firewallInfo != null && firewallInfo.getRuleset() != null) { for(HostFirewallRuleset rule : firewallInfo.getRuleset()) { if("vncServer".equalsIgnoreCase(rule.getKey())) { bRefresh = true; firewallMo.enableRuleset("vncServer"); } else if("gdbserver".equalsIgnoreCase(rule.getKey())) { bRefresh = true; firewallMo.enableRuleset("gdbserver"); } } } if(bRefresh) firewallMo.refreshFirewall(); } } catch (Exception e) { s_logger.error("Unable to connect to vSphere server: " + _vCenterAddress, e); throw new CloudRuntimeException("Unable to connect to vSphere server: " + _vCenterAddress); } } return _serviceContext; } @Override public synchronized void invalidateServiceContext(VmwareContext context) { if (_serviceContext != null) { _serviceContext.close(); } _serviceContext = null; } @Override public VmwareHypervisorHost getHyperHost(VmwareContext context, Command cmd) { if (_morHyperHost.getType().equalsIgnoreCase("HostSystem")) { return new HostMO(context, _morHyperHost); } return new ClusterMO(context, _morHyperHost); } @Override @DB public String getWorkerName(VmwareContext context, Command cmd, int workerSequence) { VmwareManager mgr = context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); String vmName = mgr.composeWorkerName(); assert(cmd != null); context.getStockObject(VmwareManager.CONTEXT_STOCK_NAME); // TODO: Fix this? long checkPointId = vmwareMgr.pushCleanupCheckpoint(this._guid, vmName); // TODO: Fix this? cmd.setContextParam("checkpoint", String.valueOf(checkPointId)); return vmName; } @Override public void setName(String name) { // TODO Auto-generated method stub } @Override public void setConfigParams(Map<String, Object> params) { // TODO Auto-generated method stub } @Override public Map<String, Object> getConfigParams() { // TODO Auto-generated method stub return null; } @Override public int getRunLevel() { // TODO Auto-generated method stub return 0; } @Override public void setRunLevel(int level) { // TODO Auto-generated method stub } @Override public Answer execute(DestroyCommand cmd) { // TODO Auto-generated method stub return null; } private boolean isVMWareToolsInstalled(VirtualMachineMO vmMo) throws Exception{ GuestInfo guestInfo = vmMo.getVmGuestInfo(); return (guestInfo != null && guestInfo.getGuestState() != null && guestInfo.getGuestState().equalsIgnoreCase("running")); } }
CLOUDSTACK-2933 Added vpc load balancing changes for vmware
plugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java
CLOUDSTACK-2933 Added vpc load balancing changes for vmware
<ide><path>lugins/hypervisors/vmware/src/com/cloud/hypervisor/vmware/resource/VmwareResource.java <ide> return new SetStaticNatRulesAnswer(cmd, results, endResult); <ide> } <ide> <add> protected Answer VPCLoadBalancerConfig(final LoadBalancerConfigCommand cmd) { <add> VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); <add> File keyFile = mgr.getSystemVMKeyFile(); <add> <add> String routerIp = cmd.getAccessDetail(NetworkElementCommand.ROUTER_IP); <add> String controlIp = getRouterSshControlIp(cmd); <add> <add> assert(controlIp != null); <add> <add> LoadBalancerConfigurator cfgtr = new HAProxyConfigurator(); <add> String[] config = cfgtr.generateConfiguration(cmd); <add> <add> String tmpCfgFilePath = "/etc/haproxy/haproxy.cfg.new"; <add> String tmpCfgFileContents = ""; <add> for (int i = 0; i < config.length; i++) { <add> tmpCfgFileContents += config[i]; <add> tmpCfgFileContents += "\n"; <add> } <add> <add> try { <add> SshHelper.scpTo(controlIp, DEFAULT_DOMR_SSHPORT, "root", keyFile, null, "/etc/haproxy/", tmpCfgFileContents.getBytes(), "haproxy.cfg.new", null); <add> <add> try { <add> String[][] rules = cfgtr.generateFwRules(cmd); <add> <add> String[] addRules = rules[LoadBalancerConfigurator.ADD]; <add> String[] removeRules = rules[LoadBalancerConfigurator.REMOVE]; <add> String[] statRules = rules[LoadBalancerConfigurator.STATS]; <add> <add> String args = ""; <add> String ip = cmd.getNic().getIp(); <add> args += " -i " + ip; <add> StringBuilder sb = new StringBuilder(); <add> if (addRules.length > 0) { <add> for (int i = 0; i < addRules.length; i++) { <add> sb.append(addRules[i]).append(','); <add> } <add> <add> args += " -a " + sb.toString(); <add> } <add> <add> sb = new StringBuilder(); <add> if (removeRules.length > 0) { <add> for (int i = 0; i < removeRules.length; i++) { <add> sb.append(removeRules[i]).append(','); <add> } <add> <add> args += " -d " + sb.toString(); <add> } <add> <add> sb = new StringBuilder(); <add> if (statRules.length > 0) { <add> for (int i = 0; i < statRules.length; i++) { <add> sb.append(statRules[i]).append(','); <add> } <add> <add> args += " -s " + sb.toString(); <add> } <add> <add> // Invoke the command <add> Pair<Boolean, String> result = SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "/opt/cloud/bin/vpc_loadbalancer.sh " + args); <add> <add> if (!result.first()) { <add> String msg = "LoadBalancerConfigCommand on domain router " + routerIp + " failed. message: " + result.second(); <add> s_logger.error(msg); <add> <add> return new Answer(cmd, false, msg); <add> } <add> <add> if (s_logger.isInfoEnabled()) { <add> s_logger.info("VPCLoadBalancerConfigCommand on domain router " + routerIp + " completed"); <add> } <add> } finally { <add> SshHelper.sshExecute(controlIp, DEFAULT_DOMR_SSHPORT, "root", mgr.getSystemVMKeyFile(), null, "rm " + tmpCfgFilePath); <add> } <add> return new Answer(cmd); <add> } catch (Throwable e) { <add> s_logger.error("Unexpected exception: " + e.toString(), e); <add> return new Answer(cmd, false, "VPCLoadBalancerConfigCommand failed due to " + VmwareHelper.getExceptionMessage(e)); <add> } <add> <add> <add> } <add> <add> <ide> protected Answer execute(final LoadBalancerConfigCommand cmd) { <add> <add> if ( cmd.getVpcId() != null ) { <add> return VPCLoadBalancerConfig(cmd); <add> } <add> <ide> VmwareManager mgr = getServiceContext().getStockObject(VmwareManager.CONTEXT_STOCK_NAME); <ide> File keyFile = mgr.getSystemVMKeyFile(); <ide>
Java
apache-2.0
f65b50789d460927206eadd290dcc771ecd38d1b
0
jeorme/OG-Platform,jeorme/OG-Platform,jeorme/OG-Platform,McLeodMoores/starling,nssales/OG-Platform,DevStreet/FinanceAnalytics,McLeodMoores/starling,codeaudit/OG-Platform,DevStreet/FinanceAnalytics,ChinaQuants/OG-Platform,jeorme/OG-Platform,nssales/OG-Platform,ChinaQuants/OG-Platform,jerome79/OG-Platform,codeaudit/OG-Platform,codeaudit/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,codeaudit/OG-Platform,ChinaQuants/OG-Platform,McLeodMoores/starling,jerome79/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics,jerome79/OG-Platform,ChinaQuants/OG-Platform,nssales/OG-Platform,DevStreet/FinanceAnalytics
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.riskfactors; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.NotImplementedException; import com.google.common.collect.ImmutableSet; import com.opengamma.core.position.Portfolio; import com.opengamma.core.position.PortfolioNode; import com.opengamma.core.position.Position; import com.opengamma.core.position.impl.AbstractPortfolioNodeTraversalCallback; import com.opengamma.core.position.impl.PortfolioNodeTraverser; import com.opengamma.core.security.SecuritySource; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.view.ViewCalculationConfiguration; import com.opengamma.financial.analytics.FilteringSummingFunction; import com.opengamma.financial.analytics.conversion.SwapSecurityUtils; import com.opengamma.financial.analytics.fixedincome.InterestRateInstrumentType; import com.opengamma.financial.analytics.ircurve.YieldCurveFunction; import com.opengamma.financial.security.FinancialSecurity; import com.opengamma.financial.security.FinancialSecurityVisitor; import com.opengamma.financial.security.bond.BondSecurity; import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity; import com.opengamma.financial.security.capfloor.CapFloorSecurity; import com.opengamma.financial.security.cash.CashSecurity; import com.opengamma.financial.security.equity.EquitySecurity; import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity; import com.opengamma.financial.security.fra.FRASecurity; import com.opengamma.financial.security.future.AgricultureFutureSecurity; import com.opengamma.financial.security.future.BondFutureSecurity; import com.opengamma.financial.security.future.EnergyFutureSecurity; import com.opengamma.financial.security.future.EquityFutureSecurity; import com.opengamma.financial.security.future.EquityIndexDividendFutureSecurity; import com.opengamma.financial.security.future.FXFutureSecurity; import com.opengamma.financial.security.future.FutureSecurity; import com.opengamma.financial.security.future.FutureSecurityVisitor; import com.opengamma.financial.security.future.IndexFutureSecurity; import com.opengamma.financial.security.future.InterestRateFutureSecurity; import com.opengamma.financial.security.future.MetalFutureSecurity; import com.opengamma.financial.security.future.StockFutureSecurity; import com.opengamma.financial.security.fx.FXForwardSecurity; import com.opengamma.financial.security.fx.FXSecurity; import com.opengamma.financial.security.fx.NonDeliverableFXForwardSecurity; import com.opengamma.financial.security.option.EquityBarrierOptionSecurity; import com.opengamma.financial.security.option.EquityIndexOptionSecurity; import com.opengamma.financial.security.option.EquityOptionSecurity; import com.opengamma.financial.security.option.FXBarrierOptionSecurity; import com.opengamma.financial.security.option.FXOptionSecurity; import com.opengamma.financial.security.option.IRFutureOptionSecurity; import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity; import com.opengamma.financial.security.option.SwaptionSecurity; import com.opengamma.financial.security.swap.InterestRateNotional; import com.opengamma.financial.security.swap.Notional; import com.opengamma.financial.security.swap.SwapSecurity; import com.opengamma.id.ExternalIdBundle; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; import com.opengamma.util.tuple.Pair; /** * Default implementation of {@link RiskFactorsGatherer}. */ public class DefaultRiskFactorsGatherer implements RiskFactorsGatherer, FinancialSecurityVisitor<Set<Pair<String, ValueProperties>>>, FutureSecurityVisitor<Set<Pair<String, ValueProperties>>> { private final SecuritySource _securities; private final RiskFactorsConfigurationProvider _configProvider; public DefaultRiskFactorsGatherer(SecuritySource securities, RiskFactorsConfigurationProvider configProvider) { ArgumentChecker.notNull(securities, "securities"); ArgumentChecker.notNull(configProvider, "configProvider"); _securities = securities; _configProvider = configProvider; } @Override public Set<ValueRequirement> getPositionRiskFactors(Position position) { ArgumentChecker.notNull(position, "position"); Set<Pair<String, ValueProperties>> securityRiskFactors = ((FinancialSecurity) position.getSecurity()).accept(this); if (securityRiskFactors.isEmpty()) { return ImmutableSet.of(); } Set<ValueRequirement> results = new HashSet<ValueRequirement>(securityRiskFactors.size()); for (Pair<String, ValueProperties> securityRiskFactor : securityRiskFactors) { results.add(getValueRequirement(position, securityRiskFactor.getFirst(), securityRiskFactor.getSecond())); } return results; } @Override public Set<ValueRequirement> getPositionRiskFactors(Portfolio portfolio) { ArgumentChecker.notNull(portfolio, "portfolio"); RiskFactorPortfolioTraverser callback = new RiskFactorPortfolioTraverser(); callback.traverse(portfolio.getRootNode()); return callback.getRiskFactors(); } @Override public void addPortfolioRiskFactors(Portfolio portfolio, ViewCalculationConfiguration calcConfig) { ArgumentChecker.notNull(portfolio, "portfolio"); ArgumentChecker.notNull(calcConfig, "calcConfig"); RiskFactorPortfolioTraverser callback = new RiskFactorPortfolioTraverser(calcConfig); callback.traverse(portfolio.getRootNode()); } //------------------------------------------------------------------------- private class RiskFactorPortfolioTraverser extends AbstractPortfolioNodeTraversalCallback { private final ViewCalculationConfiguration _calcConfig; private final Set<ValueRequirement> _valueRequirements = new HashSet<ValueRequirement>(); public RiskFactorPortfolioTraverser() { this(null); } public RiskFactorPortfolioTraverser(ViewCalculationConfiguration calcConfig) { _calcConfig = calcConfig; } public void traverse(PortfolioNode rootNode) { PortfolioNodeTraverser.depthFirst(this).traverse(rootNode); } public Set<ValueRequirement> getRiskFactors() { return new HashSet<ValueRequirement>(_valueRequirements); } @Override public void preOrderOperation(PortfolioNode portfolioNode) { } @Override public void preOrderOperation(Position position) { Set<ValueRequirement> riskFactorRequirements = DefaultRiskFactorsGatherer.this.getPositionRiskFactors(position); _valueRequirements.addAll(riskFactorRequirements); if (_calcConfig != null) { for (ValueRequirement riskFactorRequirement : riskFactorRequirements) { _calcConfig.addPortfolioRequirement(position.getSecurity().getSecurityType(), riskFactorRequirement.getValueName(), riskFactorRequirement.getConstraints()); } } } @Override public void postOrderOperation(Position position) { } @Override public void postOrderOperation(PortfolioNode portfolioNode) { } } //------------------------------------------------------------------------- // Securities @Override public Set<Pair<String, ValueProperties>> visitBondSecurity(BondSecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()), getPresentValue(ValueProperties.builder()), getPV01(getFundingCurve()), getPV01(getForwardCurve(security.getCurrency()))); } @Override public Set<Pair<String, ValueProperties>> visitCashSecurity(CashSecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()), getPresentValue(ValueProperties.builder()), getPV01(getFundingCurve()), getPV01(getForwardCurve(security.getCurrency()))); } @Override public Set<Pair<String, ValueProperties>> visitEquitySecurity(EquitySecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitFRASecurity(FRASecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()), getPresentValue(ValueProperties.builder()), getPV01(getFundingCurve()), getPV01(getForwardCurve(security.getCurrency()))); } @Override public Set<Pair<String, ValueProperties>> visitFutureSecurity(FutureSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getPresentValue(ValueProperties.builder())) .add(getPV01(getFundingCurve())) .add(getPV01(getForwardCurve(security.getCurrency()))) .addAll(security.accept((FutureSecurityVisitor<Set<Pair<String, ValueProperties>>>) this)).build(); } @Override public Set<Pair<String, ValueProperties>> visitSwapSecurity(SwapSecurity security) { ImmutableSet.Builder<Pair<String, ValueProperties>> builder = ImmutableSet.<Pair<String, ValueProperties>>builder(); // At the moment pay and receive must be the same currency, so any one of them is sufficient Notional payNotional = security.getPayLeg().getNotional(); Notional receiveNotional = security.getReceiveLeg().getNotional(); if (payNotional instanceof InterestRateNotional && receiveNotional instanceof InterestRateNotional) { Currency ccy = ((InterestRateNotional) payNotional).getCurrency(); builder.add(getYieldCurveNodeSensitivities(getFundingCurve(), ccy)); builder.add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy)); builder.add(getPV01(getFundingCurve())); builder.add(getPV01(getForwardCurve(ccy))); final InterestRateInstrumentType type = SwapSecurityUtils.getSwapType(security); if (type == InterestRateInstrumentType.SWAP_CMS_CMS || type == InterestRateInstrumentType.SWAP_FIXED_CMS || type == InterestRateInstrumentType.SWAP_IBOR_CMS) { builder.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))); } } builder.add(getPresentValue(ValueProperties.builder())); return builder.build(); } @Override public Set<Pair<String, ValueProperties>> visitEquityIndexOptionSecurity(EquityIndexOptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .addAll(getSabrSensitivities()) .add(getPresentValue(ValueProperties.builder())).build(); } @Override public Set<Pair<String, ValueProperties>> visitEquityOptionSecurity(EquityOptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .addAll(getSabrSensitivities()) .add(getPresentValue(ValueProperties.builder())) .add(getVegaMatrix(ValueProperties.builder())).build(); } @Override public Set<Pair<String, ValueProperties>> visitEquityBarrierOptionSecurity(EquityBarrierOptionSecurity security) { throw new NotImplementedException(); } @Override public Set<Pair<String, ValueProperties>> visitFXOptionSecurity(FXOptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getFXPresentValue()) .add(getFXCurrencyExposure()) .add(getVegaMatrix(ValueProperties .with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded .with(ValuePropertyNames.PAY_CURVE, getFundingCurve()) .with(ValuePropertyNames.RECEIVE_CURVE, getFundingCurve()))) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency())) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build(); } @Override public Set<Pair<String, ValueProperties>> visitNonDeliverableFXOptionSecurity(NonDeliverableFXOptionSecurity security) { throw new NotImplementedException(); } @Override public Set<Pair<String, ValueProperties>> visitSwaptionSecurity(SwaptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) .addAll(getSabrSensitivities()) .add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "DEFAULT"))) .add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build(); } @Override public Set<Pair<String, ValueProperties>> visitIRFutureOptionSecurity(IRFutureOptionSecurity security) { Currency ccy = security.getCurrency(); return ImmutableSet.<Pair<String, ValueProperties>>builder() .addAll(getSabrSensitivities()) .add(getYieldCurveNodeSensitivities(getFundingCurve(), ccy)) .add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy)) .add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))) .add(getVegaMatrix(ValueProperties .with(ValuePropertyNames.SURFACE, "DEFAULT") .with(YieldCurveFunction.PROPERTY_FUNDING_CURVE, getFundingCurve()) .with(YieldCurveFunction.PROPERTY_FORWARD_CURVE, getForwardCurve(ccy)))).build(); } @Override public Set<Pair<String, ValueProperties>> visitFXBarrierOptionSecurity(FXBarrierOptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getFXPresentValue()) .add(getFXCurrencyExposure()) .add(getVegaMatrix(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency())) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build(); } @Override public Set<Pair<String, ValueProperties>> visitFXSecurity(FXSecurity security) { return ImmutableSet.of( getFXPresentValue(), getFXCurrencyExposure(), getYieldCurveNodeSensitivities(getFundingCurve(), security.getPayCurrency()), getYieldCurveNodeSensitivities(getFundingCurve(), security.getReceiveCurrency())); } @Override public Set<Pair<String, ValueProperties>> visitFXForwardSecurity(FXForwardSecurity security) { FXSecurity underlying = (FXSecurity) getSecuritySource().getSecurity(ExternalIdBundle.of(security.getUnderlyingId())); return ImmutableSet.of( getFXPresentValue(), getFXCurrencyExposure(), getYieldCurveNodeSensitivities(getFundingCurve(), underlying.getPayCurrency()), getYieldCurveNodeSensitivities(getFundingCurve(), underlying.getReceiveCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(underlying.getPayCurrency()), underlying.getPayCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(underlying.getReceiveCurrency()), underlying.getReceiveCurrency())); } @Override public Set<Pair<String, ValueProperties>> visitNonDeliverableFXForwardSecurity( NonDeliverableFXForwardSecurity security) { throw new NotImplementedException(); } @Override public Set<Pair<String, ValueProperties>> visitCapFloorSecurity(CapFloorSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) .addAll(getSabrSensitivities()) .add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))) .add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build(); } @Override public Set<Pair<String, ValueProperties>> visitCapFloorCMSSpreadSecurity(CapFloorCMSSpreadSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) .addAll(getSabrSensitivities()) .add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))) .add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build(); } @Override public Set<Pair<String, ValueProperties>> visitEquityVarianceSwapSecurity(EquityVarianceSwapSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getPresentValue(ValueProperties.builder())) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) .add(getVegaMatrix(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))).build(); } //------------------------------------------------------------------------- // Futures @Override public Set<Pair<String, ValueProperties>> visitAgricultureFutureSecurity(AgricultureFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitBondFutureSecurity(BondFutureSecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())); } @Override public Set<Pair<String, ValueProperties>> visitEnergyFutureSecurity(EnergyFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitFXFutureSecurity(FXFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitIndexFutureSecurity(IndexFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitInterestRateFutureSecurity(InterestRateFutureSecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()), getPresentValue(ValueProperties.builder()), getPV01(getFundingCurve()), getPV01(getForwardCurve(security.getCurrency()))); } @Override public Set<Pair<String, ValueProperties>> visitMetalFutureSecurity(MetalFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitStockFutureSecurity(StockFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitEquityFutureSecurity(EquityFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitEquityIndexDividendFutureSecurity(EquityIndexDividendFutureSecurity security) { return ImmutableSet.of(); } //------------------------------------------------------------------------- private Pair<String, ValueProperties> getYieldCurveNodeSensitivities(String curve, Currency currency) { ValueProperties.Builder constraints = ValueProperties .with(ValuePropertyNames.CURVE_CURRENCY, currency.getCode()) .with(ValuePropertyNames.CURVE, curve) .with(ValuePropertyNames.AGGREGATION, FilteringSummingFunction.AGGREGATION_STYLE_FILTERED) .withOptional(ValuePropertyNames.AGGREGATION); return getRiskFactor(ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES, constraints); } private Pair<String, ValueProperties> getPresentValue(ValueProperties.Builder constraints) { return getRiskFactor(ValueRequirementNames.PRESENT_VALUE, constraints); } private Pair<String, ValueProperties> getFXPresentValue() { return getRiskFactor(ValueRequirementNames.FX_PRESENT_VALUE); } private Pair<String, ValueProperties> getFXCurrencyExposure() { return getRiskFactor(ValueRequirementNames.FX_CURRENCY_EXPOSURE, false); } private Pair<String, ValueProperties> getVegaMatrix(ValueProperties.Builder constraints) { return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_MATRIX, constraints, false); } private Pair<String, ValueProperties> getVegaCubeMatrix(ValueProperties.Builder constraints) { return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_CUBE, constraints, false); } private Pair<String, ValueProperties> getPV01(String curveName) { ValueProperties.Builder constraints = ValueProperties .with(ValuePropertyNames.CURVE, curveName); return getRiskFactor(ValueRequirementNames.PV01, constraints, true); } private Set<Pair<String, ValueProperties>> getSabrSensitivities() { return ImmutableSet.of( getPresentValueSabrAlphaSensitivity(), getPresentValueSabrRhoSensitivity(), getPresentValueSabrNuSensitivity()); } private Pair<String, ValueProperties> getPresentValueSabrAlphaSensitivity() { return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_ALPHA_SENSITIVITY); } private Pair<String, ValueProperties> getPresentValueSabrRhoSensitivity() { return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_RHO_SENSITIVITY); } private Pair<String, ValueProperties> getPresentValueSabrNuSensitivity() { return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_NU_SENSITIVITY); } //------------------------------------------------------------------------- private Pair<String, ValueProperties> getRiskFactor(String valueName) { return getRiskFactor(valueName, ValueProperties.builder(), true); } private Pair<String, ValueProperties> getRiskFactor(String valueName, boolean allowCurrencyOverride) { return getRiskFactor(valueName, ValueProperties.builder(), allowCurrencyOverride); } private Pair<String, ValueProperties> getRiskFactor(String valueName, ValueProperties.Builder constraints) { return getRiskFactor(valueName, constraints, true); } private Pair<String, ValueProperties> getRiskFactor(String valueName, ValueProperties.Builder constraints, boolean allowCurrencyOverride) { ArgumentChecker.notNull(valueName, "valueName"); ArgumentChecker.notNull(constraints, "constraints"); if (allowCurrencyOverride && getConfigProvider().getCurrencyOverride() != null) { constraints.with(ValuePropertyNames.CURRENCY, getConfigProvider().getCurrencyOverride().getCode()); } return Pair.of(valueName, constraints.get()); } private ValueRequirement getValueRequirement(Position position, String valueName, ValueProperties constraints) { return new ValueRequirement(valueName, new ComputationTargetSpecification(position), constraints); } //------------------------------------------------------------------------- private String getFundingCurve() { return getConfigProvider().getFundingCurve(); } private String getForwardCurve(Currency currency) { return getConfigProvider().getForwardCurve(currency); } //------------------------------------------------------------------------- private SecuritySource getSecuritySource() { return _securities; } private RiskFactorsConfigurationProvider getConfigProvider() { return _configProvider; } }
projects/OG-Financial/src/com/opengamma/financial/analytics/riskfactors/DefaultRiskFactorsGatherer.java
/** * Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.financial.analytics.riskfactors; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang.NotImplementedException; import com.google.common.collect.ImmutableSet; import com.opengamma.core.position.Portfolio; import com.opengamma.core.position.PortfolioNode; import com.opengamma.core.position.Position; import com.opengamma.core.position.impl.AbstractPortfolioNodeTraversalCallback; import com.opengamma.core.position.impl.PortfolioNodeTraverser; import com.opengamma.core.security.SecuritySource; import com.opengamma.engine.ComputationTargetSpecification; import com.opengamma.engine.value.ValueProperties; import com.opengamma.engine.value.ValuePropertyNames; import com.opengamma.engine.value.ValueRequirement; import com.opengamma.engine.value.ValueRequirementNames; import com.opengamma.engine.view.ViewCalculationConfiguration; import com.opengamma.financial.analytics.FilteringSummingFunction; import com.opengamma.financial.analytics.ircurve.YieldCurveFunction; import com.opengamma.financial.security.FinancialSecurity; import com.opengamma.financial.security.FinancialSecurityVisitor; import com.opengamma.financial.security.bond.BondSecurity; import com.opengamma.financial.security.capfloor.CapFloorCMSSpreadSecurity; import com.opengamma.financial.security.capfloor.CapFloorSecurity; import com.opengamma.financial.security.cash.CashSecurity; import com.opengamma.financial.security.equity.EquitySecurity; import com.opengamma.financial.security.equity.EquityVarianceSwapSecurity; import com.opengamma.financial.security.fra.FRASecurity; import com.opengamma.financial.security.future.AgricultureFutureSecurity; import com.opengamma.financial.security.future.BondFutureSecurity; import com.opengamma.financial.security.future.EnergyFutureSecurity; import com.opengamma.financial.security.future.EquityFutureSecurity; import com.opengamma.financial.security.future.EquityIndexDividendFutureSecurity; import com.opengamma.financial.security.future.FXFutureSecurity; import com.opengamma.financial.security.future.FutureSecurity; import com.opengamma.financial.security.future.FutureSecurityVisitor; import com.opengamma.financial.security.future.IndexFutureSecurity; import com.opengamma.financial.security.future.InterestRateFutureSecurity; import com.opengamma.financial.security.future.MetalFutureSecurity; import com.opengamma.financial.security.future.StockFutureSecurity; import com.opengamma.financial.security.fx.FXForwardSecurity; import com.opengamma.financial.security.fx.FXSecurity; import com.opengamma.financial.security.fx.NonDeliverableFXForwardSecurity; import com.opengamma.financial.security.option.EquityBarrierOptionSecurity; import com.opengamma.financial.security.option.EquityIndexOptionSecurity; import com.opengamma.financial.security.option.EquityOptionSecurity; import com.opengamma.financial.security.option.FXBarrierOptionSecurity; import com.opengamma.financial.security.option.FXOptionSecurity; import com.opengamma.financial.security.option.IRFutureOptionSecurity; import com.opengamma.financial.security.option.NonDeliverableFXOptionSecurity; import com.opengamma.financial.security.option.SwaptionSecurity; import com.opengamma.financial.security.swap.InterestRateNotional; import com.opengamma.financial.security.swap.Notional; import com.opengamma.financial.security.swap.SwapSecurity; import com.opengamma.id.ExternalIdBundle; import com.opengamma.util.ArgumentChecker; import com.opengamma.util.money.Currency; import com.opengamma.util.tuple.Pair; /** * Default implementation of {@link RiskFactorsGatherer}. */ public class DefaultRiskFactorsGatherer implements RiskFactorsGatherer, FinancialSecurityVisitor<Set<Pair<String, ValueProperties>>>, FutureSecurityVisitor<Set<Pair<String, ValueProperties>>> { private final SecuritySource _securities; private final RiskFactorsConfigurationProvider _configProvider; public DefaultRiskFactorsGatherer(SecuritySource securities, RiskFactorsConfigurationProvider configProvider) { ArgumentChecker.notNull(securities, "securities"); ArgumentChecker.notNull(configProvider, "configProvider"); _securities = securities; _configProvider = configProvider; } @Override public Set<ValueRequirement> getPositionRiskFactors(Position position) { ArgumentChecker.notNull(position, "position"); Set<Pair<String, ValueProperties>> securityRiskFactors = ((FinancialSecurity) position.getSecurity()).accept(this); if (securityRiskFactors.isEmpty()) { return ImmutableSet.of(); } Set<ValueRequirement> results = new HashSet<ValueRequirement>(securityRiskFactors.size()); for (Pair<String, ValueProperties> securityRiskFactor : securityRiskFactors) { results.add(getValueRequirement(position, securityRiskFactor.getFirst(), securityRiskFactor.getSecond())); } return results; } @Override public Set<ValueRequirement> getPositionRiskFactors(Portfolio portfolio) { ArgumentChecker.notNull(portfolio, "portfolio"); RiskFactorPortfolioTraverser callback = new RiskFactorPortfolioTraverser(); callback.traverse(portfolio.getRootNode()); return callback.getRiskFactors(); } @Override public void addPortfolioRiskFactors(Portfolio portfolio, ViewCalculationConfiguration calcConfig) { ArgumentChecker.notNull(portfolio, "portfolio"); ArgumentChecker.notNull(calcConfig, "calcConfig"); RiskFactorPortfolioTraverser callback = new RiskFactorPortfolioTraverser(calcConfig); callback.traverse(portfolio.getRootNode()); } //------------------------------------------------------------------------- private class RiskFactorPortfolioTraverser extends AbstractPortfolioNodeTraversalCallback { private final ViewCalculationConfiguration _calcConfig; private final Set<ValueRequirement> _valueRequirements = new HashSet<ValueRequirement>(); public RiskFactorPortfolioTraverser() { this(null); } public RiskFactorPortfolioTraverser(ViewCalculationConfiguration calcConfig) { _calcConfig = calcConfig; } public void traverse(PortfolioNode rootNode) { PortfolioNodeTraverser.depthFirst(this).traverse(rootNode); } public Set<ValueRequirement> getRiskFactors() { return new HashSet<ValueRequirement>(_valueRequirements); } @Override public void preOrderOperation(PortfolioNode portfolioNode) { } @Override public void preOrderOperation(Position position) { Set<ValueRequirement> riskFactorRequirements = DefaultRiskFactorsGatherer.this.getPositionRiskFactors(position); _valueRequirements.addAll(riskFactorRequirements); if (_calcConfig != null) { for (ValueRequirement riskFactorRequirement : riskFactorRequirements) { _calcConfig.addPortfolioRequirement(position.getSecurity().getSecurityType(), riskFactorRequirement.getValueName(), riskFactorRequirement.getConstraints()); } } } @Override public void postOrderOperation(Position position) { } @Override public void postOrderOperation(PortfolioNode portfolioNode) { } } //------------------------------------------------------------------------- // Securities @Override public Set<Pair<String, ValueProperties>> visitBondSecurity(BondSecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()), getPresentValue(ValueProperties.builder()), getPV01(getFundingCurve()), getPV01(getForwardCurve(security.getCurrency()))); } @Override public Set<Pair<String, ValueProperties>> visitCashSecurity(CashSecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()), getPresentValue(ValueProperties.builder()), getPV01(getFundingCurve()), getPV01(getForwardCurve(security.getCurrency()))); } @Override public Set<Pair<String, ValueProperties>> visitEquitySecurity(EquitySecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitFRASecurity(FRASecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()), getPresentValue(ValueProperties.builder()), getPV01(getFundingCurve()), getPV01(getForwardCurve(security.getCurrency()))); } @Override public Set<Pair<String, ValueProperties>> visitFutureSecurity(FutureSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getPresentValue(ValueProperties.builder())) .add(getPV01(getFundingCurve())) .add(getPV01(getForwardCurve(security.getCurrency()))) .addAll(security.accept((FutureSecurityVisitor<Set<Pair<String, ValueProperties>>>) this)).build(); } @Override public Set<Pair<String, ValueProperties>> visitSwapSecurity(SwapSecurity security) { ImmutableSet.Builder<Pair<String, ValueProperties>> builder = ImmutableSet.<Pair<String, ValueProperties>>builder(); // At the moment pay and receive must be the same currency, so any one of them is sufficient Notional payNotional = security.getPayLeg().getNotional(); Notional receiveNotional = security.getReceiveLeg().getNotional(); if (payNotional instanceof InterestRateNotional && receiveNotional instanceof InterestRateNotional) { Currency ccy = ((InterestRateNotional) payNotional).getCurrency(); builder.add(getYieldCurveNodeSensitivities(getFundingCurve(), ccy)); builder.add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy)); builder.add(getPV01(getFundingCurve())); builder.add(getPV01(getForwardCurve(ccy))); } builder.add(getPresentValue(ValueProperties.builder())); return builder.build(); } @Override public Set<Pair<String, ValueProperties>> visitEquityIndexOptionSecurity(EquityIndexOptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .addAll(getSabrSensitivities()) .add(getPresentValue(ValueProperties.builder())).build(); } @Override public Set<Pair<String, ValueProperties>> visitEquityOptionSecurity(EquityOptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .addAll(getSabrSensitivities()) .add(getPresentValue(ValueProperties.builder())) .add(getVegaMatrix(ValueProperties.builder())).build(); } @Override public Set<Pair<String, ValueProperties>> visitEquityBarrierOptionSecurity(EquityBarrierOptionSecurity security) { throw new NotImplementedException(); } @Override public Set<Pair<String, ValueProperties>> visitFXOptionSecurity(FXOptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getFXPresentValue()) .add(getFXCurrencyExposure()) .add(getVegaMatrix(ValueProperties .with(ValuePropertyNames.SURFACE, "DEFAULT") //TODO this should not be hard-coded .with(ValuePropertyNames.PAY_CURVE, getFundingCurve()) .with(ValuePropertyNames.RECEIVE_CURVE, getFundingCurve()))) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency())) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build(); } @Override public Set<Pair<String, ValueProperties>> visitNonDeliverableFXOptionSecurity(NonDeliverableFXOptionSecurity security) { throw new NotImplementedException(); } @Override public Set<Pair<String, ValueProperties>> visitSwaptionSecurity(SwaptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) .addAll(getSabrSensitivities()) .add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))) /*.add(getVegaMatrix(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT")))*/.build(); } @Override public Set<Pair<String, ValueProperties>> visitIRFutureOptionSecurity(IRFutureOptionSecurity security) { Currency ccy = security.getCurrency(); return ImmutableSet.<Pair<String, ValueProperties>>builder() .addAll(getSabrSensitivities()) .add(getYieldCurveNodeSensitivities(getFundingCurve(), ccy)) .add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy)) .add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))) .add(getVegaMatrix(ValueProperties .with(ValuePropertyNames.SURFACE, "DEFAULT") .with(YieldCurveFunction.PROPERTY_FUNDING_CURVE, getFundingCurve()) .with(YieldCurveFunction.PROPERTY_FORWARD_CURVE, getForwardCurve(ccy)))).build(); } @Override public Set<Pair<String, ValueProperties>> visitFXBarrierOptionSecurity(FXBarrierOptionSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getFXPresentValue()) .add(getFXCurrencyExposure()) .add(getVegaMatrix(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCallCurrency())) .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getPutCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCallCurrency()), security.getCallCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getPutCurrency()), security.getPutCurrency())).build(); } @Override public Set<Pair<String, ValueProperties>> visitFXSecurity(FXSecurity security) { return ImmutableSet.of( getFXPresentValue(), getFXCurrencyExposure(), getYieldCurveNodeSensitivities(getFundingCurve(), security.getPayCurrency()), getYieldCurveNodeSensitivities(getFundingCurve(), security.getReceiveCurrency())); } @Override public Set<Pair<String, ValueProperties>> visitFXForwardSecurity(FXForwardSecurity security) { FXSecurity underlying = (FXSecurity) getSecuritySource().getSecurity(ExternalIdBundle.of(security.getUnderlyingId())); return ImmutableSet.of( getFXPresentValue(), getFXCurrencyExposure(), getYieldCurveNodeSensitivities(getFundingCurve(), underlying.getPayCurrency()), getYieldCurveNodeSensitivities(getFundingCurve(), underlying.getReceiveCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(underlying.getPayCurrency()), underlying.getPayCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(underlying.getReceiveCurrency()), underlying.getReceiveCurrency())); } @Override public Set<Pair<String, ValueProperties>> visitNonDeliverableFXForwardSecurity( NonDeliverableFXForwardSecurity security) { throw new NotImplementedException(); } @Override public Set<Pair<String, ValueProperties>> visitCapFloorSecurity(CapFloorSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) .addAll(getSabrSensitivities()) .add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))).build(); } @Override public Set<Pair<String, ValueProperties>> visitCapFloorCMSSpreadSecurity(CapFloorCMSSpreadSecurity security) { return ImmutableSet.<Pair<String, ValueProperties>>builder() .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) .addAll(getSabrSensitivities()) .add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))).build(); } @Override public Set<Pair<String, ValueProperties>> visitEquityVarianceSwapSecurity(EquityVarianceSwapSecurity security) { return ImmutableSet.of(); } //------------------------------------------------------------------------- // Futures @Override public Set<Pair<String, ValueProperties>> visitAgricultureFutureSecurity(AgricultureFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitBondFutureSecurity(BondFutureSecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())); } @Override public Set<Pair<String, ValueProperties>> visitEnergyFutureSecurity(EnergyFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitFXFutureSecurity(FXFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitIndexFutureSecurity(IndexFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitInterestRateFutureSecurity(InterestRateFutureSecurity security) { return ImmutableSet.of( getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency()), getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency()), getPresentValue(ValueProperties.builder()), getPV01(getFundingCurve()), getPV01(getForwardCurve(security.getCurrency()))); } @Override public Set<Pair<String, ValueProperties>> visitMetalFutureSecurity(MetalFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitStockFutureSecurity(StockFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitEquityFutureSecurity(EquityFutureSecurity security) { return ImmutableSet.of(); } @Override public Set<Pair<String, ValueProperties>> visitEquityIndexDividendFutureSecurity(EquityIndexDividendFutureSecurity security) { return ImmutableSet.of(); } //------------------------------------------------------------------------- private Pair<String, ValueProperties> getYieldCurveNodeSensitivities(String curve, Currency currency) { ValueProperties.Builder constraints = ValueProperties .with(ValuePropertyNames.CURVE_CURRENCY, currency.getCode()) .with(ValuePropertyNames.CURVE, curve) .with(ValuePropertyNames.AGGREGATION, FilteringSummingFunction.AGGREGATION_STYLE_FILTERED) .withOptional(ValuePropertyNames.AGGREGATION); return getRiskFactor(ValueRequirementNames.YIELD_CURVE_NODE_SENSITIVITIES, constraints); } private Pair<String, ValueProperties> getPresentValue(ValueProperties.Builder constraints) { return getRiskFactor(ValueRequirementNames.PRESENT_VALUE, constraints); } private Pair<String, ValueProperties> getFXPresentValue() { return getRiskFactor(ValueRequirementNames.FX_PRESENT_VALUE); } private Pair<String, ValueProperties> getFXCurrencyExposure() { return getRiskFactor(ValueRequirementNames.FX_CURRENCY_EXPOSURE, false); } private Pair<String, ValueProperties> getVegaMatrix(ValueProperties.Builder constraints) { return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_MATRIX, constraints, false); } private Pair<String, ValueProperties> getPV01(String curveName) { ValueProperties.Builder constraints = ValueProperties .with(ValuePropertyNames.CURVE, curveName); return getRiskFactor(ValueRequirementNames.PV01, constraints, true); } private Set<Pair<String, ValueProperties>> getSabrSensitivities() { return ImmutableSet.of( getPresentValueSabrAlphaSensitivity(), getPresentValueSabrRhoSensitivity(), getPresentValueSabrNuSensitivity()); } private Pair<String, ValueProperties> getPresentValueSabrAlphaSensitivity() { return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_ALPHA_SENSITIVITY); } private Pair<String, ValueProperties> getPresentValueSabrRhoSensitivity() { return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_RHO_SENSITIVITY); } private Pair<String, ValueProperties> getPresentValueSabrNuSensitivity() { return getRiskFactor(ValueRequirementNames.PRESENT_VALUE_SABR_NU_SENSITIVITY); } //------------------------------------------------------------------------- private Pair<String, ValueProperties> getRiskFactor(String valueName) { return getRiskFactor(valueName, ValueProperties.builder(), true); } private Pair<String, ValueProperties> getRiskFactor(String valueName, boolean allowCurrencyOverride) { return getRiskFactor(valueName, ValueProperties.builder(), allowCurrencyOverride); } private Pair<String, ValueProperties> getRiskFactor(String valueName, ValueProperties.Builder constraints) { return getRiskFactor(valueName, constraints, true); } private Pair<String, ValueProperties> getRiskFactor(String valueName, ValueProperties.Builder constraints, boolean allowCurrencyOverride) { ArgumentChecker.notNull(valueName, "valueName"); ArgumentChecker.notNull(constraints, "constraints"); if (allowCurrencyOverride && getConfigProvider().getCurrencyOverride() != null) { constraints.with(ValuePropertyNames.CURRENCY, getConfigProvider().getCurrencyOverride().getCode()); } return Pair.of(valueName, constraints.get()); } private ValueRequirement getValueRequirement(Position position, String valueName, ValueProperties constraints) { return new ValueRequirement(valueName, new ComputationTargetSpecification(position), constraints); } //------------------------------------------------------------------------- private String getFundingCurve() { return getConfigProvider().getFundingCurve(); } private String getForwardCurve(Currency currency) { return getConfigProvider().getForwardCurve(currency); } //------------------------------------------------------------------------- private SecuritySource getSecuritySource() { return _securities; } private RiskFactorsConfigurationProvider getConfigProvider() { return _configProvider; } }
Adding more results to the risk factor results gatherer
projects/OG-Financial/src/com/opengamma/financial/analytics/riskfactors/DefaultRiskFactorsGatherer.java
Adding more results to the risk factor results gatherer
<ide><path>rojects/OG-Financial/src/com/opengamma/financial/analytics/riskfactors/DefaultRiskFactorsGatherer.java <ide> import com.opengamma.engine.value.ValueRequirementNames; <ide> import com.opengamma.engine.view.ViewCalculationConfiguration; <ide> import com.opengamma.financial.analytics.FilteringSummingFunction; <add>import com.opengamma.financial.analytics.conversion.SwapSecurityUtils; <add>import com.opengamma.financial.analytics.fixedincome.InterestRateInstrumentType; <ide> import com.opengamma.financial.analytics.ircurve.YieldCurveFunction; <ide> import com.opengamma.financial.security.FinancialSecurity; <ide> import com.opengamma.financial.security.FinancialSecurityVisitor; <ide> builder.add(getYieldCurveNodeSensitivities(getForwardCurve(ccy), ccy)); <ide> builder.add(getPV01(getFundingCurve())); <ide> builder.add(getPV01(getForwardCurve(ccy))); <add> final InterestRateInstrumentType type = SwapSecurityUtils.getSwapType(security); <add> if (type == InterestRateInstrumentType.SWAP_CMS_CMS || type == InterestRateInstrumentType.SWAP_FIXED_CMS || type == InterestRateInstrumentType.SWAP_IBOR_CMS) { <add> builder.add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))); <add> } <ide> } <ide> <ide> builder.add(getPresentValue(ValueProperties.builder())); <ide> .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) <ide> .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) <ide> .addAll(getSabrSensitivities()) <del> .add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))) <del> /*.add(getVegaMatrix(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT")))*/.build(); <add> .add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "DEFAULT"))) <add> .add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build(); <ide> } <ide> <ide> @Override <ide> .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) <ide> .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) <ide> .addAll(getSabrSensitivities()) <del> .add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))).build(); <add> .add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))) <add> .add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build(); <ide> } <ide> <ide> @Override <ide> .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) <ide> .add(getYieldCurveNodeSensitivities(getForwardCurve(security.getCurrency()), security.getCurrency())) <ide> .addAll(getSabrSensitivities()) <del> .add(getPresentValue(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))).build(); <add> .add(getVegaCubeMatrix(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))) <add> .add(getPresentValue(ValueProperties.with(ValuePropertyNames.CUBE, "BLOOMBERG"))).build(); <ide> } <ide> <ide> @Override <ide> public Set<Pair<String, ValueProperties>> visitEquityVarianceSwapSecurity(EquityVarianceSwapSecurity security) { <del> return ImmutableSet.of(); <add> return ImmutableSet.<Pair<String, ValueProperties>>builder() <add> .add(getPresentValue(ValueProperties.builder())) <add> .add(getYieldCurveNodeSensitivities(getFundingCurve(), security.getCurrency())) <add> .add(getVegaMatrix(ValueProperties.with(ValuePropertyNames.SURFACE, "DEFAULT"))).build(); <ide> } <ide> <ide> //------------------------------------------------------------------------- <ide> return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_MATRIX, constraints, false); <ide> } <ide> <add> private Pair<String, ValueProperties> getVegaCubeMatrix(ValueProperties.Builder constraints) { <add> return getRiskFactor(ValueRequirementNames.VEGA_QUOTE_CUBE, constraints, false); <add> } <add> <ide> private Pair<String, ValueProperties> getPV01(String curveName) { <ide> ValueProperties.Builder constraints = ValueProperties <ide> .with(ValuePropertyNames.CURVE, curveName);
Java
apache-2.0
cc2d9057ffb3a9526641136c912551281bdf707e
0
Ralph-VX/LMBS-Editor
package kien.lmbseditor.window.motion; import java.text.DecimalFormat; import javax.swing.JCheckBox; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import kien.lmbseditor.core.motion.SkillMotionCommandBase; import kien.lmbseditor.core.motion.SkillMotionCommandRotation; import net.miginfocom.swing.MigLayout; public class MotionPropertyDialogRotation extends MotionPropertyDialogBase { private static final long serialVersionUID = 3292873801824570323L; protected JFormattedTextField rotationField; protected JFormattedTextField durationField; public int rotation; public int dir; public int dur; public int rounds; protected JCheckBox invertCheck; private JLabel lblNewLabel_1; protected JFormattedTextField roundField; /** * Create the dialog. */ public MotionPropertyDialogRotation() { setTitle("Rotation"); setBounds(100, 100, 352, 154); contentPanel.setLayout(new MigLayout("", "[][grow]", "[][]")); DecimalFormat format = new DecimalFormat("##0"); format.setMinimumFractionDigits(0); JLabel lblNewLabel = new JLabel("rotation"); lblNewLabel.setToolTipText("target angle of rotation"); contentPanel.add(lblNewLabel, "cell 0 0,alignx trailing"); rotationField = new JFormattedTextField(format); contentPanel.add(rotationField, "flowx,cell 1 0,growx"); rotationField.setColumns(10); JLabel lblNewLabel_2 = new JLabel("duration"); lblNewLabel_2.setToolTipText("Amount of time this rotation will use"); contentPanel.add(lblNewLabel_2, "cell 1 0,alignx trailing"); durationField = new JFormattedTextField(format); durationField.setToolTipText("Amount of time this rotation will use"); contentPanel.add(durationField, "cell 1 0,growx"); lblNewLabel_1 = new JLabel("rounds"); contentPanel.add(lblNewLabel_1, "cell 0 1,alignx left"); roundField = new JFormattedTextField(format); roundField.setToolTipText("Amount of rounds this rotation will do."); contentPanel.add(roundField, "flowx,cell 1 1,growx"); invertCheck = new JCheckBox("Invert Direction "); invertCheck.setToolTipText("is this rotation is counter-clockwise or not"); contentPanel.add(invertCheck, "cell 1 1"); } @Override public void setObject(SkillMotionCommandBase object) { SkillMotionCommandRotation obj = (SkillMotionCommandRotation)object; rotationField.setValue(obj.rotation); durationField.setValue(obj.dur); invertCheck.setSelected(obj.dir > 0); roundField.setValue(obj.rounds); clearDirty(); } @Override public void onOk() { rotation = ((Number)rotationField.getValue()).intValue(); dur = ((Number)durationField.getValue()).intValue(); dir = invertCheck.isSelected() ? 1 : 0; rounds = ((Number)roundField.getValue()).intValue(); this.setDirty(); this.onCancel(); } }
src/kien/lmbseditor/window/motion/MotionPropertyDialogRotation.java
package kien.lmbseditor.window.motion; import java.text.DecimalFormat; import javax.swing.JCheckBox; import javax.swing.JFormattedTextField; import javax.swing.JLabel; import kien.lmbseditor.core.motion.SkillMotionCommandBase; import kien.lmbseditor.core.motion.SkillMotionCommandRotation; import net.miginfocom.swing.MigLayout; public class MotionPropertyDialogRotation extends MotionPropertyDialogBase { private static final long serialVersionUID = 3292873801824570323L; protected JFormattedTextField rotationField; protected JFormattedTextField durationField; public int rotation; public int dir; public int dur; public int rounds; protected JCheckBox invertCheck; private JLabel lblNewLabel_1; protected JFormattedTextField roundField; /** * Create the dialog. */ public MotionPropertyDialogRotation() { setTitle("Rotation"); setBounds(100, 100, 352, 154); contentPanel.setLayout(new MigLayout("", "[][grow]", "[][]")); DecimalFormat format = new DecimalFormat("##0"); format.setMinimumFractionDigits(0); JLabel lblNewLabel = new JLabel("rotation"); lblNewLabel.setToolTipText("target angle of rotation"); contentPanel.add(lblNewLabel, "cell 0 0,alignx trailing"); rotationField = new JFormattedTextField(format); contentPanel.add(rotationField, "flowx,cell 1 0,growx"); rotationField.setColumns(10); JLabel lblNewLabel_2 = new JLabel("duration"); lblNewLabel_2.setToolTipText("Amount of time this rotation will use"); contentPanel.add(lblNewLabel_2, "cell 1 0,alignx trailing"); durationField = new JFormattedTextField(format); durationField.setToolTipText("Amount of time this rotation will use"); contentPanel.add(durationField, "cell 1 0,growx"); lblNewLabel_1 = new JLabel("rounds"); contentPanel.add(lblNewLabel_1, "cell 0 1,alignx left"); roundField = new JFormattedTextField(format); roundField.setToolTipText("Amount of rounds this rotation will do."); contentPanel.add(roundField, "flowx,cell 1 1,growx"); invertCheck = new JCheckBox("Invert Direction "); invertCheck.setToolTipText("is this rotation is counter-clockwise or not"); contentPanel.add(invertCheck, "cell 1 1"); } @Override public void setObject(SkillMotionCommandBase object) { SkillMotionCommandRotation obj = (SkillMotionCommandRotation)object; rotationField.setValue(obj.rotation); durationField.setValue(obj.dur); invertCheck.setSelected(obj.dir > 0); roundField.setValue(obj.rounds); clearDirty(); } @Override public void onOk() { rotation = ((Number)rotationField.getValue()).intValue(); dur = ((Number)durationField.getValue()).intValue(); dir = invertCheck.isSelected() ? 1 : 0; rounds = ((Number)durationField.getValue()).intValue(); this.setDirty(); this.onCancel(); } }
Fixed Round Field and Duration field was not work correct.
src/kien/lmbseditor/window/motion/MotionPropertyDialogRotation.java
Fixed Round Field and Duration field was not work correct.
<ide><path>rc/kien/lmbseditor/window/motion/MotionPropertyDialogRotation.java <ide> rotation = ((Number)rotationField.getValue()).intValue(); <ide> dur = ((Number)durationField.getValue()).intValue(); <ide> dir = invertCheck.isSelected() ? 1 : 0; <del> rounds = ((Number)durationField.getValue()).intValue(); <add> rounds = ((Number)roundField.getValue()).intValue(); <ide> this.setDirty(); <ide> this.onCancel(); <ide> }
Java
apache-2.0
ffd1988edd9eb6a0351e149cdf7ff0962fec32a8
0
BlurEngine/Blur,BlurEngine/Blur
/* * Copyright 2016 Ali Moghnieh * * 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.blurengine.blur; import com.google.common.base.Preconditions; import com.blurengine.blur.modules.framework.ModuleManager; import com.supaham.commons.bukkit.ServerShutdown; import com.supaham.commons.bukkit.ServerShutdown.ServerShutdownEvent; import com.supaham.commons.bukkit.SimpleCommonPlugin; import com.supaham.commons.bukkit.TickerTask; import com.supaham.commons.bukkit.commands.common.CommonCommands; import com.supaham.commons.bukkit.listeners.PlayerListeners; import com.supaham.commons.state.State; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; /** * Bukkit plugin class for {@link Blur}. */ public class BlurPlugin extends SimpleCommonPlugin<BlurPlugin> implements Listener { private static BlurPlugin instance; private Blur blur; private RootBlurSession rootSession; public static BlurPlugin get() { return instance; } public BlurPlugin() { Preconditions.checkState(instance == null, "BlurPlugin already initialized."); instance = this; setSettings(() -> new BlurSettings(this)); } @Override public void onEnable() { super.onEnable(); // This is important for handling immediate shutdown via commands. ServerShutdown module = new ServerShutdown(getModuleContainer()); getModuleContainer().register(module); module.setState(State.ACTIVE); PlayerListeners.defaultSpeeds(this); registerEvents(this); this.blur = new Blur(this); this.rootSession = new RootBlurSession(this.blur.getSessionManager()); ModuleManager moduleManager = this.rootSession.getModuleManager(); // Load from serialized modules, here's how the whoooole chain starts! moduleManager.getModuleLoader().load(getSettings().getModules()); if (!enableMetrics()) { getServer().getPluginManager().disablePlugin(this); return; } CommonCommands.DEBUG.builder(this, "b").register(); // Immediately load, enable and start the root session to get the wheels going. new TickerTask(this, 0, this.rootSession::start).start(); new TickerTask(this, 0, getCommandsManager()::build).start(); } // Cleanup blur during shutdown. @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onServerShutdown(ServerShutdownEvent event) { if (this.rootSession != null) { this.rootSession.stop(); } } public BlurSettings getSettings() { return (BlurSettings) super.getSettings(); } public Blur getBlur() { return blur; } public RootBlurSession getRootSession() { return rootSession; } }
src/main/java/com/blurengine/blur/BlurPlugin.java
/* * Copyright 2016 Ali Moghnieh * * 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.blurengine.blur; import com.google.common.base.Preconditions; import com.blurengine.blur.modules.framework.ModuleManager; import com.supaham.commons.bukkit.ServerShutdown; import com.supaham.commons.bukkit.ServerShutdown.ServerShutdownEvent; import com.supaham.commons.bukkit.SimpleCommonPlugin; import com.supaham.commons.bukkit.TickerTask; import com.supaham.commons.bukkit.commands.common.CommonCommands; import com.supaham.commons.state.State; import org.bukkit.event.EventHandler; import org.bukkit.event.EventPriority; import org.bukkit.event.Listener; /** * Bukkit plugin class for {@link Blur}. */ public class BlurPlugin extends SimpleCommonPlugin<BlurPlugin> implements Listener { private static BlurPlugin instance; private Blur blur; private RootBlurSession rootSession; public static BlurPlugin get() { return instance; } public BlurPlugin() { Preconditions.checkState(instance == null, "BlurPlugin already initialized."); instance = this; setSettings(() -> new BlurSettings(this)); } @Override public void onEnable() { super.onEnable(); // This is important for handling immediate shutdown via commands. ServerShutdown module = new ServerShutdown(getModuleContainer()); getModuleContainer().register(module); module.setState(State.ACTIVE); registerEvents(this); this.blur = new Blur(this); this.rootSession = new RootBlurSession(this.blur.getSessionManager()); ModuleManager moduleManager = this.rootSession.getModuleManager(); // Load from serialized modules, here's how the whoooole chain starts! moduleManager.getModuleLoader().load(getSettings().getModules()); if (!enableMetrics()) { getServer().getPluginManager().disablePlugin(this); return; } CommonCommands.DEBUG.builder(this, "b").register(); // Immediately load, enable and start the root session to get the wheels going. new TickerTask(this, 0, this.rootSession::start).start(); new TickerTask(this, 0, getCommandsManager()::build).start(); } // Cleanup blur during shutdown. @EventHandler(priority = EventPriority.MONITOR, ignoreCancelled = true) public void onServerShutdown(ServerShutdownEvent event) { if (this.rootSession != null) { this.rootSession.stop(); } } public BlurSettings getSettings() { return (BlurSettings) super.getSettings(); } public Blur getBlur() { return blur; } public RootBlurSession getRootSession() { return rootSession; } }
Use PlayerListeners#defaultSpeeds from common lib to fix restart setting player speed to 0.
src/main/java/com/blurengine/blur/BlurPlugin.java
Use PlayerListeners#defaultSpeeds from common lib to fix restart setting player speed to 0.
<ide><path>rc/main/java/com/blurengine/blur/BlurPlugin.java <ide> import com.supaham.commons.bukkit.SimpleCommonPlugin; <ide> import com.supaham.commons.bukkit.TickerTask; <ide> import com.supaham.commons.bukkit.commands.common.CommonCommands; <add>import com.supaham.commons.bukkit.listeners.PlayerListeners; <ide> import com.supaham.commons.state.State; <ide> <ide> import org.bukkit.event.EventHandler; <ide> ServerShutdown module = new ServerShutdown(getModuleContainer()); <ide> getModuleContainer().register(module); <ide> module.setState(State.ACTIVE); <add> PlayerListeners.defaultSpeeds(this); <ide> registerEvents(this); <ide> <ide> this.blur = new Blur(this);
Java
apache-2.0
bb6c3712d2affb21c47407165e3cc1540e2c4c1a
0
emre-aydin/hazelcast,tufangorel/hazelcast,mesutcelik/hazelcast,tufangorel/hazelcast,tkountis/hazelcast,mdogan/hazelcast,emrahkocaman/hazelcast,tkountis/hazelcast,Donnerbart/hazelcast,dbrimley/hazelcast,lmjacksoniii/hazelcast,mdogan/hazelcast,tufangorel/hazelcast,tombujok/hazelcast,lmjacksoniii/hazelcast,dbrimley/hazelcast,Donnerbart/hazelcast,emre-aydin/hazelcast,Donnerbart/hazelcast,tkountis/hazelcast,emrahkocaman/hazelcast,dsukhoroslov/hazelcast,mdogan/hazelcast,tombujok/hazelcast,juanavelez/hazelcast,emre-aydin/hazelcast,juanavelez/hazelcast,mesutcelik/hazelcast,mesutcelik/hazelcast,dbrimley/hazelcast,dsukhoroslov/hazelcast
/* * Copyright (c) 2008-2010, Hazel Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hazelcast.impl; import com.hazelcast.core.MapEntry; import com.hazelcast.impl.base.DistributedLock; import com.hazelcast.impl.base.ScheduledAction; import com.hazelcast.nio.Address; import com.hazelcast.nio.Data; import java.util.*; public final class Record implements MapEntry { private final CMap cmap; private final Long id; private final short blockId; private final Data key; private volatile Data value; private volatile boolean active = true; private volatile int hits = 0; private volatile long version = 0; private volatile long maxIdleMillis = Long.MAX_VALUE; private volatile long writeTime = -1; private volatile long removeTime = 0; private volatile long lastAccessTime = 0; private volatile long creationTime = 0; private volatile long expirationTime = Long.MAX_VALUE; private volatile long lastUpdateTime = 0; private volatile boolean dirty = false; private volatile int copyCount = 0; private DistributedLock lock = null; private OptionalInfo optionalInfo = null; public Record(CMap cmap, int blockId, Data key, Data value, long ttl, long maxIdleMillis, Long id) { super(); this.id = id; this.cmap = cmap; this.blockId = (short) blockId; this.key = key; this.value = value; this.setCreationTime(System.currentTimeMillis()); this.setExpirationTime(ttl); this.maxIdleMillis = (maxIdleMillis == 0) ? Long.MAX_VALUE : maxIdleMillis; this.setVersion(0); } public Record copy() { Record recordCopy = new Record(cmap, blockId, key, value, getRemainingTTL(), getRemainingIdle(), id); recordCopy.setIndexes(getOptionalInfo().indexes, getOptionalInfo().indexTypes); if (lock != null) { recordCopy.setLock(new DistributedLock(lock)); } recordCopy.setMultiValues(getOptionalInfo().lsMultiValues); recordCopy.setCopyCount(copyCount); recordCopy.setVersion(getVersion()); return recordCopy; } public RecordEntry getRecordEntry() { return cmap.getRecordEntry(this); } public CMap getCMap() { return cmap; } public void runBackupOps() { if (getBackupOps() != null) { if (getBackupOps().size() > 0) { Iterator<VersionedBackupOp> it = getBackupOps().iterator(); while (it.hasNext()) { VersionedBackupOp bo = it.next(); if (bo.getVersion() < getVersion() + 1) { it.remove(); } else if (bo.getVersion() == getVersion() + 1) { bo.run(); setVersion(bo.getVersion()); it.remove(); } else { return; } } } } } public void addBackupOp(VersionedBackupOp bo) { if (getBackupOps() == null) { setBackupOps(new TreeSet<VersionedBackupOp>()); } getBackupOps().add(bo); if (getBackupOps().size() > 4) { forceBackupOps(); } } public void forceBackupOps() { if (getBackupOps() == null) return; Iterator<VersionedBackupOp> it = getBackupOps().iterator(); while (it.hasNext()) { VersionedBackupOp v = it.next(); v.run(); setVersion(v.getVersion()); it.remove(); } } public Data getKey() { return key; } public Data getValue() { return value; } public Object setValue(Object value) { return getRecordEntry().setValue(value); } public void setValue(Data value) { cmap.invalidateRecordEntryValue(this); this.value = value; } public Long[] getIndexes() { if (optionalInfo == null) return null; return getOptionalInfo().indexes; } public byte[] getIndexTypes() { if (optionalInfo == null) return null; return getOptionalInfo().indexTypes; } public void setIndexes(Long[] indexes, byte[] indexTypes) { if (indexes != null) { this.getOptionalInfo().indexes = indexes; this.getOptionalInfo().indexTypes = indexTypes; } } public int valueCount() { int count = 0; if (getValue() != null) { count = 1; } else if (getMultiValues() != null) { count = getMultiValues().size(); } else if (copyCount > 0) { count += copyCount; } return count; } public long getCost() { long cost = 0; if (getValue() != null) { cost = getValue().size(); if (copyCount > 0) { cost *= copyCount; } } else if (getMultiValues() != null && getMultiValues().size() > 0) { for (Data data : getMultiValues()) { if (data != null) { cost += data.size(); } } } return cost + getKey().size() + 250; } public boolean containsValue(Data value) { if (this.getValue() != null) { return this.getValue().equals(value); } else if (getMultiValues() != null) { int count = getMultiValues().size(); if (count > 0) { return getMultiValues().contains(value); } } return false; } public void addValue(Data value) { if (getMultiValues() == null) { setMultiValues(new HashSet<Data>(2)); } getMultiValues().add(value); } public boolean unlock(int threadId, Address address) { return lock == null || lock.unlock(address, threadId); } public boolean testLock(int threadId, Address address) { return lock == null || lock.testLock(threadId, address); } public boolean lock(int threadId, Address address) { if (lock == null) { lock = new DistributedLock(address, threadId); return true; } return lock.lock(address, threadId); } public void addScheduledAction(ScheduledAction scheduledAction) { if (getScheduledActions() == null) { setScheduledActions(new LinkedList<ScheduledAction>()); } getScheduledActions().add(scheduledAction); } public boolean isRemovable() { return !isActive() && (valueCount() <= 0 && !hasListener() && (getScheduledActionCount() == 0) && getBackupOpCount() == 0); } public boolean isEvictable() { return (getLockCount() == 0 && !hasListener() && (getScheduledActionCount() == 0)); } public boolean hasListener() { return (getListeners() != null && getListeners().size() > 0); } public void addListener(Address address, boolean returnValue) { if (getListeners() == null) setMapListeners(new HashMap<Address, Boolean>(1)); getListeners().put(address, returnValue); } public void removeListener(Address address) { if (getListeners() == null) return; getListeners().remove(address); } public void incrementCopyCount() { copyCount++; } public void decrementCopyCount() { copyCount--; } public int getCopyCount() { return copyCount; } public void setLastUpdated() { setLastUpdateTime(System.currentTimeMillis()); } public void setLastAccessed() { setLastAccessTime(System.currentTimeMillis()); incrementHits(); } public long getExpirationTime() { return expirationTime; } public long getRemainingTTL() { if (expirationTime == Long.MAX_VALUE) { return Long.MAX_VALUE; } else { long ttl = expirationTime - System.currentTimeMillis(); return (ttl < 0) ? 1 : ttl; } } public long getRemainingIdle() { if (maxIdleMillis == Long.MAX_VALUE) { return Long.MAX_VALUE; } else { long lastTouch = Math.max(lastAccessTime, creationTime); long idle = System.currentTimeMillis() - lastTouch; return maxIdleMillis - idle; } } public void setMaxIdle(long idle) { if (idle <= 0 || idle == Long.MAX_VALUE) { maxIdleMillis = Long.MAX_VALUE; } else { maxIdleMillis = idle; } } public void setExpirationTime(long ttl) { if (ttl <= 0 || ttl == Long.MAX_VALUE) { expirationTime = Long.MAX_VALUE; } else { expirationTime = getCreationTime() + ttl; } } public void setInvalid() { expirationTime = (System.currentTimeMillis() - 10); } public boolean isValid(long now) { if (expirationTime == Long.MAX_VALUE && maxIdleMillis == Long.MAX_VALUE) { return true; } long lastTouch = Math.max(lastAccessTime, creationTime); long idle = now - lastTouch; return expirationTime > now && (maxIdleMillis > idle); } public boolean isValid() { return isValid(System.currentTimeMillis()); } public void markRemoved() { setActive(false); setRemoveTime(System.currentTimeMillis()); } public void setActive() { setRemoveTime(0); setActive(true); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Record)) return false; Record record = (Record) o; return record.getId().equals(getId()); } @Override public int hashCode() { return id.hashCode(); } public String toString() { return "Record key=" + getKey() + ", active=" + isActive() + ", version=" + getVersion() + ", removable=" + isRemovable(); } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } public void incrementVersion() { this.version++; } public long getCreationTime() { return creationTime; } public void setCreationTime(long newValue) { creationTime = newValue; } public long getLastAccessTime() { return lastAccessTime; } public void setLastAccessTime(long lastAccessTime) { this.lastAccessTime = lastAccessTime; } public long getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(long lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public int getHits() { return hits; } public void incrementHits() { hits++; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; if (!active) { cmap.invalidateRecordEntryValue(this); } } public String getName() { return cmap.name; } public int getBlockId() { return blockId; } public DistributedLock getLock() { return lock; } public void setLock(DistributedLock lock) { this.lock = lock; } public Set<Data> getMultiValues() { if (optionalInfo == null) return null; return getOptionalInfo().lsMultiValues; } public void setMultiValues(Set<Data> lsValues) { if (lsValues != null || optionalInfo != null) { this.getOptionalInfo().lsMultiValues = lsValues; } } public int getBackupOpCount() { return (getOptionalInfo().backupOps == null) ? 0 : getOptionalInfo().backupOps.size(); } public SortedSet<VersionedBackupOp> getBackupOps() { return getOptionalInfo().backupOps; } public void setBackupOps(SortedSet<VersionedBackupOp> backupOps) { this.getOptionalInfo().backupOps = backupOps; } public boolean isDirty() { return dirty; } public void setDirty(boolean dirty) { this.dirty = dirty; } public long getWriteTime() { return writeTime; } public void setWriteTime(long writeTime) { this.writeTime = writeTime; } public long getRemoveTime() { return removeTime; } public void setRemoveTime(long removeTime) { this.removeTime = removeTime; } public Long getId() { return id; } public boolean hasScheduledAction() { return optionalInfo != null && optionalInfo.lsScheduledActions != null && optionalInfo.lsScheduledActions.size() > 0; } public List<ScheduledAction> getScheduledActions() { if (optionalInfo == null) return null; return getOptionalInfo().lsScheduledActions; } public void setScheduledActions(List<ScheduledAction> lsScheduledActions) { this.getOptionalInfo().lsScheduledActions = lsScheduledActions; } public Map<Address, Boolean> getListeners() { if (optionalInfo == null) return null; return getOptionalInfo().mapListeners; } public void setMapListeners(Map<Address, Boolean> mapListeners) { this.getOptionalInfo().mapListeners = mapListeners; } public void setCopyCount(int copyCount) { this.copyCount = copyCount; } public boolean isLocked() { return lock != null && lock.isLocked(); } public int getScheduledActionCount() { if (optionalInfo == null) return 0; return (getOptionalInfo().lsScheduledActions == null) ? 0 : getOptionalInfo().lsScheduledActions.size(); } public int getLockCount() { return (lock == null) ? 0 : lock.getLockCount(); } public void clearLock() { if (lock != null) { lock.clear(); } } public Address getLockAddress() { return (lock == null) ? null : lock.getLockAddress(); } public OptionalInfo getOptionalInfo() { // if (true) throw new RuntimeException(); if (optionalInfo == null) { optionalInfo = new OptionalInfo(); } return optionalInfo; } class OptionalInfo { private Long[] indexes; // indexes of the current value; private byte[] indexTypes; // index types of the current value; private List<ScheduledAction> lsScheduledActions = null; private Map<Address, Boolean> mapListeners = null; private Set<Data> lsMultiValues = null; // multimap values private SortedSet<VersionedBackupOp> backupOps = null; } }
hazelcast/src/main/java/com/hazelcast/impl/Record.java
/* * Copyright (c) 2008-2010, Hazel Ltd. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.hazelcast.impl; import com.hazelcast.core.MapEntry; import com.hazelcast.impl.base.DistributedLock; import com.hazelcast.impl.base.ScheduledAction; import com.hazelcast.nio.Address; import com.hazelcast.nio.Data; import java.util.*; public final class Record implements MapEntry { private final CMap cmap; private final Long id; private final short blockId; private final Data key; private volatile Data value; private volatile boolean active = true; private volatile int hits = 0; private volatile long version = 0; private volatile long maxIdleMillis = Long.MAX_VALUE; private volatile long writeTime = -1; private volatile long removeTime = 0; private volatile long lastAccessTime = 0; private volatile long creationTime = 0; private volatile long expirationTime = Long.MAX_VALUE; private volatile long lastUpdateTime = 0; private volatile boolean dirty = false; private volatile int copyCount = 0; private DistributedLock lock = null; private OptionalInfo optionalInfo = null; public Record(CMap cmap, int blockId, Data key, Data value, long ttl, long maxIdleMillis, Long id) { super(); this.id = id; this.cmap = cmap; this.blockId = (short) blockId; this.key = key; this.value = value; this.setCreationTime(System.currentTimeMillis()); this.setExpirationTime(ttl); this.maxIdleMillis = (maxIdleMillis == 0) ? Long.MAX_VALUE : maxIdleMillis; this.setVersion(0); } public Record copy() { Record recordCopy = new Record(cmap, blockId, key, value, getRemainingTTL(), getRemainingIdle(), id); recordCopy.setIndexes(getOptionalInfo().indexes, getOptionalInfo().indexTypes); if (lock != null) { recordCopy.setLock(new DistributedLock(lock)); } recordCopy.setMultiValues(getOptionalInfo().lsMultiValues); recordCopy.setCopyCount(copyCount); recordCopy.setVersion(getVersion()); return recordCopy; } public RecordEntry getRecordEntry() { return cmap.getRecordEntry(this); } public CMap getCMap() { return cmap; } public void runBackupOps() { if (getBackupOps() != null) { if (getBackupOps().size() > 0) { Iterator<VersionedBackupOp> it = getBackupOps().iterator(); while (it.hasNext()) { VersionedBackupOp bo = it.next(); if (bo.getVersion() < getVersion() + 1) { it.remove(); } else if (bo.getVersion() == getVersion() + 1) { bo.run(); setVersion(bo.getVersion()); it.remove(); } else { return; } } } } } public void addBackupOp(VersionedBackupOp bo) { if (getBackupOps() == null) { setBackupOps(new TreeSet<VersionedBackupOp>()); } getBackupOps().add(bo); if (getBackupOps().size() > 4) { forceBackupOps(); } } public void forceBackupOps() { if (getBackupOps() == null) return; Iterator<VersionedBackupOp> it = getBackupOps().iterator(); while (it.hasNext()) { VersionedBackupOp v = it.next(); v.run(); setVersion(v.getVersion()); it.remove(); } } public Data getKey() { return key; } public Data getValue() { return value; } public Object setValue(Object value) { return getRecordEntry().setValue(value); } public void setValue(Data value) { cmap.invalidateRecordEntryValue(this); this.value = value; } public Long[] getIndexes() { if (optionalInfo == null) return null; return getOptionalInfo().indexes; } public byte[] getIndexTypes() { if (optionalInfo == null) return null; return getOptionalInfo().indexTypes; } public void setIndexes(Long[] indexes, byte[] indexTypes) { if (indexes != null) { this.getOptionalInfo().indexes = indexes; this.getOptionalInfo().indexTypes = indexTypes; } } public int valueCount() { int count = 0; if (getValue() != null) { count = 1; } else if (getMultiValues() != null) { count = getMultiValues().size(); } else if (copyCount > 0) { count += copyCount; } return count; } public long getCost() { long cost = 0; if (getValue() != null) { cost = getValue().size(); if (copyCount > 0) { cost *= copyCount; } } else if (getMultiValues() != null && getMultiValues().size() > 0) { for (Data data : getMultiValues()) { if (data != null) { cost += data.size(); } } } return cost + getKey().size() + 250; } public boolean containsValue(Data value) { if (this.getValue() != null) { return this.getValue().equals(value); } else if (getMultiValues() != null) { int count = getMultiValues().size(); if (count > 0) { return getMultiValues().contains(value); } } return false; } public void addValue(Data value) { if (getMultiValues() == null) { setMultiValues(new HashSet<Data>(2)); } getMultiValues().add(value); } public boolean unlock(int threadId, Address address) { return lock == null || lock.unlock(address, threadId); } public boolean testLock(int threadId, Address address) { return lock == null || lock.testLock(threadId, address); } public boolean lock(int threadId, Address address) { if (lock == null) { lock = new DistributedLock(address, threadId); return true; } return lock.lock(address, threadId); } public void addScheduledAction(ScheduledAction scheduledAction) { if (getScheduledActions() == null) { setScheduledActions(new LinkedList<ScheduledAction>()); } getScheduledActions().add(scheduledAction); } public boolean isRemovable() { return !isActive() && (valueCount() <= 0 && !hasListener() && (getScheduledActionCount() == 0) && getBackupOpCount() == 0); } public boolean isEvictable() { return (getLockCount() == 0 && !hasListener() && (getScheduledActionCount() == 0)); } public boolean hasListener() { return (getListeners() != null && getListeners().size() > 0); } public void addListener(Address address, boolean returnValue) { if (getListeners() == null) setMapListeners(new HashMap<Address, Boolean>(1)); getListeners().put(address, returnValue); } public void removeListener(Address address) { if (getListeners() == null) return; getListeners().remove(address); } public void incrementCopyCount() { copyCount++; } public void decrementCopyCount() { copyCount--; } public int getCopyCount() { return copyCount; } public void setLastUpdated() { setLastUpdateTime(System.currentTimeMillis()); } public void setLastAccessed() { setLastAccessTime(System.currentTimeMillis()); incrementHits(); } public long getExpirationTime() { return expirationTime; } public long getRemainingTTL() { if (expirationTime == Long.MAX_VALUE) { return Long.MAX_VALUE; } else { long ttl = expirationTime - System.currentTimeMillis(); return (ttl < 0) ? 1 : ttl; } } public long getRemainingIdle() { if (maxIdleMillis == Long.MAX_VALUE) { return Long.MAX_VALUE; } else { long lastTouch = Math.max(lastAccessTime, creationTime); long idle = System.currentTimeMillis() - lastTouch; return maxIdleMillis - idle; } } public void setMaxIdle(long idle) { if (idle <= 0 || idle == Long.MAX_VALUE) { maxIdleMillis = Long.MAX_VALUE; } else { maxIdleMillis = idle; } } public void setExpirationTime(long ttl) { if (ttl <= 0 || ttl == Long.MAX_VALUE) { expirationTime = Long.MAX_VALUE; } else { expirationTime = getCreationTime() + ttl; } } public void setInvalid() { expirationTime = (System.currentTimeMillis() - 10); } public boolean isValid(long now) { if (expirationTime == Long.MAX_VALUE && maxIdleMillis == Long.MAX_VALUE) { return true; } long lastTouch = Math.max(lastAccessTime, creationTime); long idle = now - lastTouch; return expirationTime > now && (maxIdleMillis > idle); } public boolean isValid() { return isValid(System.currentTimeMillis()); } public void markRemoved() { setActive(false); setRemoveTime(System.currentTimeMillis()); } public void setActive() { setRemoveTime(0); setActive(true); } @Override public boolean equals(Object o) { if (this == o) return true; if ((o instanceof Record)) return false; Record record = (Record) o; return record.getId().equals(getId()); } @Override public int hashCode() { return id.hashCode(); } public String toString() { return "Record key=" + getKey() + ", active=" + isActive() + ", version=" + getVersion() + ", removable=" + isRemovable(); } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } public void incrementVersion() { this.version++; } public long getCreationTime() { return creationTime; } public void setCreationTime(long newValue) { creationTime = newValue; } public long getLastAccessTime() { return lastAccessTime; } public void setLastAccessTime(long lastAccessTime) { this.lastAccessTime = lastAccessTime; } public long getLastUpdateTime() { return lastUpdateTime; } public void setLastUpdateTime(long lastUpdateTime) { this.lastUpdateTime = lastUpdateTime; } public int getHits() { return hits; } public void incrementHits() { hits++; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; if (!active) { cmap.invalidateRecordEntryValue(this); } } public String getName() { return cmap.name; } public int getBlockId() { return blockId; } public DistributedLock getLock() { return lock; } public void setLock(DistributedLock lock) { this.lock = lock; } public Set<Data> getMultiValues() { if (optionalInfo == null) return null; return getOptionalInfo().lsMultiValues; } public void setMultiValues(Set<Data> lsValues) { if (lsValues != null || optionalInfo != null) { this.getOptionalInfo().lsMultiValues = lsValues; } } public int getBackupOpCount() { return (getOptionalInfo().backupOps == null) ? 0 : getOptionalInfo().backupOps.size(); } public SortedSet<VersionedBackupOp> getBackupOps() { return getOptionalInfo().backupOps; } public void setBackupOps(SortedSet<VersionedBackupOp> backupOps) { this.getOptionalInfo().backupOps = backupOps; } public boolean isDirty() { return dirty; } public void setDirty(boolean dirty) { this.dirty = dirty; } public long getWriteTime() { return writeTime; } public void setWriteTime(long writeTime) { this.writeTime = writeTime; } public long getRemoveTime() { return removeTime; } public void setRemoveTime(long removeTime) { this.removeTime = removeTime; } public Long getId() { return id; } public boolean hasScheduledAction() { return optionalInfo != null && optionalInfo.lsScheduledActions != null && optionalInfo.lsScheduledActions.size() > 0; } public List<ScheduledAction> getScheduledActions() { if (optionalInfo == null) return null; return getOptionalInfo().lsScheduledActions; } public void setScheduledActions(List<ScheduledAction> lsScheduledActions) { this.getOptionalInfo().lsScheduledActions = lsScheduledActions; } public Map<Address, Boolean> getListeners() { if (optionalInfo == null) return null; return getOptionalInfo().mapListeners; } public void setMapListeners(Map<Address, Boolean> mapListeners) { this.getOptionalInfo().mapListeners = mapListeners; } public void setCopyCount(int copyCount) { this.copyCount = copyCount; } public boolean isLocked() { return lock != null && lock.isLocked(); } public int getScheduledActionCount() { if (optionalInfo == null) return 0; return (getOptionalInfo().lsScheduledActions == null) ? 0 : getOptionalInfo().lsScheduledActions.size(); } public int getLockCount() { return (lock == null) ? 0 : lock.getLockCount(); } public void clearLock() { if (lock != null) { lock.clear(); } } public Address getLockAddress() { return (lock == null) ? null : lock.getLockAddress(); } public OptionalInfo getOptionalInfo() { // if (true) throw new RuntimeException(); if (optionalInfo == null) { optionalInfo = new OptionalInfo(); } return optionalInfo; } class OptionalInfo { private Long[] indexes; // indexes of the current value; private byte[] indexTypes; // index types of the current value; private List<ScheduledAction> lsScheduledActions = null; private Map<Address, Boolean> mapListeners = null; private Set<Data> lsMultiValues = null; // multimap values private SortedSet<VersionedBackupOp> backupOps = null; } }
fixes Record.equals git-svn-id: 505f71283407c412190d59965c6d67c623df2891@1426 3f8e66b6-ca9d-11dd-a2b5-e5f827957e07
hazelcast/src/main/java/com/hazelcast/impl/Record.java
fixes Record.equals
<ide><path>azelcast/src/main/java/com/hazelcast/impl/Record.java <ide> @Override <ide> public boolean equals(Object o) { <ide> if (this == o) return true; <del> if ((o instanceof Record)) return false; <add> if (!(o instanceof Record)) return false; <ide> Record record = (Record) o; <ide> return record.getId().equals(getId()); <ide> }
Java
apache-2.0
7e29ce520bcb3ab4a5275ff2dce49332f66887c6
0
sdgdsffdsfff/hermes,sdgdsffdsfff/hermes,lejingw/hermes,sdgdsffdsfff/hermes,lejingw/hermes,fengshao0907/hermes,fengshao0907/hermes,Tony-Zhang03/hermes,lejingw/hermes,Tony-Zhang03/hermes,fengshao0907/hermes,sdgdsffdsfff/hermes,fengshao0907/hermes,Tony-Zhang03/hermes,Tony-Zhang03/hermes,lejingw/hermes
package com.ctrip.hermes.broker.lease; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.annotation.Named; import org.unidal.tuple.Pair; import com.ctrip.hermes.broker.build.BuildConstants; import com.ctrip.hermes.broker.config.BrokerConfig; import com.ctrip.hermes.broker.lease.BrokerLeaseManager.BrokerLeaseKey; import com.ctrip.hermes.core.lease.Lease; import com.ctrip.hermes.core.lease.LeaseAcquireResponse; import com.ctrip.hermes.core.lease.LeaseManager; import com.ctrip.hermes.core.service.SystemClockService; import com.ctrip.hermes.core.utils.HermesThreadFactory; /** * @author Leo Liang([email protected]) * */ @Named(type = BrokerLeaseContainer.class) public class BrokerLeaseContainer implements Initializable { private static final Logger log = LoggerFactory.getLogger(BrokerLeaseContainer.class); @Inject(BuildConstants.BROKER) private LeaseManager<BrokerLeaseKey> m_leaseManager; @Inject private BrokerConfig m_config; @Inject private SystemClockService m_systemClockService; private Map<BrokerLeaseKey, Lease> m_existingLeases = new ConcurrentHashMap<>(); private Map<Pair<String, Integer>, Long> m_nextAcquireTimes = new ConcurrentHashMap<>(); private ConcurrentMap<BrokerLeaseKey, AtomicBoolean> m_leaseAcquireTaskRunnings = new ConcurrentHashMap<>(); private ScheduledExecutorService m_scheduledExecutorService; public Lease acquireLease(String topic, int partition, String sessionId) { BrokerLeaseKey key = new BrokerLeaseKey(topic, partition, sessionId); Lease lease = m_existingLeases.get(key); if (lease == null || lease.isExpired()) { scheduleLeaseAcquireTask(key); return null; } else { return lease; } } private void scheduleLeaseAcquireTask(final BrokerLeaseKey key) { m_leaseAcquireTaskRunnings.putIfAbsent(key, new AtomicBoolean(false)); final AtomicBoolean acquireTaskRunning = m_leaseAcquireTaskRunnings.get(key); if (acquireTaskRunning.compareAndSet(false, true)) { m_scheduledExecutorService.submit(new Runnable() { @Override public void run() { try { doAcquireLease(key); } finally { acquireTaskRunning.set(false); } } }); } } private void doAcquireLease(BrokerLeaseKey key) { Lease existingLease = m_existingLeases.get(key); if (existingLease != null && !existingLease.isExpired()) { return; } Pair<String, Integer> tp = new Pair<String, Integer>(key.getTopic(), key.getPartition()); if (m_nextAcquireTimes.containsKey(tp) && m_nextAcquireTimes.get(tp) > m_systemClockService.now()) { return; } LeaseAcquireResponse response = m_leaseManager.tryAcquireLease(key); if (response != null && response.isAcquired() && !response.getLease().isExpired()) { Lease lease = response.getLease(); if (!lease.isExpired()) { m_existingLeases.put(key, lease); long renewDelay = calRenewDelay(lease); m_nextAcquireTimes.remove(tp); scheduleRenewLeaseTask(key, renewDelay); log.info("Lease acquired(topic={}, partition={}, sessionId={}, leaseId={}, expireTime={})", key.getTopic(), key.getPartition(), key.getSessionId(), lease.getId(), new Date(lease.getExpireTime())); } } else { long nextTryTime = response != null && response.getNextTryTime() > 0 ? response.getNextTryTime() : m_config .getDefaultLeaseAcquireDelayMillis() + m_systemClockService.now(); m_nextAcquireTimes.put(tp, nextTryTime); if (log.isDebugEnabled()) { log.debug("Unable to acquire lease(topic={}, partition={}, sessionId={}), next retry time will be {}.", key.getTopic(), key.getPartition(), key.getSessionId(), new Date(nextTryTime)); } } } private long calRenewDelay(Lease lease) { return lease.getRemainingTime() - m_config.getLeaseRenewTimeMillsBeforeExpire(); } private void scheduleRenewLeaseTask(final BrokerLeaseKey key, long delay) { if (delay < 0) { return; } m_scheduledExecutorService.schedule(new Runnable() { @Override public void run() { Lease existingLease = m_existingLeases.get(key); if (existingLease != null && !existingLease.isExpired()) { LeaseAcquireResponse response = m_leaseManager.tryRenewLease(key, existingLease); long renewDelay = 0; if (response != null && response.isAcquired()) { Lease lease = response.getLease(); existingLease.setExpireTime(lease.getExpireTime()); renewDelay = calRenewDelay(lease); if (log.isDebugEnabled()) { log.debug( "Successfully renew lease(topic={}, partition={}, sessionId={}, leaseId={}, expireTime={})", key.getTopic(), key.getPartition(), key.getSessionId(), existingLease.getId(), new Date( existingLease.getExpireTime())); } } else { renewDelay = m_config.getDefaultLeaseRenewDelayMillis(); if (response != null && response.getNextTryTime() > 0) { renewDelay = response.getNextTryTime() - m_systemClockService.now(); } if (log.isDebugEnabled()) { log.debug( "Unable to renew lease((topic={}, partition={}, sessionId={}, leaseId={}), next retry will delay {} milliseconds.", key.getTopic(), key.getPartition(), key.getSessionId(), existingLease.getId(), renewDelay); } } scheduleRenewLeaseTask(key, renewDelay); } else { if (existingLease != null) { log.info("Lease expired(topic={}, parition={}, sessionId={}, leaseId={}).", key.getTopic(), key.getPartition(), key.getSessionId(), existingLease.getId()); } else { log.info("Lease expired(topic={}, parition={}, sessionId={}).", key.getTopic(), key.getPartition(), key.getSessionId()); } } } }, delay, TimeUnit.MILLISECONDS); } @Override public void initialize() throws InitializationException { m_scheduledExecutorService = Executors.newScheduledThreadPool(m_config.getLeaseContainerThreadCount(), HermesThreadFactory.create("BrokerLeaseContainer", true)); } }
hermes-broker/src/main/java/com/ctrip/hermes/broker/lease/BrokerLeaseContainer.java
package com.ctrip.hermes.broker.lease; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.unidal.lookup.annotation.Inject; import org.unidal.lookup.annotation.Named; import org.unidal.tuple.Pair; import com.ctrip.hermes.broker.build.BuildConstants; import com.ctrip.hermes.broker.config.BrokerConfig; import com.ctrip.hermes.broker.lease.BrokerLeaseManager.BrokerLeaseKey; import com.ctrip.hermes.core.lease.Lease; import com.ctrip.hermes.core.lease.LeaseAcquireResponse; import com.ctrip.hermes.core.lease.LeaseManager; import com.ctrip.hermes.core.service.SystemClockService; import com.ctrip.hermes.core.utils.HermesThreadFactory; /** * @author Leo Liang([email protected]) * */ @Named(type = BrokerLeaseContainer.class) public class BrokerLeaseContainer implements Initializable { private static final Logger log = LoggerFactory.getLogger(BrokerLeaseContainer.class); @Inject(BuildConstants.BROKER) private LeaseManager<BrokerLeaseKey> m_leaseManager; @Inject private BrokerConfig m_config; @Inject private SystemClockService m_systemClockService; private Map<BrokerLeaseKey, Lease> m_existingLeases = new ConcurrentHashMap<>(); private Map<Pair<String, Integer>, Long> m_nextAcquireTimes = new ConcurrentHashMap<>(); private ConcurrentMap<BrokerLeaseKey, AtomicBoolean> m_leaseAcquireTaskRunnings = new ConcurrentHashMap<>(); private ScheduledExecutorService m_scheduledExecutorService; public Lease acquireLease(String topic, int partition, String sessionId) { BrokerLeaseKey key = new BrokerLeaseKey(topic, partition, sessionId); Lease lease = m_existingLeases.get(key); if (lease == null || lease.isExpired()) { scheduleLeaseAcquireTask(key); return null; } else { return lease; } } private void scheduleLeaseAcquireTask(final BrokerLeaseKey key) { m_leaseAcquireTaskRunnings.putIfAbsent(key, new AtomicBoolean(false)); final AtomicBoolean acquireTaskRunning = m_leaseAcquireTaskRunnings.get(key); if (acquireTaskRunning.compareAndSet(false, true)) { m_scheduledExecutorService.submit(new Runnable() { @Override public void run() { try { doAcquireLease(key); } finally { acquireTaskRunning.set(false); } } }); } } private void doAcquireLease(BrokerLeaseKey key) { Lease existingLease = m_existingLeases.get(key); if (existingLease != null && !existingLease.isExpired()) { return; } Pair<String, Integer> tp = new Pair<String, Integer>(key.getTopic(), key.getPartition()); if (m_nextAcquireTimes.containsKey(tp) && m_nextAcquireTimes.get(tp) > m_systemClockService.now()) { return; } LeaseAcquireResponse response = m_leaseManager.tryAcquireLease(key); if (response != null && response.isAcquired() && !response.getLease().isExpired()) { Lease lease = response.getLease(); if (!lease.isExpired()) { m_existingLeases.put(key, lease); long renewDelay = lease.getRemainingTime() - m_config.getLeaseRenewTimeMillsBeforeExpire(); m_nextAcquireTimes.remove(tp); scheduleRenewLeaseTask(key, renewDelay); log.info("Lease acquired(topic={}, partition={}, sessionId={}, leaseId={}, expireTime={})", key.getTopic(), key.getPartition(), key.getSessionId(), lease.getId(), new Date(lease.getExpireTime())); } } else { long nextTryTime = response != null && response.getNextTryTime() > 0 ? response.getNextTryTime() : m_config .getDefaultLeaseAcquireDelayMillis() + m_systemClockService.now(); m_nextAcquireTimes.put(tp, nextTryTime); if (log.isDebugEnabled()) { log.debug("Unable to acquire lease(topic={}, partition={}, sessionId={}), next retry time will be {}.", key.getTopic(), key.getPartition(), key.getSessionId(), new Date(nextTryTime)); } } } private void scheduleRenewLeaseTask(final BrokerLeaseKey key, long delay) { if (delay < 0) { return; } m_scheduledExecutorService.schedule(new Runnable() { @Override public void run() { Lease existingLease = m_existingLeases.get(key); if (existingLease != null && !existingLease.isExpired()) { LeaseAcquireResponse response = m_leaseManager.tryRenewLease(key, existingLease); if (response != null && response.isAcquired()) { existingLease.setExpireTime(response.getLease().getExpireTime()); if (log.isDebugEnabled()) { log.debug( "Successfully renew lease(topic={}, partition={}, sessionId={}, leaseId={}, expireTime={})", key.getTopic(), key.getPartition(), key.getSessionId(), existingLease.getId(), new Date( existingLease.getExpireTime())); } } else { long delay = m_config.getDefaultLeaseRenewDelayMillis(); if (response != null && response.getNextTryTime() > 0) { delay = response.getNextTryTime() - m_systemClockService.now(); } scheduleRenewLeaseTask(key, delay); if (log.isDebugEnabled()) { log.debug( "Unable to renew lease((topic={}, partition={}, sessionId={}, leaseId={}), next retry will delay {} milliseconds.", key.getTopic(), key.getPartition(), key.getSessionId(), existingLease.getId(), delay); } } } else { if (existingLease != null) { log.info("Lease expired(topic={}, parition={}, sessionId={}, leaseId={}).", key.getTopic(), key.getPartition(), key.getSessionId(), existingLease.getId()); } else { log.info("Lease expired(topic={}, parition={}, sessionId={}).", key.getTopic(), key.getPartition(), key.getSessionId()); } } } }, delay, TimeUnit.MILLISECONDS); } @Override public void initialize() throws InitializationException { m_scheduledExecutorService = Executors.newScheduledThreadPool(m_config.getLeaseContainerThreadCount(), HermesThreadFactory.create("BrokerLeaseContainer", true)); } }
fix lease renew bug
hermes-broker/src/main/java/com/ctrip/hermes/broker/lease/BrokerLeaseContainer.java
fix lease renew bug
<ide><path>ermes-broker/src/main/java/com/ctrip/hermes/broker/lease/BrokerLeaseContainer.java <ide> if (!lease.isExpired()) { <ide> m_existingLeases.put(key, lease); <ide> <del> long renewDelay = lease.getRemainingTime() - m_config.getLeaseRenewTimeMillsBeforeExpire(); <add> long renewDelay = calRenewDelay(lease); <ide> m_nextAcquireTimes.remove(tp); <ide> scheduleRenewLeaseTask(key, renewDelay); <ide> log.info("Lease acquired(topic={}, partition={}, sessionId={}, leaseId={}, expireTime={})", key.getTopic(), <ide> } <ide> } <ide> <add> private long calRenewDelay(Lease lease) { <add> return lease.getRemainingTime() - m_config.getLeaseRenewTimeMillsBeforeExpire(); <add> } <add> <ide> private void scheduleRenewLeaseTask(final BrokerLeaseKey key, long delay) { <ide> if (delay < 0) { <ide> return; <ide> if (existingLease != null && !existingLease.isExpired()) { <ide> LeaseAcquireResponse response = m_leaseManager.tryRenewLease(key, existingLease); <ide> <add> long renewDelay = 0; <ide> if (response != null && response.isAcquired()) { <del> existingLease.setExpireTime(response.getLease().getExpireTime()); <add> Lease lease = response.getLease(); <add> existingLease.setExpireTime(lease.getExpireTime()); <add> renewDelay = calRenewDelay(lease); <ide> if (log.isDebugEnabled()) { <ide> log.debug( <ide> "Successfully renew lease(topic={}, partition={}, sessionId={}, leaseId={}, expireTime={})", <ide> existingLease.getExpireTime())); <ide> } <ide> } else { <del> long delay = m_config.getDefaultLeaseRenewDelayMillis(); <add> renewDelay = m_config.getDefaultLeaseRenewDelayMillis(); <ide> if (response != null && response.getNextTryTime() > 0) { <del> delay = response.getNextTryTime() - m_systemClockService.now(); <add> renewDelay = response.getNextTryTime() - m_systemClockService.now(); <ide> } <del> scheduleRenewLeaseTask(key, delay); <ide> if (log.isDebugEnabled()) { <ide> log.debug( <ide> "Unable to renew lease((topic={}, partition={}, sessionId={}, leaseId={}), next retry will delay {} milliseconds.", <del> key.getTopic(), key.getPartition(), key.getSessionId(), existingLease.getId(), delay); <add> key.getTopic(), key.getPartition(), key.getSessionId(), existingLease.getId(), renewDelay); <ide> } <ide> } <add> scheduleRenewLeaseTask(key, renewDelay); <ide> } else { <ide> if (existingLease != null) { <ide> log.info("Lease expired(topic={}, parition={}, sessionId={}, leaseId={}).", key.getTopic(),
Java
apache-2.0
4c0a5886ca10f60b0efff843dd10d4b12d4c6de9
0
zxhfirefox/netty,silvaran/netty,ninja-/netty,Kalvar/netty,lznhust/netty,afds/netty,Alwayswithme/netty,mikkokar/netty,Mounika-Chirukuri/netty,f7753/netty,ijuma/netty,netty/netty,shenguoquan/netty,lukw00/netty,danny200309/netty,windie/netty,lukehutch/netty,brennangaunce/netty,duqiao/netty,yrcourage/netty,huuthang1993/netty,codevelop/netty,satishsaley/netty,MediumOne/netty,mx657649013/netty,nkhuyu/netty,yonglehou/netty-1,WangJunTYTL/netty,ejona86/netty,Apache9/netty,Scottmitch/netty,ijuma/netty,liuciuse/netty,lukehutch/netty,clebertsuconic/netty,mcobrien/netty,wangyikai/netty,shelsonjava/netty,daschl/netty,caoyanwei/netty,BrunoColin/netty,wangyikai/netty,pengzj/netty,smayoorans/netty,fengjiachun/netty,ngocdaothanh/netty,JungMinu/netty,lugt/netty,Kingson4Wu/netty,jongyeol/netty,jchambers/netty,yonglehou/netty-1,chanakaudaya/netty,nmittler/netty,shenguoquan/netty,shenguoquan/netty,dongjiaqiang/netty,jdivy/netty,KatsuraKKKK/netty,nadeeshaan/netty,DolphinZhao/netty,carlbai/netty,kvr000/netty,caoyanwei/netty,tbrooks8/netty,AnselQiao/netty,hyangtack/netty,bigheary/netty,jdivy/netty,altihou/netty,bryce-anderson/netty,joansmith/netty,jongyeol/netty,louxiu/netty,niuxinghua/netty,yipen9/netty,windie/netty,netty/netty,gigold/netty,chinayin/netty,jovezhougang/netty,dongjiaqiang/netty,firebase/netty,x1957/netty,zhoffice/netty,kiril-me/netty,nat2013/netty,NiteshKant/netty,louiscryan/netty,x1957/netty,MediumOne/netty,yonglehou/netty-1,chanakaudaya/netty,DolphinZhao/netty,ichaki5748/netty,bigheary/netty,exinguu/netty,clebertsuconic/netty,WangJunTYTL/netty,drowning/netty,bigheary/netty,fantayeneh/netty,JungMinu/netty,kjniemi/netty,IBYoung/netty,mx657649013/netty,Kingson4Wu/netty,mcanthony/netty,liyang1025/netty,AchinthaReemal/netty,AchinthaReemal/netty,balaprasanna/netty,sja/netty,blademainer/netty,wuxiaowei907/netty,normanmaurer/netty,ajaysarda/netty,andsel/netty,mcanthony/netty,shism/netty,purplefox/netty-4.0.2.8-hacked,kjniemi/netty,blademainer/netty,danny200309/netty,timboudreau/netty,wuxiaowei907/netty,huuthang1993/netty,AchinthaReemal/netty,xiongzheng/netty,zhoffice/netty,djchen/netty,Techcable/netty,tempbottle/netty,BrunoColin/netty,fenik17/netty,ajaysarda/netty,hepin1989/netty,smayoorans/netty,alkemist/netty,mway08/netty,eonezhang/netty,moyiguket/netty,zer0se7en/netty,mx657649013/netty,sja/netty,brennangaunce/netty,johnou/netty,shism/netty,alkemist/netty,andsel/netty,qingsong-xu/netty,DolphinZhao/netty,castomer/netty,sverkera/netty,altihou/netty,MediumOne/netty,IBYoung/netty,huanyi0723/netty,BrunoColin/netty,chinayin/netty,youprofit/netty,pengzj/netty,ichaki5748/netty,jongyeol/netty,MediumOne/netty,AnselQiao/netty,golovnin/netty,pengzj/netty,mubarak/netty,rovarga/netty,qingsong-xu/netty,sja/netty,eonezhang/netty,zzcclp/netty,youprofit/netty,exinguu/netty,jchambers/netty,louxiu/netty,seetharamireddy540/netty,bob329/netty,f7753/netty,lukw00/netty,jongyeol/netty,zhujingling/netty,Kalvar/netty,carl-mastrangelo/netty,jdivy/netty,Spikhalskiy/netty,yipen9/netty,nkhuyu/netty,pengzj/netty,fantayeneh/netty,tempbottle/netty,mway08/netty,xiongzheng/netty,ioanbsu/netty,ioanbsu/netty,brennangaunce/netty,idelpivnitskiy/netty,smayoorans/netty,zzcclp/netty,maliqq/netty,louxiu/netty,afredlyj/learn-netty,kvr000/netty,zxhfirefox/netty,artgon/netty,zxhfirefox/netty,luyiisme/netty,mcobrien/netty,Mounika-Chirukuri/netty,Squarespace/netty,xiexingguang/netty,Kalvar/netty,codevelop/netty,x1957/netty,zhujingling/netty,rovarga/netty,menacher/netty,chinayin/netty,AnselQiao/netty,lznhust/netty,blademainer/netty,nat2013/netty,bob329/netty,ejona86/netty,kiril-me/netty,niuxinghua/netty,carl-mastrangelo/netty,s-gheldd/netty,fantayeneh/netty,f7753/netty,mubarak/netty,wuyinxian124/netty,nkhuyu/netty,eincs/netty,zzcclp/netty,danbev/netty,serioussam/netty,sameira/netty,rovarga/netty,qingsong-xu/netty,zxhfirefox/netty,fenik17/netty,xingguang2013/netty,codevelop/netty,jenskordowski/netty,sunbeansoft/netty,duqiao/netty,JungMinu/netty,windie/netty,caoyanwei/netty,carl-mastrangelo/netty,yipen9/netty,normanmaurer/netty,x1957/netty,Kingson4Wu/netty,doom369/netty,balaprasanna/netty,olupotd/netty,codevelop/netty,Kingson4Wu/netty,ijuma/netty,Spikhalskiy/netty,firebase/netty,ioanbsu/netty,bigheary/netty,gigold/netty,Mounika-Chirukuri/netty,gigold/netty,cnoldtree/netty,olupotd/netty,zer0se7en/netty,xiexingguang/netty,normanmaurer/netty,nkhuyu/netty,Apache9/netty,rovarga/netty,LuminateWireless/netty,buchgr/netty,castomer/netty,f7753/netty,liuciuse/netty,serioussam/netty,lukehutch/netty,joansmith/netty,mcanthony/netty,moyiguket/netty,lightsocks/netty,mikkokar/netty,lukw00/netty,nmittler/netty,junjiemars/netty,shuangqiuan/netty,artgon/netty,chanakaudaya/netty,johnou/netty,jenskordowski/netty,danbev/netty,lightsocks/netty,phlizik/netty,balaprasanna/netty,shelsonjava/netty,danbev/netty,afds/netty,hgl888/netty,lznhust/netty,tbrooks8/netty,andsel/netty,sja/netty,zhoffice/netty,firebase/netty,louiscryan/netty,mway08/netty,jdivy/netty,lugt/netty,fengjiachun/netty,kjniemi/netty,SinaTadayon/netty,ioanbsu/netty,doom369/netty,olupotd/netty,danbev/netty,xiexingguang/netty,johnou/netty,gerdriesselmann/netty,Techcable/netty,qingsong-xu/netty,clebertsuconic/netty,tempbottle/netty,unei66/netty,kjniemi/netty,eonezhang/netty,Squarespace/netty,serioussam/netty,chrisprobst/netty,Alwayswithme/netty,sammychen105/netty,drowning/netty,sameira/netty,chanakaudaya/netty,huuthang1993/netty,xingguang2013/netty,yawkat/netty,moyiguket/netty,kjniemi/netty,hyangtack/netty,fengjiachun/netty,ngocdaothanh/netty,lightsocks/netty,satishsaley/netty,liyang1025/netty,zxhfirefox/netty,ajaysarda/netty,ninja-/netty,huuthang1993/netty,liyang1025/netty,Mounika-Chirukuri/netty,xiexingguang/netty,fantayeneh/netty,WangJunTYTL/netty,JungMinu/netty,skyao/netty,castomer/netty,imangry/netty-zh,liyang1025/netty,fenik17/netty,Scottmitch/netty,danny200309/netty,chinayin/netty,gerdriesselmann/netty,duqiao/netty,silvaran/netty,unei66/netty,alkemist/netty,phlizik/netty,menacher/netty,orika/netty,shism/netty,CodingFabian/netty,kiril-me/netty,phlizik/netty,balaprasanna/netty,youprofit/netty,yrcourage/netty,DavidAlphaFox/netty,joansmith/netty,fenik17/netty,castomer/netty,lznhust/netty,liuciuse/netty,serioussam/netty,firebase/netty,kvr000/netty,shuangqiuan/netty,bob329/netty,CodingFabian/netty,afds/netty,joansmith/netty,carlbai/netty,sja/netty,unei66/netty,wangyikai/netty,eincs/netty,seetharamireddy540/netty,bryce-anderson/netty,xiongzheng/netty,dongjiaqiang/netty,djchen/netty,hyangtack/netty,bryce-anderson/netty,maliqq/netty,lukw00/netty,nat2013/netty,wuxiaowei907/netty,shuangqiuan/netty,luyiisme/netty,moyiguket/netty,idelpivnitskiy/netty,shelsonjava/netty,nmittler/netty,tempbottle/netty,wangyikai/netty,woshilaiceshide/netty,caoyanwei/netty,Techcable/netty,yrcourage/netty,liyang1025/netty,DolphinZhao/netty,Mounika-Chirukuri/netty,tbrooks8/netty,ijuma/netty,slandelle/netty,sverkera/netty,nadeeshaan/netty,SinaTadayon/netty,andsel/netty,s-gheldd/netty,eonezhang/netty,bigheary/netty,Spikhalskiy/netty,niuxinghua/netty,lugt/netty,brennangaunce/netty,smayoorans/netty,eonezhang/netty,x1957/netty,alkemist/netty,tbrooks8/netty,s-gheldd/netty,kvr000/netty,duqiao/netty,sverkera/netty,youprofit/netty,ngocdaothanh/netty,Squarespace/netty,CodingFabian/netty,bob329/netty,fengjiachun/netty,bob329/netty,DavidAlphaFox/netty,orika/netty,carlbai/netty,KatsuraKKKK/netty,IBYoung/netty,buchgr/netty,jovezhougang/netty,ichaki5748/netty,daschl/netty,zzcclp/netty,ichaki5748/netty,CodingFabian/netty,danbev/netty,Apache9/netty,zhoffice/netty,IBYoung/netty,olupotd/netty,clebertsuconic/netty,silvaran/netty,tbrooks8/netty,danny200309/netty,Kingson4Wu/netty,afds/netty,huanyi0723/netty,nayato/netty,mcobrien/netty,NiteshKant/netty,nayato/netty,castomer/netty,kyle-liu/netty4study,skyao/netty,louiscryan/netty,kiril-me/netty,blademainer/netty,sameira/netty,serioussam/netty,chrisprobst/netty,artgon/netty,afds/netty,huuthang1993/netty,cnoldtree/netty,nadeeshaan/netty,djchen/netty,yawkat/netty,golovnin/netty,zer0se7en/netty,Scottmitch/netty,shism/netty,niuxinghua/netty,kyle-liu/netty4study,golovnin/netty,sameira/netty,slandelle/netty,fenik17/netty,gerdriesselmann/netty,louxiu/netty,blucas/netty,blucas/netty,mway08/netty,youprofit/netty,fengshao0907/netty,LuminateWireless/netty,BrunoColin/netty,ngocdaothanh/netty,sunbeansoft/netty,ejona86/netty,ngocdaothanh/netty,mosoft521/netty,gerdriesselmann/netty,jdivy/netty,imangry/netty-zh,windie/netty,wuxiaowei907/netty,WangJunTYTL/netty,tempbottle/netty,netty/netty,luyiisme/netty,hgl888/netty,Apache9/netty,AchinthaReemal/netty,louxiu/netty,LuminateWireless/netty,louiscryan/netty,LuminateWireless/netty,unei66/netty,nayato/netty,satishsaley/netty,yonglehou/netty-1,zer0se7en/netty,ijuma/netty,netty/netty,blucas/netty,liuciuse/netty,jovezhougang/netty,seetharamireddy540/netty,wuyinxian124/netty,SinaTadayon/netty,wuyinxian124/netty,hgl888/netty,shenguoquan/netty,carl-mastrangelo/netty,moyiguket/netty,mosoft521/netty,kvr000/netty,cnoldtree/netty,ifesdjeen/netty,blucas/netty,hepin1989/netty,zzcclp/netty,johnou/netty,ifesdjeen/netty,maliqq/netty,jenskordowski/netty,drowning/netty,Spikhalskiy/netty,shelsonjava/netty,carlbai/netty,buchgr/netty,eincs/netty,chrisprobst/netty,nayato/netty,silvaran/netty,normanmaurer/netty,mcanthony/netty,eincs/netty,smayoorans/netty,xingguang2013/netty,woshilaiceshide/netty,lightsocks/netty,exinguu/netty,netty/netty,junjiemars/netty,johnou/netty,idelpivnitskiy/netty,silvaran/netty,jenskordowski/netty,ioanbsu/netty,yawkat/netty,BrunoColin/netty,DavidAlphaFox/netty,MediumOne/netty,mikkokar/netty,fengjiachun/netty,zhujingling/netty,KatsuraKKKK/netty,woshilaiceshide/netty,cnoldtree/netty,skyao/netty,jroper/netty,doom369/netty,idelpivnitskiy/netty,NiteshKant/netty,golovnin/netty,sammychen105/netty,gigold/netty,KatsuraKKKK/netty,chanakaudaya/netty,nadeeshaan/netty,junjiemars/netty,timboudreau/netty,hepin1989/netty,louiscryan/netty,chrisprobst/netty,alkemist/netty,ichaki5748/netty,lightsocks/netty,mway08/netty,s-gheldd/netty,doom369/netty,lznhust/netty,zer0se7en/netty,mosoft521/netty,xingguang2013/netty,Techcable/netty,artgon/netty,olupotd/netty,junjiemars/netty,satishsaley/netty,purplefox/netty-4.0.2.8-hacked,mikkokar/netty,daschl/netty,yawkat/netty,shelsonjava/netty,zhoffice/netty,carl-mastrangelo/netty,sunbeansoft/netty,ninja-/netty,seetharamireddy540/netty,xiexingguang/netty,eincs/netty,Alwayswithme/netty,f7753/netty,exinguu/netty,unei66/netty,shuangqiuan/netty,orika/netty,afredlyj/learn-netty,sameira/netty,duqiao/netty,shuangqiuan/netty,lukehutch/netty,lugt/netty,DolphinZhao/netty,danny200309/netty,djchen/netty,timboudreau/netty,develar/netty,Scottmitch/netty,purplefox/netty-4.0.2.8-hacked,AnselQiao/netty,satishsaley/netty,buchgr/netty,fantayeneh/netty,ninja-/netty,Kalvar/netty,jongyeol/netty,brennangaunce/netty,Alwayswithme/netty,jchambers/netty,luyiisme/netty,dongjiaqiang/netty,timboudreau/netty,clebertsuconic/netty,shism/netty,develar/netty,gerdriesselmann/netty,yonglehou/netty-1,Apache9/netty,zhujingling/netty,hgl888/netty,nadeeshaan/netty,andsel/netty,jovezhougang/netty,mubarak/netty,blucas/netty,kiril-me/netty,woshilaiceshide/netty,joansmith/netty,mikkokar/netty,artgon/netty,ejona86/netty,ajaysarda/netty,WangJunTYTL/netty,s-gheldd/netty,gigold/netty,wuxiaowei907/netty,Techcable/netty,imangry/netty-zh,mcobrien/netty,yawkat/netty,altihou/netty,blademainer/netty,timboudreau/netty,hyangtack/netty,slandelle/netty,fengshao0907/netty,SinaTadayon/netty,orika/netty,bryce-anderson/netty,huanyi0723/netty,huanyi0723/netty,purplefox/netty-4.0.2.8-hacked,Scottmitch/netty,mx657649013/netty,djchen/netty,lukw00/netty,hgl888/netty,niuxinghua/netty,yrcourage/netty,CodingFabian/netty,phlizik/netty,mubarak/netty,seetharamireddy540/netty,LuminateWireless/netty,nayato/netty,doom369/netty,imangry/netty-zh,mosoft521/netty,carlbai/netty,AnselQiao/netty,orika/netty,jovezhougang/netty,afredlyj/learn-netty,nkhuyu/netty,bryce-anderson/netty,ejona86/netty,woshilaiceshide/netty,altihou/netty,mcanthony/netty,Spikhalskiy/netty,ninja-/netty,xiongzheng/netty,jenskordowski/netty,skyao/netty,normanmaurer/netty,maliqq/netty,huanyi0723/netty,yrcourage/netty,yipen9/netty,sunbeansoft/netty,skyao/netty,sverkera/netty,xingguang2013/netty,hepin1989/netty,cnoldtree/netty,liuciuse/netty,mubarak/netty,sunbeansoft/netty,chrisprobst/netty,jchambers/netty,slandelle/netty,lugt/netty,chinayin/netty,DavidAlphaFox/netty,Squarespace/netty,caoyanwei/netty,dongjiaqiang/netty,imangry/netty-zh,exinguu/netty,wuyinxian124/netty,luyiisme/netty,NiteshKant/netty,mcobrien/netty,maliqq/netty,xiongzheng/netty,ajaysarda/netty,sverkera/netty,junjiemars/netty,wangyikai/netty,windie/netty,KatsuraKKKK/netty,fengshao0907/netty,mosoft521/netty,Kalvar/netty,AchinthaReemal/netty,NiteshKant/netty,zhujingling/netty,golovnin/netty,drowning/netty,Alwayswithme/netty,balaprasanna/netty,mx657649013/netty,Squarespace/netty,idelpivnitskiy/netty,qingsong-xu/netty,IBYoung/netty,lukehutch/netty,SinaTadayon/netty,shenguoquan/netty,sammychen105/netty,altihou/netty,jchambers/netty
/* * Copyright 2011 The Netty Project * * The Netty Project 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.netty.testsuite.transport.socket; import static org.junit.Assert.assertTrue; import io.netty.bootstrap.ConnectionlessBootstrap; import io.netty.buffer.ChannelBuffer; import io.netty.buffer.ChannelBuffers; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.MessageEvent; import io.netty.channel.SimpleChannelUpstreamHandler; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.DatagramChannelFactory; import io.netty.testsuite.util.TestUtils; import io.netty.util.internal.ExecutorUtil; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public abstract class AbstractDatagramMulticastTest { private static ExecutorService executor; @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract DatagramChannelFactory newServerSocketChannelFactory(Executor executor); protected abstract DatagramChannelFactory newClientSocketChannelFactory(Executor executor); @Test public void testMulticast() throws Throwable { ConnectionlessBootstrap sb = new ConnectionlessBootstrap(newServerSocketChannelFactory(executor)); ConnectionlessBootstrap cb = new ConnectionlessBootstrap(newClientSocketChannelFactory(executor)); MulticastTestHandler mhandler = new MulticastTestHandler(); cb.getPipeline().addFirst("handler", mhandler); sb.getPipeline().addFirst("handler", new SimpleChannelUpstreamHandler()); int port = TestUtils.getFreePort(); NetworkInterface iface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); // check if the NetworkInterface is null, this is the case on my ubuntu dev machine but not on osx and windows. // if so fail back the the first interface if (iface == null) { // use nextElement() as NetWorkInterface.getByIndex(0) returns null iface = NetworkInterface.getNetworkInterfaces().nextElement(); } sb.setOption("networkInterface", iface); sb.setOption("reuseAddress", true); Channel sc = sb.bind(new InetSocketAddress(port)); String group = "230.0.0.1"; InetSocketAddress groupAddress = new InetSocketAddress(group, port); cb.setOption("networkInterface", iface); cb.setOption("reuseAddress", true); DatagramChannel cc = (DatagramChannel) cb.bind(new InetSocketAddress(port)); assertTrue(cc.joinGroup(groupAddress, iface).awaitUninterruptibly().isSuccess()); assertTrue(sc.write(ChannelBuffers.wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess()); assertTrue(mhandler.await()); assertTrue(sc.write(ChannelBuffers.wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess()); // leave the group assertTrue(cc.leaveGroup(groupAddress, iface).awaitUninterruptibly().isSuccess()); // sleep a second to make sure we left the group Thread.sleep(1000); // we should not receive a message anymore as we left the group before assertTrue(sc.write(ChannelBuffers.wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess()); sc.close().awaitUninterruptibly(); cc.close().awaitUninterruptibly(); } private final class MulticastTestHandler extends SimpleChannelUpstreamHandler { private final CountDownLatch latch = new CountDownLatch(1); private boolean done = false; private volatile boolean fail = false; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { super.messageReceived(ctx, e); if (done) { fail = true; } Assert.assertEquals(1,((ChannelBuffer)e.getMessage()).readInt()); latch.countDown(); // mark the handler as done as we only are supposed to receive one message done = true; } public boolean await() throws Exception { boolean success = latch.await(10, TimeUnit.SECONDS); if (fail) { // fail if we receive an message after we are done Assert.fail(); } return success; } } }
testsuite/src/test/java/io/netty/testsuite/transport/socket/AbstractDatagramMulticastTest.java
/* * Copyright 2011 The Netty Project * * The Netty Project 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.netty.testsuite.transport.socket; import static org.junit.Assert.assertTrue; import io.netty.bootstrap.ConnectionlessBootstrap; import io.netty.buffer.ChannelBuffer; import io.netty.buffer.ChannelBuffers; import io.netty.channel.Channel; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.MessageEvent; import io.netty.channel.SimpleChannelUpstreamHandler; import io.netty.channel.socket.DatagramChannel; import io.netty.channel.socket.DatagramChannelFactory; import io.netty.testsuite.util.TestUtils; import io.netty.util.internal.ExecutorUtil; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; public abstract class AbstractDatagramMulticastTest { private static ExecutorService executor; @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract DatagramChannelFactory newServerSocketChannelFactory(Executor executor); protected abstract DatagramChannelFactory newClientSocketChannelFactory(Executor executor); @Test public void testMulticast() throws Throwable { ConnectionlessBootstrap sb = new ConnectionlessBootstrap(newServerSocketChannelFactory(executor)); ConnectionlessBootstrap cb = new ConnectionlessBootstrap(newClientSocketChannelFactory(executor)); MulticastTestHandler mhandler = new MulticastTestHandler(); cb.getPipeline().addFirst("handler", mhandler); sb.getPipeline().addFirst("handler", new SimpleChannelUpstreamHandler()); int port = TestUtils.getFreePort(); NetworkInterface iface = NetworkInterface.getNetworkInterfaces().nextElement(); sb.setOption("networkInterface", iface); sb.setOption("reuseAddress", true); Channel sc = sb.bind(new InetSocketAddress(port)); String group = "230.0.0.1"; InetSocketAddress groupAddress = new InetSocketAddress(group, port); cb.setOption("networkInterface", iface); cb.setOption("reuseAddress", true); DatagramChannel cc = (DatagramChannel) cb.bind(new InetSocketAddress(port)); assertTrue(cc.joinGroup(groupAddress, iface).awaitUninterruptibly().isSuccess()); assertTrue(sc.write(ChannelBuffers.wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess()); assertTrue(mhandler.await()); assertTrue(sc.write(ChannelBuffers.wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess()); // leave the group assertTrue(cc.leaveGroup(groupAddress, iface).awaitUninterruptibly().isSuccess()); // sleep a second to make sure we left the group Thread.sleep(1000); // we should not receive a message anymore as we left the group before assertTrue(sc.write(ChannelBuffers.wrapInt(1), groupAddress).awaitUninterruptibly().isSuccess()); sc.close().awaitUninterruptibly(); cc.close().awaitUninterruptibly(); } private final class MulticastTestHandler extends SimpleChannelUpstreamHandler { private final CountDownLatch latch = new CountDownLatch(1); private boolean done = false; private volatile boolean fail = false; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { super.messageReceived(ctx, e); if (done) { fail = true; } Assert.assertEquals(1,((ChannelBuffer)e.getMessage()).readInt()); latch.countDown(); // mark the handler as done as we only are supposed to receive one message done = true; } public boolean await() throws Exception { boolean success = latch.await(10, TimeUnit.SECONDS); if (fail) { // fail if we receive an message after we are done Assert.fail(); } return success; } } }
Make sure multicast tests pass on all os'es
testsuite/src/test/java/io/netty/testsuite/transport/socket/AbstractDatagramMulticastTest.java
Make sure multicast tests pass on all os'es
<ide><path>estsuite/src/test/java/io/netty/testsuite/transport/socket/AbstractDatagramMulticastTest.java <ide> import io.netty.testsuite.util.TestUtils; <ide> import io.netty.util.internal.ExecutorUtil; <ide> <add>import java.net.InetAddress; <ide> import java.net.InetSocketAddress; <ide> import java.net.NetworkInterface; <ide> import java.util.concurrent.CountDownLatch; <ide> <ide> int port = TestUtils.getFreePort(); <ide> <del> NetworkInterface iface = NetworkInterface.getNetworkInterfaces().nextElement(); <add> NetworkInterface iface = NetworkInterface.getByInetAddress(InetAddress.getLocalHost()); <add> <add> // check if the NetworkInterface is null, this is the case on my ubuntu dev machine but not on osx and windows. <add> // if so fail back the the first interface <add> if (iface == null) { <add> // use nextElement() as NetWorkInterface.getByIndex(0) returns null <add> iface = NetworkInterface.getNetworkInterfaces().nextElement(); <add> } <ide> sb.setOption("networkInterface", iface); <ide> sb.setOption("reuseAddress", true); <ide>
Java
unlicense
db5fc15363432b11f40208a6b18034cf83248418
0
ktams/CV-Navi,ktams/CV-Navi
/* * KlarTextUI.java * * Created on 20.01.2009, 17:34:06 */ package my.KlarText; import java.awt.Container; import java.awt.Cursor; import java.awt.Dialog.ModalExclusionType; import java.awt.Dimension; import java.awt.Frame; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import static javax.xml.bind.DatatypeConverter.printHexBinary; /** * * @author ktams */ // Konstanten definieren, die auch in switch-Anweisungen funktionieren ! // Etwas umständlich, aber sonst müssen alle switch-Anweisungen, // die KTUI.Decoder verwenden auf "if-then-else-if..." umgeschrieben werden :( // // Zuerst die Definition der Konstanten (nur hier stehen Zahlen für Menu und switch-Anweisungen !!!) // Erster Block ist für das Auswahlmenü: // Nur fortlaufende Nummern, beginnend mit 0 erlaubt // Die Nummer ist der Index in der Auswahlliste! // Das wird beim Programmstart als Erstes auf Plausibilität überprüft ! interface c { public static final int tLOK = 0; public static final int LD_G30 = 1; public static final int LD_G31 = 2; public static final int LD_W32 = 3; public static final int LD_W32_2 = 4; public static final int LD_G32 = 5; public static final int LD_G32_2 = 6; public static final int LD_W33 = 7; public static final int LD_G33 = 8; public static final int LD_G34 = 9; public static final int LD_G31Plus = 10; public static final int LD_G33Plus = 11; public static final int LD_G34Plus = 12; public static final int LD_G36Plus = 13; public static final int LINE_1 = 14; public static final int tFD = 15; public static final int FD_R = 16; public static final int FD_R2 = 17; public static final int FD_R_ex = 18; public static final int FD_M = 19; public static final int FD_XL = 20; public static final int FD_LED = 21; public static final int LINE_2 = 22; public static final int tZUB = 23; public static final int WD_34 = 24; public static final int WD_34_2 = 25; public static final int SD_34 = 26; public static final int SD_34_2 = 27; public static final int MultiDecoder = 28; public static final int LINE_3 = 29; public static final int tOTHER = 30; public static final int MC = 31; // MasterControl/RedBox public static final int B_4 = 32; public static final int BiDi_B = 33; public static final int WIB_30 = 34; // special numbers (used in SaveOpenDialog) public static final int MC_WR = 196; // special handling of MC config writes public static final int M3 = 197; // M3 uid/sid Liste public static final int KENN = 198; // (Motor-)Kennlinie public static final int HEX = 199; // Firmware public static final int TXT = 200; // Firmware // MC-Konstanten: public static final int MAX_SYSWRITES = 11; // #zu schreibende Variablen für ein Restore der Basiseinstellungen (ohne Listen) public static final int MAX_LOCS = 250; // Lokliste [0-249] public static final int MAX_TRACTIONS = 150; // Tracktionsliste [0..149] public static final int MAX_M3_ENTRIES = 512; // M3UID-SID-Pairs [0..511] public static final int MAX_LOC_NAME_LENGTH = 11; // maximum length of loco name // Zubehoerdecoder public static final int MAX_MM1_ACCMOD = 255; // 255 Module[0..254] =^= addr[1-1020] public static final int MAX_DCC_ACCMOD = 510; // 510 Module[0..509] "^° addr[1-2040] // Zentralen public static final int cuOpenDCC = 0; public static final int cuIntellibox1 = 1; public static final int cuMasterControl = 2; // Status public static final int cuPowerUnknown = -1; public static final int cuPowerOff = 0; public static final int cuPowerOn = 1; // S88 public static final int maxS88 = 52; // MessageBoxErrorCodes public static final int mbRDcancel = 1; public static final int mbWRcancel = 2; public static final int mbRDtimeout = 3; public static final int mbWRtimeout = 4; public static final int mbRDtooShort = 5; public static final int mbMCRDtimeout = 6; public static final int mbMCRDcommitErr = 7; public static final int mbMCWRtimeout = 8; public static final int mbRDverify = 9; // public static final long MIN_MC_XFUNCS_VERSION = 0x01040666; // 1.4.6f public static final long MIN_MC_XM3SID_VERSION = 0x01040762; // 1.4.7b public static final long MIN_MC_SO999_VERSION = 0x01040863; // 1.4.8c // other public static final int MAX_CV = 1024; public static final int MAX_M3_SID = 16383; public static final String ERR_PROBLEM_LEFT = "<- Problem !"; public static final String TamsFirmwareURL = "http://tams-online.de/epages/642f1858-c39b-4b7d-af86-f6a1feaca0e4.sf/de_DE/?ObjectPath=/Shops/642f1858-c39b-4b7d-af86-f6a1feaca0e4/Categories/Download1/Firmware"; } // Jetzt die Records mit und zu den Konstanten enum decoderList { // const menuIdx, selectable, german text, english (if different) tLOK (c.tLOK, false, "Lok-Decoder", "Loco-Decoder"), LD_G30 (c.LD_G30, true, " LD-G-30",""), LD_G31 (c.LD_G31, true, " LD-G-31",""), LD_W32 (c.LD_W32, true, " LD-W-32",""), LD_W32_2 (c.LD_W32_2, true, " LD-W-32.2",""), LD_G32 (c.LD_G32, true, " LD-G-32",""), LD_G32_2 (c.LD_G32_2, true, " LD-G-32.2",""), LD_W33 (c.LD_W33, true, " LD-W-33",""), LD_G33 (c.LD_G33, true, " LD-G-33",""), LD_G34 (c.LD_G34, true, " LD-G-34",""), LD_G31Plus (c.LD_G31Plus, true, " LD-G-31Plus",""), LD_G33Plus (c.LD_G33Plus, true, " LD-G-33Plus",""), LD_G34Plus (c.LD_G34Plus, true, " LD-G-34Plus",""), LD_G36Plus (c.LD_G36Plus, true, " LD-G-36Plus",""), line_1 (c.LINE_1, false, "____________",""), tFD (c.tFD, false, "Funktions-Dekoder","Function-Decoder"), FD_R (c.FD_R, true, " FD-R basic",""), FD_R2 (c.FD_R2, true, " FD-R basic 2",""), FD_R_ex (c.FD_R_ex,true, " FD-R extended",""), FD_M (c.FD_M, true, " FD-M",""), FD_XL (c.FD_XL, true, " FD-XL",""), FD_LED (c.FD_LED, true, " FD-LED",""), line_2 (c.LINE_2, false, "____________",""), tZUB (c.tZUB, false, "Zubehör-Decoder","Accessory-Decoder"), WD_34 (c.WD_34, true, " WD-34",""), WD_34_2 (c.WD_34_2, true, " WD-34.2",""), SD_34 (c.SD_34, true, " SD-34",""), SD_34_2 (c.SD_34_2, true, " SD-34.2",""), MultiDecoder (c.MultiDecoder, true, " MultiDecoder",""), line_3 (c.LINE_3, false, "____________",""), tOTHER (c.tOTHER, false, "Sonstiges","Other"), MC (c.MC, true, " MasterControl/RedBox",""), B_4 (c.B_4, true, " B-4",""), BiDi_B (c.BiDi_B, true, " BiDi-Booster",""), WIB_30 (c.WIB_30, true, " WIB-30er",""); private final int idx; private final Boolean selectable; private final String menuTextGer; private final String menuTextEng; decoderList(int idx, Boolean sel, String textGer, String textEng) { this.idx = idx; this.selectable = sel; this.menuTextGer = textGer; this.menuTextEng = textEng; } public int getIdx() {return idx;} public Boolean isSelectable() {return selectable;} public String getMenutextGer() { return menuTextGer; } public String getMenutextEng() { return menuTextEng.isEmpty() ? menuTextGer : menuTextEng; } } public class KlarTextUI extends javax.swing.JFrame { /** Creates new form KlarTextUI */ public int gsVersionMayor = 2; // Version 2.8 public int gsVersionMinor = 8; // Version 2.8 public JFrame frameInstanceDEVICE = null; public JFrame frameInstanceOPTIONS = null; public JFrame frameInstanceINFO = null; public int Decoder = 0; // better name would be Device, because MC and B4 are also handled public int currSelection = 0; public boolean bSpracheDE = true; //true -> deutsch, false -> englisch public static int debugLevel = 0; public static boolean debugOffline = false; public static boolean forceTrackPowerOn = false; public static int debugDummyData = 0; private static int userTimer1 = -1; private static int userTimer2 = -1; private static int userTimer3 = -1; private static int userTimerRetries = -1; public static int userTimerFwUp = 150; public static int MCtimer1 = -1; public static int MCtimer2 = -1; public static int timer1 = -1; public static int timer2 = -1; public static int timer3 = -1; public static int timerRetries = -1; public static boolean updateAlwaysVisible = false; public static boolean skipCV17 = false; public static boolean skipCV18 = false; private static int trackStatus = c.cuPowerUnknown; private boolean bReadStatusBin = false; public static boolean rs232_or_rb_usb_2 = false; public static boolean rs232_mode_was_forced = false; // Globale Variablen, die nur einmal eingelesen werden sollten // gs = GlobalSetting // Die ersten 3 Variablen sind static, da sie auch in main (static context) verwendet werden static String gsConfigDirectory = System.getProperty("user.home") + "/.CV-Navi/"; static String gsConfigFilename = System.getProperty("user.home") + "/.CV-Navi/" + "CV-Navi.xml"; static String gsConfigComment = "Tams CV Navi"; public String gsZentrale = "MasterControl"; private int lcZentrale = 2; private TwoWaySerialComm KTUICom = null; private TwoWaySerialComm ExternalCom = null; private Boolean bVerifyZentraleInProgress = false; private Timer timer = null; public static Boolean bZentraleVerified = false; public String fwVersion = null; public static Boolean bUseXfuncs = false; // MC >= 1.4.6f ; OpenDCC >= 23.08 ; IB >= 2.000 public static Boolean bUseXm3sid = false; // MC >= 1.4.7b public static Boolean bUseSo999 = false; // MC >= 1.4.8c public String gsSchnittstelle = "noCom"; public int gsBaudRate = -1 ; public boolean gsRtsCts = true; public String gsLastMcConfLoad = "NoData" ; public String gsLastMcConfSave = "NoData" ; public int gsDecoderIndex = -1 ; public String gsLookAndFeel = "Nothing" ; public String gsSaveOpenDirectory ; public String gsSaveOpenFilename ; public String gsSaveOpenKennDirectory ; public String gsSaveOpenKennFilename ; public String gsSaveOpenMcDirectory ; public String gsSaveOpenMcFilename ; public String gsSaveOpenM3Directory ; public String gsSaveOpenM3Filename ; public String gsOpenFirmwareDirectory ; public String gsOpenFirmwareFilename ; // public String gsReadBuffer; public Boolean lastSaveOpenDialogWasCancel; public Dimension SODlocalSize ; public Point mainWindowLocation; public boolean bGotoUpdate; public enum ModeZentrale { Halted, PwrOn, PwrOff, DCCprogram, Reset, UNKNOWN }; public enum MZ { UNKNOWN, STOP, GO }; public ModeZentrale gModeZentrale = ModeZentrale.UNKNOWN ; public MZ gMZvorAktion = MZ.UNKNOWN ; private ResourceBundle bundle; private int numS88 = 0; public KlarTextUI() { this.lastSaveOpenDialogWasCancel = false; mainWindowLocation = new Point(); ImageIcon i = new ImageIcon(getClass().getResource("/main.gif")); this.setIconImage(i.getImage()); initComponents(); jDecoderChooser.setSelectedIndex(c.MC); jLabelProgVersion.setText("Version " + gsVersionMayor + "." + gsVersionMinor); setLocationRelativeTo(null); fillMenuSelection(); bundle = java.util.ResourceBundle.getBundle("my.KlarText/Bundle"); if( debugLevel >= 3 ) { for(decoderList co : decoderList.values()) { System.out.printf("decoderList[%2d] [%2d] (%s) %10s Text %-35s %s\n", co.ordinal(), co.getIdx(), co.isSelectable()?"X":" ", co, co.getMenutextGer(), co.getMenutextEng()); } } } public void setZentrale( int newZentrale ) { switch (newZentrale) { case c.cuOpenDCC: lcZentrale = newZentrale; gsZentrale = "OpenDCC"; break; case c.cuIntellibox1: lcZentrale = newZentrale; gsZentrale = "Intellibox"; break; default: lcZentrale = c.cuMasterControl ; gsZentrale = "MasterControl"; } } public void setZentrale( String newZentrale ) { switch (newZentrale) { case "OpenDCC": lcZentrale = c.cuOpenDCC; gsZentrale = newZentrale; break; case "Intellibox": lcZentrale = c.cuIntellibox1; gsZentrale = newZentrale; break; default: // all other cases lcZentrale = c.cuMasterControl ; gsZentrale = "MasterControl"; break; } } public int getZentrale() { return lcZentrale; } public int getDecoderChooser() { return(jDecoderChooser.getSelectedIndex()); } public void setDecoderChooser( int n ) { if( n >= 0 ) jDecoderChooser.setSelectedIndex(n); } public boolean setModeZentrale( String mode ) { switch(mode) { // "Pwr off", "Halted!", "Pwr on", "DCC program" oder "RESET" case "Pwr on": gModeZentrale = ModeZentrale.PwrOn ; break; case "Halted!": gModeZentrale = ModeZentrale.Halted ; break; case "Pwr off": gModeZentrale = ModeZentrale.PwrOff ; break; case "DCC program": gModeZentrale = ModeZentrale.DCCprogram ; break; case "RESET": gModeZentrale = ModeZentrale.Reset ; break; default: System.out.println("setModeZentrale UNEXPECTED mode="+mode); return false; } return true; } public ModeZentrale getModeZentrale() { return gModeZentrale; } public MZ getMZ() { switch( gModeZentrale ) { case Halted: case PwrOn: return MZ.GO; case PwrOff: case DCCprogram: case Reset : return MZ.STOP; case UNKNOWN: default: return MZ.UNKNOWN; } } public String getModeZentraleAsStringLong() { switch( gModeZentrale ) { case Halted: return"Halted"; case PwrOn: return"PwrOn"; case PwrOff: return"PwrOff"; case DCCprogram: return"DCCprogram"; case Reset : return"Reset"; case UNKNOWN: default: return "???"; } } public String getModeZentraleAsStringShort() { switch( gModeZentrale ) { case Halted: case PwrOn: return"GO"; case PwrOff: case DCCprogram: case Reset : return"STOP"; case UNKNOWN: default: return "???"; } } public String getMenutext( decoderList dl ) { if( dl == null ) { return "CV-Navi"; } else { if( bSpracheDE ) { return dl.getMenutextGer(); } else { return dl.getMenutextEng(); } } } public int getNumS88() { return numS88; } public void setNumS88( int num ) { if( checkNumRange( num, 0, c.maxS88 ) ) { numS88 = num; } } public void mbTest( Container cont, Boolean modal ) { System.out.println("mbTest" ); MsgBox messageBox = new MsgBox( (Frame) this.getParent(), modal, cont); messageBox.jLabel1.setText("Test!"); messageBox.jLabel2.setText("Decoder: "+Decoder+" SS: " + gsSchnittstelle); messageBox.jLabel3.setText("Test."); messageBox.setVisible(true); } public void mbGeneric( Container cont, String s1 ) { mbGeneric( cont, s1, null, null, 0, true ); } public void mbGeneric( Container cont, String s1, Boolean modal ) { mbGeneric( cont, s1, null, null, 0, modal ); } public void mbGeneric( Container cont, String s1, int seconds ) { mbGeneric( cont, s1, null, null, seconds, true ); } public void mbGeneric( Container cont, String s1, int seconds, Boolean modal ) { mbGeneric( cont, s1, null, null, seconds, modal ); } public void mbGeneric( Container cont, String s1, String s2 ) { mbGeneric( cont, s1, s2, null, true ); } public void mbGeneric( Container cont, String s1, String s2, Boolean modal ) { mbGeneric( cont, s1, s2, null, modal ); } public void mbGeneric( Container cont, String s1, String s2, int seconds ) { mbGeneric( cont, s1, s2, null, seconds, true ); } public void mbGeneric( Container cont, String s1, String s2, int seconds, Boolean modal ) { mbGeneric( cont, s1, s2, null, seconds, modal ); } public void mbGeneric( Container cont, String s1, String s2, String s3 ) { mbGeneric( cont, s1, s2, s3, 0, true ); } public void mbGeneric( Container cont, String s1, String s2, String s3, Boolean modal ) { mbGeneric( cont, s1, s2, s3, 0, modal ); } public void mbGeneric( Container cont, String s1, String s2, String s3, int seconds ) { mbGeneric( cont, s1, s2, s3, seconds, true ); } public void mbGeneric( Container cont, String s1, String s2, String s3, int seconds, Boolean modal ) { // System.out.println("mbGeneric seconds="+seconds+" modal="+modal+" Container name="+c.getName()+" string=" +c.toString()); MsgBox messageBox = new MsgBox( (Frame) this.getParent(), modal, cont); messageBox.jLabel1.setText(s1==null?"":s1); messageBox.jLabel2.setText(s2==null?"":s2); messageBox.jLabel3.setText(s3==null?"":s3); messageBox.setCountdown(seconds); messageBox.pack(); messageBox.setLocationRelativeTo(cont); messageBox.setVisible(true); } public void mbVerifyXVer(Container cont, String verInfo, Boolean mismatch) { String dbgOptions =""; if( debugLevel > 0 ) { dbgOptions = "(Xfuncs="+bUseXfuncs+" Xm3sid="+bUseXm3sid+")"; } if( mismatch ) { mbGeneric(cont, bundle.getString("Configrationmismatch"), bundle.getString("Configured")+gsZentrale, bundle.getString("Detected")+verInfo+" "+dbgOptions, 0, true); } else { if( debugLevel > 0 ) { mbGeneric(cont, "Information", verInfo, "OK "+dbgOptions, 5, false); } } } public void mbNotAvailable( Container cont, String s3) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information"); messageBox.jLabel2.setText(bundle.getString("notavailable")); messageBox.jLabel3.setText(s3==null?"":s3); messageBox.setVisible(true); } public void mbDeviceConnectProblem( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Openfailed")); messageBox.setVisible(true); } public void mbDeviceConnectProblemOffline( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Openfailed") + "-> Offline Modus"); messageBox.setCountdown(5); messageBox.setVisible(true); } public void mbDeviceDisconnectProblem( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Closefailed")); messageBox.setVisible(true); } public void mbDeviceReadProblem( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Readfailed")); messageBox.setVisible(true); } public void mbDeviceWriteProblem( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Writefailed")); messageBox.setVisible(true); } public void mbDeviceOwned( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText("Interface " + gsSchnittstelle + bundle.getString("busy")); messageBox.setVisible(true); } public void mbDeviceNotSupported( Container cont, int seconds ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Hinweis")); messageBox.jLabel2.setText(bundle.getString("notsupported")); messageBox.jLabel3.setText(""); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbUpdateWriteSuccess( Container cont, int block ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Hinweis")); messageBox.jLabel2.setText(bundle.getString("successful")); messageBox.jLabel3.setText("" + block + " " +bundle.getString("transferred")); messageBox.setCountdown(5); messageBox.setVisible(true); } public void mbUpdateWriteError( Container cont, char c ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont ); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Unexpected") + " " + c + " " + bundle.getString("empfangen")); messageBox.jLabel3.setText(bundle.getString("restartupdate")); messageBox.setVisible(true); } public void mbUpdateWriteError( Container cont, String s ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont ); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Unexpected") + " " + s + " " + bundle.getString("empfangen")); messageBox.jLabel3.setText(bundle.getString("restartupdate")); messageBox.setVisible(true); } public void mbUpdateReadAnswerError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Noanswer")); messageBox.jLabel3.setText(bundle.getString("Updatecancelled")); messageBox.setVisible(true); } public void mbConfigReadSuccess( Container cont ) { mbConfigReadSuccess( cont, 0); } public void mbConfigReadSuccess( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information:"); messageBox.jLabel2.setText(bundle.getString("successfullyread")); messageBox.jLabel3.setText(""); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigReadAbort( Container cont ) { mbConfigReadAbort( cont, 0); } public void mbConfigReadAbort(Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Problem!"); messageBox.jLabel2.setText(bundle.getString("readaborted")); messageBox.jLabel3.setText(bundle.getString("notprocessed")); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigReadCancelled( Container cont ) { mbConfigReadCancelled( cont, 0); } public void mbConfigReadCancelled( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information:"); messageBox.jLabel2.setText(bundle.getString("readaborted")); messageBox.jLabel3.setText(bundle.getString("incomplete")); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbRWCancelled( Container cont ) { mbRWCancelled( cont, 0); } public void mbRWCancelled( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information:"); messageBox.jLabel2.setText(bundle.getString("readwritecancelled")); messageBox.jLabel3.setText(bundle.getString("incomplete")); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigWriteCancelled( Container cont ) { mbConfigWriteCancelled( cont, 0); } public void mbConfigWriteCancelled( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information:"); messageBox.jLabel2.setText(bundle.getString("readwritecancelled")); messageBox.jLabel3.setText(bundle.getString("incomplete")); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigWriteSuccess( Container cont ) { mbConfigWriteSuccess( cont, 0); } public void mbConfigWriteSuccess( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information"); messageBox.jLabel2.setText(bundle.getString("successfullywritten")); messageBox.jLabel3.setText(""); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigWriteSuccessMcWithProblems( Container cont, int errBits ) { if( errBits == 0 ) { mbConfigWriteSuccess( cont ); return; } MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if( bSpracheDE) { messageBox.jLabel1.setText("Schreiben erfolgreich."); messageBox.jLabel2.setText("ACHTUNG! Einige Eingaben waren falsch und wurden korrigiert:"); String sFehler = "("; if((errBits & 0x0007) != 0 ) sFehler += "Adressfehler: "; if((errBits & 0x0001) == 0x0001 ){ sFehler += "DCC"; if((errBits & 0x0006) != 0) { sFehler += ", "; } } if((errBits & 0x0002) == 0x0002 ) { sFehler += "MM"; if((errBits & 0x0004) != 0) { sFehler += ", "; } } if((errBits & 0x0004) == 0x0004 ) sFehler += "m3"; if(((errBits & 0x00F8) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0008) == 0x0008 ) sFehler += "Formatfehler"; if(((errBits & 0x00F0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0010) == 0x0010 ) sFehler += "Fahrstufenfehler"; if(((errBits & 0x00E0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0020) == 0x0020 ) sFehler += "Name zu lang"; if(((errBits & 0x00C0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0040) == 0x0040 ) sFehler += "Adressfehler Doppeltraktion"; if(((errBits & 0x0080) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0080) == 0x0080 ) sFehler += "Formatfehler Acc-Decoder"; sFehler += ")"; messageBox.jLabel3.setText(sFehler); } else { messageBox.jLabel1.setText("Configuration data successfully sent."); messageBox.jLabel2.setText("ATTENTION! Some data was corrected while writing:"); String sFehler = "("; if((errBits & 0x0007) != 0) sFehler += "loco address error: "; if((errBits & 0x0001) == 0x0001 ) { sFehler += "DCC"; if((errBits & 0x0006) != 0) { sFehler += ", "; } } if((errBits & 0x0002) == 0x0002 ) { sFehler += "MM"; if((errBits & 0x0004) != 0) { sFehler += ", "; } } if((errBits & 0x0004) == 0x0004 ) sFehler += "m3"; if(((errBits & 0x00F8) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0008) == 0x0008 ) sFehler += "format error"; if(((errBits & 0x00F0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0010) == 0x0010 ) sFehler += "speed step error"; if(((errBits & 0x00E0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0020) == 0x0020 ) sFehler += "name too long"; if(((errBits & 0x00C0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0040) == 0x0040 ) sFehler += "traction address error"; if(((errBits & 0x0080) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0080) == 0x0080 ) sFehler += "accessory format error"; sFehler += ")"; messageBox.jLabel3.setText(sFehler); } messageBox.setVisible(true); } public void mbConfigWriteError( Container cont ) { mbConfigWriteError( cont, "", 0); } public void mbConfigWriteError( Container cont, String sError ) { mbConfigWriteError( cont, sError, 0); } public void mbConfigWriteError( Container cont, String sError, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Errorwriting")); if( (sError != null) && (sError.length() > 0 ) ) { messageBox.jLabel3.setText(sError); } else { messageBox.jLabel3.setText(""); } messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbM3TooMany( Container cont ) { mbGeneric( cont, "Problem", bundle.getString("UIDSIDPaare"), bundle.getString("MaxAnz")+c.MAX_M3_ENTRIES, 0, true); return; } public void mbTableCheckOK( Container cont, boolean repair, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information"); if( repair ) { messageBox.jLabel2.setText(bundle.getString("TabellenreparaturOK")); } else { messageBox.jLabel2.setText(bundle.getString("TablecheckedOK")); } messageBox.jLabel3.setText(""); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbTableCheck( Container cont, int errBits ) { mbTableCheck( cont, errBits, false, null ); return; } public void mbTableCheck( Container cont, int errBits, boolean repair ) { mbTableCheck( cont, errBits, repair, null ); return; } public void mbTableCheck( Container cont, int errBits, boolean repair, String sList ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if( bSpracheDE) { if( sList != null ) { messageBox.jLabel1.setText("Probleme in Zeile(n)"+sList+" festgestellt!"); } else { messageBox.jLabel1.setText("Probleme festgestellt!"); } if( repair ) messageBox.jLabel2.setText("ACHTUNG! Einige Eingaben waren falsch und wurden korrigiert:"); else messageBox.jLabel2.setText("ACHTUNG! Einige Eingaben sind falsch:"); String sFehler = "("; if((errBits & 0x0007) != 0 ) sFehler += "Adressfehler: "; if((errBits & 0x0001) == 0x0001 ){ sFehler += "DCC"; if((errBits & 0x0006) != 0) { sFehler += ", "; } } if((errBits & 0x0002) == 0x0002 ) { sFehler += "MM"; if((errBits & 0x0004) != 0) { sFehler += ", "; } } if((errBits & 0x0004) == 0x0004 ) sFehler += "m3"; if(((errBits & 0x00F8) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0008) == 0x0008 ) sFehler += "Formatfehler"; if((errBits & 0x0010) != 0) { if(sFehler.length() > 1) sFehler += " ; "; sFehler += "Fahrstufenfehler"; } if((errBits & 0x0020) != 0) { if(sFehler.length() > 1) sFehler += " ; "; sFehler += "Name zu lang"; } if((errBits & 0x0040) != 0) { if(sFehler.length() > 1) sFehler += " ; "; sFehler += "Adressfehler Doppeltraktion"; } if((errBits & 0x0080) != 0) { if(sFehler.length() > 1) sFehler += " ; "; sFehler += "Formatfehler Acc-Decoder"; } sFehler += ")"; messageBox.jLabel3.setText(sFehler); } else { if( sList != null ) { messageBox.jLabel1.setText("Problems in line(s)"+sList+" detected!"); } else { messageBox.jLabel1.setText("Problems detected!"); } if( repair ) messageBox.jLabel2.setText("ATTENTION! Some data was corrected:"); else messageBox.jLabel2.setText("ATTENTION! Some data is wrong:"); String sFehler = "("; if((errBits & 0x0007) != 0) sFehler += "loco address error: "; if((errBits & 0x0001) == 0x0001 ) { sFehler += "DCC"; if((errBits & 0x0006) != 0) { sFehler += ", "; } } if((errBits & 0x0002) == 0x0002 ) { sFehler += "MM"; if((errBits & 0x0004) != 0) { sFehler += ", "; } } if((errBits & 0x0004) == 0x0004 ) sFehler += "m3"; if(((errBits & 0x00F8) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0008) == 0x0008 ) sFehler += "format error"; if(((errBits & 0x00F0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0010) == 0x0010 ) sFehler += "speed step error"; if(((errBits & 0x00E0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0020) == 0x0020 ) sFehler += "name too long"; if(((errBits & 0x00C0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0040) == 0x0040 ) sFehler += "traction address error"; if(((errBits & 0x0080) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0080) == 0x0080 ) sFehler += "accessory format error"; sFehler += ")"; messageBox.jLabel3.setText(sFehler); } ModalExclusionType MET = messageBox.getModalExclusionType(); String t = "" + MET ; System.out.println("MET = ["+t+"]"); messageBox.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE); messageBox.setVisible(true); } public void mbFileNotFound( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Filenotfound")); messageBox.setVisible(true); } public void mbFileNotFound( Container cont, String name) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Filenotfound") + ": "+name); messageBox.setVisible(true); } public void mbFileOpenError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Filenotopenend")); messageBox.setVisible(true); } public void mbFileOpenError( Container cont, String name) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Filenotopenend") + ": "+name); messageBox.setVisible(true); } public void mbFileWriteError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Problemswriting")); messageBox.setVisible(true); } public void mbFileReadError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Problemsreading")); messageBox.setVisible(true); } public void mbFileHexFormatError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("noHEX")); messageBox.jLabel3.setText(bundle.getString("chooseHEX")); messageBox.setVisible(true); } public void mbFileReadBeginError( Container cont, String begin) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("notstarting") + begin ); messageBox.setVisible(true); } public void mbTimeout( Container cont ) { mbTimeout( cont, 0 ); } public void mbTimeout( Container cont, int errCode ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if(bSpracheDE) { messageBox.jLabel1.setText("Achtung!"); switch( errCode ) { case c.mbRDtimeout: messageBox.jLabel2.setText("Zentrale meldet Timeout beim Lesen!"); messageBox.jLabel3.setText("Auslesen abgebrochen."); break; case c.mbWRtimeout: messageBox.jLabel2.setText("Zentrale meldet Timeout beim Schreiben!"); messageBox.jLabel3.setText("Schreiben abgebrochen."); break; case c.mbMCRDtimeout: messageBox.jLabel2.setText("Timeout beim Lesen aus der Zentrale!"); messageBox.jLabel3.setText("Auslesen abgebrochen."); break; case c.mbRDtooShort: messageBox.jLabel2.setText("Antwort zu kurz beim Lesen aus der Zentrale!"); messageBox.jLabel3.setText("Auslesen abgebrochen."); break; case c.mbMCRDcommitErr: messageBox.jLabel2.setText("Timeout beim Warten auf eine Antwort der Zentrale!"); messageBox.jLabel3.setText("Bitte Verbindung überprüfen."); break; case c.mbMCWRtimeout: messageBox.jLabel2.setText("Timeout beim Schreiben in die Zentrale!"); messageBox.jLabel3.setText("Schreiben abgebrochen."); break; case c.mbRDverify: messageBox.jLabel2.setText("Timeout beim Verifizieren der Zentrale!"); messageBox.jLabel3.setText(""); break; default: messageBox.jLabel2.setText("Timeout aufgetreten!"); messageBox.jLabel3.setText(""); } } else { messageBox.jLabel1.setText("WARNING!"); switch( errCode ) { case c.mbRDtimeout: messageBox.jLabel2.setText("Control unit reports timeout on read!"); messageBox.jLabel3.setText("read cancelled"); break; case c.mbWRtimeout: messageBox.jLabel2.setText("Control unit reports timeout on write!"); messageBox.jLabel3.setText("write cancelled"); break; case c.mbMCRDtimeout: messageBox.jLabel2.setText("Timeout reading data from control unit!"); messageBox.jLabel3.setText("read cancelled"); break; case c.mbRDtooShort: messageBox.jLabel2.setText("Answer too short while reading data from control unit!"); messageBox.jLabel3.setText("read cancelled"); break; case c.mbMCRDcommitErr: messageBox.jLabel2.setText("Timeout waiting for an answer from control unit!"); messageBox.jLabel3.setText("Please check connection."); break; case c.mbMCWRtimeout: messageBox.jLabel2.setText("Timeout writing data to control unit!"); messageBox.jLabel3.setText("write cancelled"); break; case c.mbRDverify: messageBox.jLabel2.setText("Timeout verifying control unit!"); messageBox.jLabel3.setText(""); break; default: messageBox.jLabel2.setText("Timeout occured!"); messageBox.jLabel3.setText(""); } } messageBox.setVisible(true); } public void mbTimeoutMcUpdStart( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if(bSpracheDE) { messageBox.jLabel1.setText("keine Verbindung zur MasterControl!"); messageBox.jLabel2.setText("Bitte Verbindung überprüfen und"); messageBox.jLabel3.setText("MC in Update-Modus setzen (Stop + GO beim Einschalten drücken)!"); } else { messageBox.jLabel1.setText("No connection to MasterControl!"); messageBox.jLabel2.setText("Please check connectivity and "); messageBox.jLabel3.setText("set MC in update mode: Press Stop + GO while switching power on!"); } messageBox.setVisible(true); } public void mbEnablePower( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if(bSpracheDE) { messageBox.jLabel1.setText("Schienenspannung ist aus!"); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText("Bitte Schienenspannung einschalten und erneut probieren"); } else { messageBox.jLabel1.setText("Track Power is off!"); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText("Please enable Power and try again"); } messageBox.setVisible(true); } public void mbNoTams( Container cont ) { mbNoTams( cont, 0 ); } public void mbNoTams( Container cont, int errCode ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if(bSpracheDE) { messageBox.jLabel1.setText("Achtung!"); messageBox.jLabel2.setText("Dies ist kein Tams Decoder!"); switch( errCode ) { case c.mbRDcancel: messageBox.jLabel3.setText("weiteres Auslesen abgebrochen."); break; case c.mbWRcancel: messageBox.jLabel3.setText("weiteres Schreiben abgebrochen."); break; default: messageBox.jLabel3.setText(""); } } else { messageBox.jLabel1.setText("WARNING!"); messageBox.jLabel2.setText("This is no Tams device!"); switch( errCode ) { case c.mbRDcancel: messageBox.jLabel3.setText("read cancelled"); break; case c.mbWRcancel: messageBox.jLabel3.setText("write cancelled"); break; default: messageBox.jLabel3.setText(""); } } messageBox.setVisible(true); } public void mbNoTamsMC( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Wrongcu") + gsZentrale + "\" "+bundle.getString("configured")); messageBox.jLabel3.setText(bundle.getString("PleaseSelectMC")); messageBox.setVisible(true); } public void mbNoS88modules( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Information")); messageBox.jLabel2.setText(bundle.getString("NoS88modules")); messageBox.jLabel3.setText(bundle.getString("SkipS88monitor")); messageBox.setVisible(true); } public void mbInvalidValue( Container cont, int cv, int value, String validValues ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText("CV# "+cv+bundle.getString("invalidvalue")+value); if( validValues.length() > 0) { messageBox.jLabel3.setText(bundle.getString("Validvalues")+validValues); } messageBox.setVisible(true); } public void mbValueTooSmall( Container cont ) { mbValueTooSmall( cont, 0, 0, false); } public void mbValueTooSmall( Container cont, int low, int high, boolean showRange ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valuetoosmall")); if(bSpracheDE) { if( showRange ) { messageBox.jLabel3.setText("Bitte einen Wert zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" eingeben."); } else { messageBox.jLabel3.setText("Bitte einen größeren Wert eingeben."); } } else { if( showRange ) { messageBox.jLabel3.setText("Please enter a value between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Please enter a higher value."); } } messageBox.setVisible(true); } public void mbValueTooBig( Container cont ) { mbValueTooBig( cont, 0, 0, false); } public void mbValueTooBig( Container cont, int low, int high, boolean showRange ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valuetoobig")); if(bSpracheDE) { if( showRange ) { messageBox.jLabel3.setText("Bitte einen Wert zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" eingeben."); } else { messageBox.jLabel3.setText("Bitte einen kleineren Wert eingeben."); } } else { if( showRange ) { messageBox.jLabel3.setText("Please enter a value between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Please enter a lower value."); } } messageBox.setVisible(true); } public void mbValueNaN( Container cont ) { mbValueNaN( cont, 0, 0, false); } public void mbValueNaN( Container cont, int low, int high, boolean showRange ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valueinvalid")); if(bSpracheDE) { if( showRange ) { messageBox.jLabel3.setText("Bitte einen Wert zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" eingeben."); } else { messageBox.jLabel3.setText("Bitte einen korrekten Wert eingeben."); } } else { if( showRange ) { messageBox.jLabel3.setText("Please use a value between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Please use a valid value."); } } messageBox.setVisible(true); } public void mbValueNaNcv( Container cont, int low, int high, int cv, boolean showRange ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valueinvalid")); if(bSpracheDE) { if( showRange ) { messageBox.jLabel3.setText("CV#"+cv+" muß einen Wert zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" haben."); } else { messageBox.jLabel3.setText("Bitte einen korrekten Wert für CV#"+cv+" eingeben."); } } else { if( showRange ) { messageBox.jLabel3.setText("CV#"+cv+" must have a value between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Please use a valid value for CV#"+cv); } } messageBox.setVisible(true); } public void mbValueConsist( Container cont, int low, int high ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valueinvalid")); if(bSpracheDE) { messageBox.jLabel3.setText("Gültige Werte für Consist-Adresse zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Valid consist address is between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } messageBox.setVisible(true); } public void mbAdr128MMonly( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); if(bSpracheDE) { messageBox.jLabel2.setText("Nur für MM."); messageBox.jLabel3.setText("Bei kurzen Adressen zwischen 128 und 255 reagiert der Decoder nur noch auf MM-Befehle!"); } else { messageBox.jLabel2.setText("Only for MM."); messageBox.jLabel3.setText("Short addresses between 128 and 255 are for MM protocol only!"); } messageBox.setVisible(true); } public void mbBlinkFrequenz( Container cont, int dauer, int pause, String eingabe ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); if(bSpracheDE) { // "Wert \""+jBlink_Pausezeit_1.getText()+"\" ungültig.", "Bitte einen Wert zwischen 0 und Blinkfrequenz minus 2xein eingeben." messageBox.jLabel2.setText("Eingabe \""+eingabe+"\" für Frequenz ist ungültig."); messageBox.jLabel3.setText("Bitte einen Wert zwischen "+((dauer*2)+pause)+" und 255 eingeben. ( Minimum = ( Blinkdauer("+dauer+") * 2 ) plus Pause("+pause+") )"); } else { messageBox.jLabel2.setText("Input \""+eingabe+"\" for frequency is invalid."); messageBox.jLabel3.setText("Please use a value between "+((dauer*2)+pause)+" and 255. ( min = ( onTime("+dauer+") * 2 ) plus pause("+pause+") ) "); } messageBox.pack(); // resize to fit contents before making visible ;) messageBox.setVisible(true); } public void mbBlinkEinschaltzeit( Container cont, int freq, int pause, String eingabe ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); if(bSpracheDE) { // "Wert \""+jBlink_Pausezeit_1.getText()+"\" ungültig.", "Bitte einen Wert zwischen 0 und Blinkfrequenz minus 2xein eingeben." messageBox.jLabel2.setText("Eingabe \""+eingabe+"\" für Einschaltzeit ist ungültig."); messageBox.jLabel3.setText("Bitte einen Wert zwischen 0 und "+((freq-pause)/2)+" eingeben. ( = ( Blinkfrequenz("+freq+") minus Pause("+pause+") geteilt durch 2 ) )"); } else { messageBox.jLabel2.setText("Input \""+eingabe+"\" for onTime is invalid."); messageBox.jLabel3.setText("Please use a value between 0 and "+((freq-pause)/2)+" ( = ( flash freqeuncy("+freq+") minus pause("+pause+") ) / 2 )"); } messageBox.pack(); // resize to fit contents before making visible ;) messageBox.setVisible(true); } public void mbBlinkPausezeit( Container cont, int freq, int dauer, String eingabe ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); if(bSpracheDE) { // "Wert \""+jBlink_Pausezeit_1.getText()+"\" ungültig.", "Bitte einen Wert zwischen 0 und Blinkfrequenz minus 2xein eingeben." messageBox.jLabel2.setText("Eingabe \""+eingabe+"\" für Pause ist ungültig."); messageBox.jLabel3.setText("Bitte einen Wert zwischen 0 und "+(freq-(2*dauer))+" eingeben. ( = Blinkfrequenz("+freq+") minus 2 * Einschaltdauer("+dauer+") )"); } else { messageBox.jLabel2.setText("Input \""+eingabe+"\" for pause is invalid."); messageBox.jLabel3.setText("Please use a value between 0 and "+(freq-(2*dauer))+" ( = flash freqeuncy("+freq+") minus 2 * OnTime("+dauer+") )"); } messageBox.setVisible(true); } public int yesNoResetFactoryDefault() { int dialogResult = -1; if(bSpracheDE) { Object[] options = { "Ja", "Nein" }; dialogResult = JOptionPane.showOptionDialog( this, "Zurücksetzen aller Werte auf Auslieferungszustand.\n\nSind Sie sicher?", "Warnung", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1] ); } else { Object[] options = { "Yes", "No" }; dialogResult = JOptionPane.showOptionDialog( this, "Reset all values to factory defaults.\n\nAre you sure?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1] ); } return dialogResult; } public int yesNoM3listSave() { int dialogResult = -1; if(bSpracheDE) { Object[] options = { "Ja", "Nein" }; dialogResult = JOptionPane.showOptionDialog( this, "M3 UID/SID-Liste wurde geändert.\n\nSoll die Liste gesichert werden?", "Warnung", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); } else { Object[] options = { "Yes", "No" }; dialogResult = JOptionPane.showOptionDialog( this, "M3 UID/SID list changed.\n\nDo you want to save?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); } return dialogResult; } // Checks public int checkTextFieldUnit( Container cont, JTextField textField, int minValue, int maxValue, int defValue, int unit, boolean show ) { int i = checkTextField( cont, textField, minValue, maxValue, defValue, show ); int j = (i/unit)*unit; if( i != j ) { textField.setText(Integer.toString(j)); } return j; } public int checkTextField( Container cont, JTextField textField, int minValue, int maxValue, int defValue, boolean show ) { int value; try { value = Integer.parseInt(textField.getText()); if(value < minValue) { if( show ) { mbValueTooSmall( cont, minValue, maxValue, true ); textField.grabFocus(); } value = minValue; textField.setText("" + value); } if(value > maxValue) { if( show ) { mbValueTooBig( cont, minValue, maxValue, true ); textField.grabFocus(); } value = maxValue; textField.setText("" + value); } } catch (NumberFormatException numberFormatException) { if( show ) { mbValueNaN( cont, minValue, maxValue, true ); textField.grabFocus(); } value = defValue; textField.setText("" + value); } return value; } public boolean checkNumRange( String sValue, int minValue, int maxValue ) { try { int value = Integer.parseInt(sValue); return( checkNumRange( value, minValue, maxValue ) ); } catch (NumberFormatException numberFormatException) { return false; } } public boolean checkNumRange( int value, int minValue, int maxValue ) { if(value < minValue) return false; if(value > maxValue) return false; return true; } public int checkAndGetStrNumRangeDef( Container cont, String sValue, int minValue, int maxValue, int defValue, boolean show ) { int value; try { value = Integer.parseInt(sValue); if(value < minValue) { if( show ) mbValueTooSmall( cont, minValue, maxValue, true ); value = minValue; } if(value > maxValue) { if( show ) mbValueTooBig( cont, minValue, maxValue, true ); value = maxValue; } } catch (NumberFormatException numberFormatException) { if( show ) mbValueNaN( cont, minValue, maxValue, true ); value = defValue; } return value; } public Boolean setCVvalue( int[][] CV, int cv, int value ) { if( CV == null ) { return false; } int CVlen = CV[0].length ; if( checkNumRange( cv, 1, CVlen) && checkNumRange( value, 0, 255) ) { CV[0][cv] = cv; CV[1][cv] = value ; return true; } return false; } public Boolean unsetCVvalue( int[][] CV, int cv ) { if( CV == null ) { return false; } int CVlen = CV[0].length ; if( checkNumRange( cv, 1, CVlen) ) { CV[0][cv] = 0; CV[1][cv] = 0 ; return true; } return false; } /** * * @param bArray answer from command station * @return CV value <b>OR</b> <br> -1 if bArray is null pointer or an invalid answer <br> -2 answer is incomplete */ public int checkPTRDAnswer( byte[] bArray ) { if( bArray == null ) { return -1; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = |\r|\\000"); if( debugLevel >= 3 ) { for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkPTRDAnswer 1622 strParts["+i+"]("+strParts[i].length()+")=\""+strParts[i]+"\""+((strParts[i].equals("]"))?" (ENDE)":"" )); } } int cvWert = -1; if( strParts.length > 0) { if( ! strParts[(strParts.length-1)].equals("]") ) { // answer is not complete ! if( debugLevel >= 3 ) { System.out.println("checkPTRDAnswer 1630 strParts.length="+strParts.length+" strParts["+(strParts.length-1)+"]=["+strParts[strParts.length-1]+"] INCOMPLETE"); } return -2; } // answer is complete if( debugLevel >= 4 ) { if( strParts[(strParts.length-1)].equals("]") ) { System.out.println("checkPTRDAnswer 1637 strParts[(strParts.length-1)].equals(\"[\") Yes"); } else { System.out.println("checkPTRDAnswer 1639 strParts[(strParts.length-1)].equals(\"[\") NO"); } } if( strParts[0].equalsIgnoreCase("No ack") ) { System.out.println("checkPTRDAnswer 1644 strParts[0]=["+strParts[0]+"]" ); return -1; } // convert first part to integer String s = ""; try { s = ""+strParts[0]; cvWert = Integer.parseInt(s); } catch (NumberFormatException ex) { System.out.println("checkPTRDAnswer 1516 Eception ex["+ex+"]"); for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkPTRDAnswer 1655 strParts["+i+"]=\""+strParts[i]+"\""+((strParts[i].startsWith("]"))?" (ENDE)":"" )); } } } return cvWert; } /** * * @param bArray answer from command station * @return true answer is complete (last answer line starts with "]") */ public boolean checkAnswerComplete( byte[] bArray ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = |\r|\\000"); if( debugLevel >= 3 ) { for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkAnswerComplete 1668 strParts["+i+"]=\""+strParts[i]+"\""+((strParts[i].startsWith("]"))?" (ENDE)":"" )); } } if( strParts.length > 0) { if( strParts[(strParts.length-1)].startsWith("]") ) { // answer is complete ! if( debugLevel >= 3 ) { System.out.println("checkAnswerComplete 1505 strParts.length="+strParts.length+" strParts["+(strParts.length-1)+"]=["+strParts[strParts.length-1]+"] COMPLETE"); } return true; } } return false; } /** * * @param bArray answer from command station * @return true answer is complete (last answer line starts with "]") */ public boolean checkReadComplete( byte[] bArray ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); int idxTerm = str_bArr.indexOf("\r]"); // line starting with "]" is end of data if( idxTerm >= 0 ) { return true; } return false; } /** * * @param bArray array of bytes (answer from command station) */ public void dumpbArray( byte[] bArray ) { if( bArray == null ) { return; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts //String[] strParts = str_bArr.split(" = |\r|\\000"); String[] strParts = str_bArr.split("\r|\\000"); dumpbArray( strParts ); } /** * * @param bArray array of bytes (answer from command station) */ public void dumpbArrayHex( byte[] bArray ) { if( bArray == null ) { return; } System.out.print("HEX: "); for (byte theByte : bArray) { System.out.printf( " %02x", theByte ); // System.out.print(Integer.toHexString(theByte)+" "); } System.out.println(""); } /** * * @param bArray array of bytes (answer from command station) * @return String with array in Hex */ public String dumpbArrayHexAsString( byte[] bArray ) { String sRet; String sTmp; String sTmp2; if( bArray == null ) { sRet = "null"; return sRet; } sTmp = ("HEX: "); for (byte theByte : bArray) { sTmp2 = String.format(" %02x", theByte); sTmp.concat(sTmp2); } sRet = sTmp; return sRet; } public void dumpbArrayBIN( byte[] bArray, int num ) { if( bArray == null ) { return; } for( int n = 0 ; n < num ; n++ ) { byte theByte = bArray[n]; System.out.printf( "HEX: 0x%02x BIN: %s\n", theByte, String.format("%8s", Integer.toBinaryString(theByte & 0xFF)).replace(' ', '0') ); } } /** * * @param strArray array of strings */ public void dumpbArray( String[] strArray ) { if( strArray == null ) { return; } for( int i = 0 ; i < strArray.length ; i++ ) { System.out.println("dumpbArray 1209 line["+i+"]("+strArray[i].length()+")=\""+strArray[i]+"\""+ (strArray[i].startsWith("]")?" (ENDE)":"") ); } } /** * * @param bArr array of bytes (answer from command station) * @param show if true show message box with raw error code * @return true if answer starts with 0x00 * * Liste der Error-Codes: 0x00 OK - kein Fehler, Befehl korrekt ausgeführt 0x02 XBADPRM - Parameterfehler (Parameterbyte außerhalb der zulässigen Werte) 0x06 XPWOFF - Befehl nicht ausgeführt, da MC im Modus STOP 0x07 XNOTSPC - Weichen-Queue ist voll, es können momentan keine weiterern Weichenbefehle angenommen werden. 0x08 XNOLSPC - Kein Platz im Kommandobuffer, Kommando später wiederholen 0x0A XNODATA - Lok ist nicht im Refresh-Buffer, daher kein Status verfügbar 0x0B XNOSLOT - Kein PLatz in der Refresh-Queue (Slot) 0x0D XLKBUSY - Lok wird bereits von einer anderen Unit kontrolliert 0x0E XBADTNP - Die Weichenadresse ist für das eingestellte Protokoll ungültig 0x41 XLKHALT - Lok-Kommando akzeptiert, aber nicht ausgeführt, da Steuerung im HALT-Modus ist. Die Geschwindigkeit wird auf 0 gesetzt. 0x42 XLKPOFF - Lok-Kommando akzeptiert, aber nicht ausgeführt, da Steuerung im STOP-Modus ist. Die Geschwindigkeit wird auf 0 gesetzt. */ public boolean checkMCAnswerByte( Container cont, byte[] bArr, Boolean show ) { if( bArr == null ) { if( show ) mbGeneric( cont, "checkMCAnswerByte", "invalid byteArray"); return false; } int len = bArr.length; if( len == 0 ) { if( show ) mbGeneric( cont, "checkMCAnswerByte", "byteArray is empty"); return false; } if( len > 1 ) { if( show ) mbGeneric( cont, "checkMCAnswerByte", "byteArray is too long (more than one byte)"); // was ist das denn ? } String errCode; errCode = bundle.getString("Errorcode"); if( debugLevel > 0 ) { System.out.println("checkMCAnswerByte: len="+len+" bArr[0]="+String.format("%02X ", bArr[0])); } switch( bArr[0] ) { case 0x00 : // OK return true; case 0x02 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XBADPRM"); break; case 0x06 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XPWOFF"); break; case 0x07 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XNOTSPC"); break; case 0x08 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XNOLSPC"); break; case 0x0A : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XNODATA"); break; case 0x0B : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XNOSLOT"); break; case 0x0D : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XLKBUSY"); break; case 0x0E : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XBADTNP"); break; case 0x41 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XLKHALT"); break; case 0x42 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XLKPOFF"); // "Lok-Kommando akzeptiert, aber nicht ausgeführt, da Steuerung im STOP-Modus ist.\nDie Geschwindigkeit wird auf 0 gesetzt." ); break; default: if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode, String.format(" %02X (unknown)", bArr[0])); } return false; } /** * * @param bArray array of bytes (answer from command station) * @return true if answer starts with "Ok" */ public boolean checkAnswerOK( byte[] bArray ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = |\r|\\000"); if( debugLevel >= 2 ) { for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkPTRDAnswer 1857 strParts["+i+"]("+strParts[i].length()+")=\""+strParts[i]+"\""+((strParts[i].startsWith("]"))?" (ENDE)":"" )); } } if( strParts.length > 0) { if( strParts[0].equalsIgnoreCase("Ok") ) { if( debugLevel >= 2 ) { System.out.println("checkPTWDAnswer 1232 strParts[0]=["+strParts[0]+"]" ); } return true; } } return false; } /** * * @param bArray array of bytes (answer from command station) * @return true if answer starts with "No ack" */ public boolean checkAnswerNoAck( byte[] bArray ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = |\r|\\000"); if( debugLevel >= 3 ) { dumpbArray( strParts ); } if( strParts.length > 0) { if( strParts[0].equalsIgnoreCase("No ack") ) { if( debugLevel >= 2 ) { System.out.println("checkPTWDAnswer 1258 strParts[0]=["+strParts[0]+"]"); } return true; } } return false; } public TwoWaySerialComm safelyOpenCom( Container cont, TwoWaySerialComm Com ) { return( safelyOpenCom( cont, Com, true)); } public TwoWaySerialComm safelyOpenCom( Container cont, TwoWaySerialComm Com, Boolean showMbox ) { if( debugLevel > 0 ) { System.out.println("safelyOpenCom: Com "+ Com==null?"=":"!" +"= null"); } if( Com != null ) { // valid Com -> check status connected try { if( Com.isconnected() ) { // already connected -> all OK return Com; } } catch (Exception | Error ex) { // problem COM is invalid } // problem COM is not connected Com = safelyCloseCom( cont, Com, showMbox ); } if( Com == null ) { try { Com = new TwoWaySerialComm(); Com.connect(this); if( ! Com.isconnected() ) { if( showMbox ) { mbDeviceConnectProblem( cont ); } Com = safelyCloseCom( cont, Com, showMbox ); return Com; } } catch (Exception | Error ex) { if( showMbox ) { mbDeviceConnectProblem( cont ); } Com = null; } } return Com; } public TwoWaySerialComm safelyCloseCom( Container cont, TwoWaySerialComm Com ) { return( safelyCloseCom( cont, Com, true)); } public TwoWaySerialComm safelyCloseCom( Container cont, TwoWaySerialComm Com, Boolean showMbox ) { if( debugLevel > 0 ) { System.out.println("safelyCloseCom: Com "+ Com==null?"=":"!" +"= null" ); System.out.println("cont name="+cont.getName() +" class="+cont.getClass() ); } if( Com != null ) { try { if( Com.isconnected() ) { Com.close(); } } catch (Exception | Error ex) { if( showMbox ) { mbDeviceDisconnectProblem( cont ); } } Com = null; } return Com; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); KlarTextMainPanel = new javax.swing.JPanel(); jButtonEnd = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jDecoderChooser = new javax.swing.JList(); jLabelProgName = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButtonStart = new javax.swing.JButton(); jButtonOptions = new javax.swing.JButton(); jLabelProgVersion = new javax.swing.JLabel(); jButtonInfo = new javax.swing.JButton(); jZentraleTitle = new javax.swing.JTextField(); jZentrale = new javax.swing.JTextField(); jSchnittstelleTitle = new javax.swing.JTextField(); jSchnittstelle = new javax.swing.JTextField(); jBaudrateTitle = new javax.swing.JTextField(); jBaudRate = new javax.swing.JTextField(); jLabelBuild = new javax.swing.JLabel(); jLabelOS = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("my/KlarText/Bundle"); // NOI18N setTitle(bundle.getString("KlarTextUI.title")); // NOI18N addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); KlarTextMainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, bundle.getString("KlarTextUI.KlarTextMainPanel.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N KlarTextMainPanel.setName("CV-Navi"); // NOI18N jButtonEnd.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButtonEnd.setText(bundle.getString("KlarTextUI.jButtonEnd.text")); // NOI18N jButtonEnd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonEndActionPerformed(evt); } }); jDecoderChooser.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jDecoderChooser.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Lok-Decoder", ". LD-G-30", ". LD-G-31", ". LD-W-32", ". LD-G-32", ". LD-W-33", ". LD-G-33", ". LD-G-34", ". LD-G-31Plus", ". LD-G-33Plus", ". LD-G-34Plus", ". LD-G-36Plus", "____________", "Funktions-Decoder", ". FD-R basic", ". FD-R extended", ". FD-M", ". FD-XL", "____________", "Zubehör-Decoder", ". WD-34", ". SD-34", "____________", "Sonstiges", ". MasterControl", ". B-4", ". WIB-30er" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jDecoderChooser.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jDecoderChooser.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { jDecoderChooserMouseReleased(evt); } public void mouseClicked(java.awt.event.MouseEvent evt) { jDecoderChooserMouseClicked(evt); } }); jDecoderChooser.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jDecoderChooserKeyReleased(evt); } }); jScrollPane1.setViewportView(jDecoderChooser); jLabelProgName.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabelProgName.setText(bundle.getString("KlarTextUI.jLabelProgName.text")); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 0, 0)); jLabel2.setText(bundle.getString("KlarTextUI.jLabel2.text")); // NOI18N jLabel3.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel3.setText(bundle.getString("KlarTextUI.jLabel3.text")); // NOI18N jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel4.setText(bundle.getString("KlarTextUI.jLabel4.text")); // NOI18N jLabel4.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); jLabel4.setIconTextGap(0); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 0, 0)); jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel5.setText(bundle.getString("KlarTextUI.jLabel5.text")); // NOI18N jLabel5.setIconTextGap(0); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText(bundle.getString("KlarTextUI.jLabel6.text")); // NOI18N jLabel6.setIconTextGap(0); jButtonStart.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jButtonStart.setText(bundle.getString("KlarTextUI.jButtonStart.text")); // NOI18N jButtonStart.setToolTipText(bundle.getString("KlarTextUI.jButtonStart.toolTipText")); // NOI18N jButtonStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStartActionPerformed(evt); } }); jButtonOptions.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButtonOptions.setText(bundle.getString("KlarTextUI.jButtonOptions.text")); // NOI18N jButtonOptions.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonOptionsActionPerformed(evt); } }); jLabelProgVersion.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabelProgVersion.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelProgVersion.setText(bundle.getString("KlarTextUI.jLabelProgVersion.text")); // NOI18N jLabelProgVersion.setIconTextGap(0); jButtonInfo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButtonInfo.setText(bundle.getString("KlarTextUI.jButtonInfo.text")); // NOI18N jButtonInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonInfoActionPerformed(evt); } }); jZentraleTitle.setEditable(false); jZentraleTitle.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N jZentraleTitle.setHorizontalAlignment(javax.swing.JTextField.LEFT); jZentraleTitle.setText(bundle.getString("KlarTextUI.jZentraleTitle.text")); // NOI18N jZentraleTitle.setToolTipText(bundle.getString("KlarTextUI.jZentraleTitle.toolTipText")); // NOI18N jZentraleTitle.setBorder(null); jZentrale.setEditable(false); jZentrale.setHorizontalAlignment(javax.swing.JTextField.CENTER); jZentrale.setText(bundle.getString("KlarTextUI.jZentrale.text")); // NOI18N jSchnittstelleTitle.setEditable(false); jSchnittstelleTitle.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N jSchnittstelleTitle.setHorizontalAlignment(javax.swing.JTextField.LEFT); jSchnittstelleTitle.setText(bundle.getString("KlarTextUI.jSchnittstelleTitle.text")); // NOI18N jSchnittstelleTitle.setToolTipText(bundle.getString("KlarTextUI.jSchnittstelleTitle.toolTipText")); // NOI18N jSchnittstelleTitle.setBorder(null); jSchnittstelle.setEditable(false); jSchnittstelle.setHorizontalAlignment(javax.swing.JTextField.CENTER); jSchnittstelle.setText(bundle.getString("KlarTextUI.jSchnittstelle.text")); // NOI18N jBaudrateTitle.setEditable(false); jBaudrateTitle.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N jBaudrateTitle.setHorizontalAlignment(javax.swing.JTextField.LEFT); jBaudrateTitle.setText(bundle.getString("KlarTextUI.jBaudrateTitle.text")); // NOI18N jBaudrateTitle.setToolTipText(bundle.getString("KlarTextUI.jBaudrateTitle.toolTipText")); // NOI18N jBaudrateTitle.setBorder(null); jBaudRate.setEditable(false); jBaudRate.setHorizontalAlignment(javax.swing.JTextField.CENTER); jBaudRate.setText(bundle.getString("KlarTextUI.jBaudRate.text")); // NOI18N jBaudRate.setToolTipText(bundle.getString("KlarTextUI.jBaudRate.toolTipText")); // NOI18N jLabelBuild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelBuild.setText("build"); jLabelBuild.setIconTextGap(0); jLabelOS.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelOS.setText("os info"); jLabelOS.setIconTextGap(0); javax.swing.GroupLayout KlarTextMainPanelLayout = new javax.swing.GroupLayout(KlarTextMainPanel); KlarTextMainPanel.setLayout(KlarTextMainPanelLayout); KlarTextMainPanelLayout.setHorizontalGroup( KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addComponent(jLabel4) .addGap(0, 0, 0) .addComponent(jLabel5) .addGap(0, 0, 0) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonEnd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE) .addGap(18, 18, 18) .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addComponent(jLabelProgName) .addGap(0, 0, 0) .addComponent(jLabel2) .addGap(0, 0, 0) .addComponent(jLabel3)) .addComponent(jButtonStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonOptions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jBaudrateTitle, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jBaudRate, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSchnittstelle, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSchnittstelleTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE) .addComponent(jZentrale, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jZentraleTitle, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addGap(41, 41, 41) .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabelBuild, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelProgVersion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelOS, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))) ); KlarTextMainPanelLayout.setVerticalGroup( KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, KlarTextMainPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelProgName) .addComponent(jLabel3) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabelProgVersion) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelOS, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelBuild, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 180, Short.MAX_VALUE) .addComponent(jButtonStart, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(46, 46, 46) .addComponent(jButtonOptions) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jZentraleTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jZentrale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSchnittstelleTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSchnittstelle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(8, 8, 8) .addComponent(jBaudrateTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBaudRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1)) .addGap(18, 18, 18) .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jButtonInfo) .addComponent(jButtonEnd)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(KlarTextMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(KlarTextMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); KlarTextMainPanel.getAccessibleContext().setAccessibleName(bundle.getString("KlarTextUI.KlarTextMainPanel.AccessibleContext.accessibleName")); // NOI18N pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonEndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEndActionPerformed stopIOAction(); mainWindowLocation = getLocationOnScreen(); System.out.println("jButtonEndActionPerformed mainWindowLocation="+mainWindowLocation); Properties prop = new Properties(); try { prop.loadFromXML(new FileInputStream(gsConfigFilename)); } catch (FileNotFoundException ex) { // Die XML-Config-Datei wird bei Bedarf beim Start des Programms in main() angelegt // deshalb hier keine weitere Behandlung Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } try { if ( -1 != jDecoderChooser.getSelectedIndex() ) { gsDecoderIndex = jDecoderChooser.getSelectedIndex(); } prop.setProperty("DecoderIndex", Integer.toString(gsDecoderIndex)); if( bSpracheDE ) { prop.setProperty("Language", "german") ; } else { prop.setProperty("Language", "english") ; } prop.setProperty("SaveOpenDirectory", gsSaveOpenDirectory); prop.setProperty("SaveOpenFilename", gsSaveOpenFilename); prop.setProperty("SaveOpenKennDirectory", gsSaveOpenKennDirectory); prop.setProperty("SaveOpenKennFilename", gsSaveOpenKennFilename); prop.setProperty("SaveOpenMcDirectory", gsSaveOpenMcDirectory); prop.setProperty("SaveOpenMcFilename", gsSaveOpenMcFilename); prop.setProperty("SaveOpenM3Directory", gsSaveOpenM3Directory); prop.setProperty("SaveOpenM3Filename", gsSaveOpenM3Filename); prop.setProperty("OpenFirmwareDirectory", gsOpenFirmwareDirectory); prop.setProperty("OpenFirmwareFilename", gsOpenFirmwareFilename); prop.setProperty("WindowLocationX", ""+mainWindowLocation.x); prop.setProperty("WindowLocationY", ""+mainWindowLocation.y); if( ! rs232_mode_was_forced ) { // only store if it was not forced on command line if( rs232_or_rb_usb_2 ) { prop.setProperty("DeviceForFwUpdate", "usb2"); } else { prop.setProperty("DeviceForFwUpdate", "usb1"); } } prop.storeToXML(new FileOutputStream(gsConfigFilename), gsConfigComment); } catch (IOException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } System.exit(0); }//GEN-LAST:event_jButtonEndActionPerformed public void fillMenuSelection() { int prevIdx = this.getDecoderChooser(); if( debugLevel > 0 ) { System.out.println("fillMenuSelection prevIdx="+prevIdx); } int coSize = decoderList.values().length; final String[] myStrings = new String[coSize]; for(decoderList co : decoderList.values()) { // System.out.printf("decoderList[%2d] [%2d] (%s) Const %10s Text %-35s %s\n",co.ordinal(), co.getIdx(), co.isSelectable()?"X":" ", co, co.getMenutextGer(), co.getMenutextEng()); myStrings[co.getIdx()] = bSpracheDE?co.getMenutextGer():co.getMenutextEng(); } if( bSpracheDE ) { jButtonOptions.setText("Optionen"); jButtonEnd.setText("Beenden"); jZentraleTitle.setText("Zentrale:"); jSchnittstelleTitle.setText("Schnittstelle:"); jBaudrateTitle.setText("Baudrate (seriell):"); } else { jButtonOptions.setText("Options"); jButtonEnd.setText("End"); jZentraleTitle.setText("control unit:"); jSchnittstelleTitle.setText("interface:"); jBaudrateTitle.setText("baud rate (serial):"); } if( ( fwVersion != null ) && ( fwVersion.length() > 0 ) ) { jZentrale.setText(gsZentrale+" ( "+fwVersion+ " )"); } else { jZentrale.setText(gsZentrale); } jSchnittstelle.setText(gsSchnittstelle); jBaudRate.setText(Integer.toString(gsBaudRate)); // TimerSettings 1. defaults MCtimer1 = 1; MCtimer2 = 1; timer1 = 2000; timer2 = 500; timer3 = -1; // timer3 is optional and may stay < 0 switch( lcZentrale ) { case c.cuIntellibox1: timerRetries = 20; break; case c.cuMasterControl: timerRetries = 9; break; case c.cuOpenDCC: timerRetries = 9; break; default: timerRetries = 20; } // if overridden by command-line, use user's values if( userTimer1 > 0 ){ MCtimer1 = userTimer1; timer1 = userTimer1; } if( userTimer2 > 0 ){ MCtimer2 = userTimer2; timer2 = userTimer2; } if( userTimer3 > 0 ) timer3 = userTimer3; if( userTimerRetries >= 0 ) timerRetries = userTimerRetries; if( debugLevel > 0 ) { System.out.println("timerSettings MCtimer1="+MCtimer1+" MCtimer2="+MCtimer2+" timer1="+timer1+" timer2="+timer2+" timer3="+timer3+" timerRetries="+timerRetries); } jDecoderChooser.setModel(new javax.swing.AbstractListModel() { public int getSize() { return myStrings.length; } public Object getElementAt(int i) { return myStrings[i]; } }); if( debugLevel > 0 ) { System.out.println("fillMenuSelection prevIdx("+prevIdx+")"); } this.setDecoderChooser(prevIdx); } private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartActionPerformed currSelection = jDecoderChooser.getSelectedIndex(); if( debugLevel > 0 ) { System.out.println("jButtonStartActionPerformed currSelection="+currSelection ); } if( this.frameInstanceDEVICE != null ) { this.frameInstanceDEVICE.toFront(); this.frameInstanceDEVICE.repaint(); if( debugLevel > 0 ) { System.out.println("jButtonStartActionPerformed: there is already an instance running for Decoder="+Decoder ); } return; } Decoder = currSelection; switch( Decoder ) { case c.LD_G30: // LD-G-30 case c.LD_W32: // LD-W-32 case c.LD_G32: // LD-G-32 case c.LD_W32_2: // LD-W-32.2 case c.LD_G32_2: // LD-G-32.2 LDG30 lDG30 = new LDG30(this); break; case c.LD_G31: // LD-G-31 LDG31 lDG31 = new LDG31(this); break; case c.LD_W33: // LD-W-33 case c.LD_G33: // LD-G-33 case c.LD_G34: // LD-G-34 case c.FD_XL: // FD-XL LDG33 lDG33 = new LDG33(this); break; case c.LD_G31Plus: // LD-G-31Plus case c.LD_G33Plus: // LD-G-33Plus case c.LD_G34Plus: // LD-G-33Plus case c.LD_G36Plus: // LD-G-33Plus LDG30erPlus lDG33Plus = new LDG30erPlus(this); break; case c.FD_R: // FD-R case c.FD_R2: // FD-R-basic2 FDR fDR = new FDR(this); break; case c.FD_R_ex: // FD-R extended FD_R_Extended fDRex = new FD_R_Extended(this); break; case c.FD_M: // FD-M FD_M fD_M = new FD_M(this); break; case c.FD_LED: //FD-LED FD_LED fD_LED = new FD_LED(this); break; /* case c.SD_22: // SD-22 break; */ case c.WD_34: // WD-34 case c.SD_34: // SD-34 case c.WD_34_2: // WD-34 case c.SD_34_2: // SD-34 WD34 wD34 = new WD34(this); break; case c.MultiDecoder: // MasterControl/RedBox MultiDec MD = new MultiDec(this); break; case c.MC: // MasterControl/RedBox MC mC = new MC(this); break; case c.B_4: // B-4 B_4 b_4 = new B_4(this); break; case c.BiDi_B: // BiDi-Booster BiDi_B BiDi_B = new BiDi_B(this); break; case c.WIB_30: // WIB-30er WIB_30 wib_30 = new WIB_30(this); break; default: mbDeviceNotSupported( this, 5 ); } }//GEN-LAST:event_jButtonStartActionPerformed private void jButtonOptionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOptionsActionPerformed Options options = new Options(this); }//GEN-LAST:event_jButtonOptionsActionPerformed enum KTUImenuEvt { VK_UP, VK_DOWN } private void KTUImenuEvalKey(KTUImenuEvt key) { Boolean checkAgain = true; decoderList[] DLval = decoderList.values(); while( checkAgain ) { checkAgain = false; int n = jDecoderChooser.getSelectedIndex(); if( DLval[n].isSelectable() ) { // entry is selectable -> OK return; } if( key == KTUImenuEvt.VK_DOWN) { if( n < ( DLval.length - 1 )) { jDecoderChooser.setSelectedIndex(n+1); checkAgain = true; } if( n == ( DLval.length - 1 )) { // UUps, das Ende der Liste ist nicht selectable ! // wir muessen aufwaerts bis wieder ein selectable kommt while( --n > 0 ) { if( DLval[n].isSelectable() ) { jDecoderChooser.setSelectedIndex(n); return; } } } } if( key == KTUImenuEvt.VK_UP) { if( n > 0 ) { jDecoderChooser.setSelectedIndex(n-1); checkAgain = true; } if( n == 0 ) { // 1st entry is not selectable // change to first selectable choice while( ++n < ( DLval.length - 1 ) ) { if( DLval[n].isSelectable() ) { jDecoderChooser.setSelectedIndex(n); return; } } } } } } private void jDecoderChooserMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDecoderChooserMouseReleased // mouse event is treated like VK_DOWN KTUImenuEvalKey(KTUImenuEvt.VK_DOWN); }//GEN-LAST:event_jDecoderChooserMouseReleased private void jDecoderChooserKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jDecoderChooserKeyReleased if(evt.getKeyCode()== KeyEvent.VK_DOWN) { KTUImenuEvalKey(KTUImenuEvt.VK_DOWN); } if(evt.getKeyCode()== KeyEvent.VK_UP) { KTUImenuEvalKey(KTUImenuEvt.VK_UP); } }//GEN-LAST:event_jDecoderChooserKeyReleased private void jDecoderChooserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDecoderChooserMouseClicked if(evt.getClickCount() == 2) { ActionEvent evnt = null; this.jButtonStartActionPerformed(evnt); } }//GEN-LAST:event_jDecoderChooserMouseClicked private void jButtonInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInfoActionPerformed jInfo jI = new jInfo( this ); }//GEN-LAST:event_jButtonInfoActionPerformed public void setFocus() { jButtonStart.grabFocus(); this.toFront(); this.repaint(); } private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened Properties prop = new Properties(); try { prop.loadFromXML(new FileInputStream(gsConfigFilename)); } catch (FileNotFoundException ex) { // Logger.getLogger(KlarTextUI.class.getName()).log(Level.INFO, null, ex); try { File f = new File(gsConfigDirectory); f.mkdir(); prop.storeToXML(new FileOutputStream(gsConfigFilename), gsConfigComment); } catch (IOException ex1) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex1); } } catch (IOException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } // Werte auslesen bzw. mit Defaults initialisieren setZentrale(prop.getProperty("Zentrale", "MasterControl")); gsSchnittstelle = prop.getProperty("Schnittstelle", "COM1"); gsBaudRate = Integer.parseInt( prop.getProperty("BaudRate","9600")); gsDecoderIndex = Integer.parseInt( prop.getProperty("DecoderIndex", Integer.toString(c.MC))); if(bundle.getString("Sprache").equals("Deutsch")) { bSpracheDE = true; } else { bSpracheDE = false; } gsLookAndFeel = prop.getProperty("LookAndFeel","Metal"); gsSaveOpenDirectory = prop.getProperty("SaveOpenDirectory",System.getProperty("user.home")); gsSaveOpenFilename = prop.getProperty("SaveOpenFilename"," "); gsSaveOpenKennDirectory = prop.getProperty("SaveOpenKennDirectory",System.getProperty("user.home")); gsSaveOpenKennFilename = prop.getProperty("SaveOpenKennFilename"," "); gsSaveOpenMcDirectory = prop.getProperty("SaveOpenMcDirectory",System.getProperty("user.home")); gsSaveOpenMcFilename = prop.getProperty("SaveOpenMcFilename"," "); gsSaveOpenM3Directory = prop.getProperty("SaveOpenM3Directory",System.getProperty("user.home")); gsSaveOpenM3Filename = prop.getProperty("SaveOpenM3Filename"," "); gsOpenFirmwareDirectory = prop.getProperty("OpenFirmwareDirectory",System.getProperty("user.home")); gsOpenFirmwareFilename = prop.getProperty("OpenFirmwareFilename"," "); if( ! rs232_mode_was_forced ) { // nur nach Änderung durch Benutzer zurückschreiben (Umstellung per Aufrufparameter ignorieren) rs232_or_rb_usb_2 = prop.getProperty("DeviceForFwUpdate","usb1").contentEquals("usb2"); } int x = Integer.parseInt( prop.getProperty("WindowLocationX", "-1" ) ); int y = Integer.parseInt( prop.getProperty("WindowLocationY", "-1" ) ); mainWindowLocation.setLocation(x, y); if( (mainWindowLocation.x >= 0 ) && (mainWindowLocation.y >= 0 ) ) { setLocation(mainWindowLocation); } fillMenuSelection(); jDecoderChooser.setSelectedIndex(gsDecoderIndex); jButtonStart.setSelected(true); jButtonStart.grabFocus(); SODlocalSize = new Dimension(); String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); String dataModel = System.getProperty("sun.arch.data.model"); String osInfo = "( "+osName+"["+osArch+"] , java "+dataModel+"bit )"; jLabelOS.setText(osInfo); String gsBuild ="beta 20180118b"; // use keyword "beta" or "release" System.out.println("Build: "+gsBuild); if( debugLevel > 0 || gsBuild.contains("beta") ) { jLabelBuild.setText(gsBuild); } else { jLabelBuild.setText(""); } // store pointer to instance in a final variable -> useable inside ActionListener final KlarTextUI outerThis = this; final ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { if( debugLevel > 0 ) { System.out.println( "actionPerformed" ); } byte[] bArray = new byte[0xFFFF]; if( bReadStatusBin ) { if( debugLevel > 0 ) { System.out.println( "actionPerformed bReadStatusBin " ); } bReadStatusBin = false; stopIOAction(); int tmpBytesRead = ExternalCom.read(bArray); // Gbts was Neues ? ExternalCom = null; if( debugLevel > 0 ) { System.out.println( "actionPerformed bReadStatusBin tmpBytesRead="+tmpBytesRead ); } if( tmpBytesRead > 0 ) { dumpbArrayBIN(bArray, tmpBytesRead); if( (bArray[0]&0x08)==0x08) { trackStatus = c.cuPowerOn; } else { trackStatus = c.cuPowerOff; } } else { trackStatus = -1 ; } distributeTrackStatus(); } if( bVerifyZentraleInProgress ) { bVerifyZentraleInProgress = false; stopIOAction(); int nBytes = KTUICom.read(bArray); KTUICom = safelyCloseCom( outerThis, KTUICom ); if( debugDummyData == 1 ) { // DUMMY - Werte zum DEBUGGEN : Tams MC bArray[0] = 0x04; bArray[1] = 0x01; bArray[2] = 0x04; bArray[3] = 0x07; bArray[4] = 'b'; bArray[5] = 0x04; bArray[6] = 0x00; bArray[7] = 0x13; bArray[8] = 0x07; bArray[9] = 0x56; bArray[10] = 0x00; nBytes = 11; } if( debugDummyData == 2 ) { // DUMMY - Werte zum DEBUGGEN : OpenDCC neu bArray[0] = 0x02; bArray[1] = 0x17; bArray[2] = 0x08; bArray[3] = 0x01; bArray[4] = 0x2a; bArray[5] = 0x00; nBytes = 6; } if( debugDummyData == 3 ) { // DUMMY - Werte zum DEBUGGEN : IB /* For example, the IB replies with: 02h, <SPU version low>, <SPU version high>, 02h, <KPU version low>, <KPU version high>, 01h, <PPU version>, 01h, <LIPU version>, 01h, <DNG version>, 05h, <IB serial number: 5 bytes (digits 98, 76, 54, 32, 10)>, 00h A single byte version # is to be interpreted as: H.L For example: 10h -> version 1.0 A two byte version # (low/high) is to be interpreted as: H.HLL For example: 23h, 10h -> version 1.023 (the version numbers and the serial number are sent in BCD notation - Binary Coded Decimal). The serial number is to be interpreted as: '9876543210' - i.e. digit '9' is the most significant digit, etc... SPU = System Processing Unit (the IB 'heart') KPU = Keypad Processing Unit (user interface) PPU = Peripheral Processing Unit (digital signal generator) LIPU = Lokmaus/I2C Processing Unit DNG = Dispositivo di Nostra Gestione (sorry this is italian language!) */ bArray[0] = 0x02; bArray[1] = (byte) 0x92; bArray[2] = 0x20; bArray[3] = 0x01; bArray[4] = 0x02; bArray[5] = 0x01; bArray[6] = 0x03; bArray[7] = 0x01; bArray[8] = 0x04; bArray[9] = 0x01; bArray[10] = 0x05; bArray[11] = 0x01; bArray[12] = 0x06; bArray[13] = 0x00; nBytes = 14; } if( debugDummyData == 4 ) { // DUMMY - Werte zum DEBUGGEN : IB bArray[0] = 0x02; bArray[1] = 0x23; bArray[2] = 0x10; bArray[3] = 0x01; bArray[4] = 0x02; bArray[5] = 0x01; bArray[6] = 0x03; bArray[7] = 0x01; bArray[8] = 0x04; bArray[9] = 0x01; bArray[10] = 0x05; bArray[11] = 0x01; bArray[12] = 0x06; bArray[13] = 0x00; nBytes = 14; } if(nBytes < 1) { mbTimeout( outerThis, c.mbRDverify ); } else { if( debugLevel > 0 ) { System.out.println("Xver: finished bArraySize="+nBytes); } byte[] mYbArray = new byte[nBytes]; System.arraycopy(bArray, 0, mYbArray, 0, nBytes); Boolean ok = verifyXVer( mYbArray ); bZentraleVerified = true; fillMenuSelection(); if( ok && bGotoUpdate ) { if( debugLevel > 0 ) { System.out.println("bVerifyZentraleInProgress jDecoderChooser.setSelectedIndex="+c.MC ); } jDecoderChooser.setSelectedIndex(c.MC); jButtonStartActionPerformed( null ); } } return; } } }; timer = new javax.swing.Timer(5000, actionListener); timer.setRepeats(false); actionListener.actionPerformed(null); verifyZentrale(false); }//GEN-LAST:event_formWindowOpened private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing // leave through OS closing the app -> simulate exit-button event jButtonEndActionPerformed( null ); }//GEN-LAST:event_formWindowClosing private Boolean verifyXVer( byte[] bIn ) { int lenIn = bIn.length; int numAnswers = 0; int idx = 0; String sSwVersion = null; long lSwVersion = 0; char b = ' '; char bNum = ' '; /* * Version Info: * IB 6 answers first is 2 Bytes (BCD) * OpenDCC 1 answer 1 Bytes (BYTE) (until V0.14, only version) * OpenDCC 1 answer 2 Bytes (BYTE) (since V0.15, version+serno combined) * OpenDCC 2 answers first is 2 Bytes (BYTE) (since V0.23.8release) * Tams 2 answers first is 3 Bytes (BCD) or 4 Bytes (3*BCD + ASCII) * MoPi 2 answer 3 Bytes (BYTE) (stores version: major, minor, build) */ /* First in byte tells how much bytes are in next answer. */ if( debugLevel > 0 ) { System.out.println("bIn("+lenIn+")=0x"+printHexBinary(bIn)); } if( lenIn <= 0 ) { if( debugLevel > 0 ) { System.out.println("verifyXVer bIn is empty lenIn="+lenIn); } return false; } int lenAntwort = (int) bIn[idx]; idx++; if( debugLevel > 0 ) { System.out.println("Antwort["+numAnswers+"] ist "+lenAntwort+" Bytes lang"); } if( lenAntwort > lenIn ) { System.out.println("May be a TamsMC waiting for a software update..."); // meist zwischen 8 und 12 Bytes if( lenIn >= 5 ) { // 0x4C235423542354235423 T#L#T#T#T# // 10 MasterControl // 0x4C235423542354235423 L#T#T#T#T# T#L#T#T#T#T# // MC als HC T#T#T#T#T#T# // 0x54234323542354235423 C#T#T#T#T# T#C#T#T#T# // 10 HandControl / PhoneControl // 0x543F4C3F543F543F543F L?T?T?T?T? // 10 XN-Control / mControl T?C?T?T? C?T?T?T? T?L?T?T?T?T? T?L?T?T?T?T? // 0x23 = 35 = '#' Block wiederholen (256 Bytes) // 0x3F = 63 = '?' Block wiederholen (128 Bytes) // 0x43 = 67 = 'C' CRC Error // 0x4C = 76 = 'L' Length Error // 0x54 = 84 = 'T' Time out Error String s = new String( bIn ); String cs = s.substring(1, 5); if( debugLevel > 0 ) { System.out.println("bIN as String="+s+" len="+s.length()+" cs="+cs ); } // die ersten 4 Zeichen vergleichen switch( cs ) { case "L#T#" : case "T#L#" : case "C#T#" : case "T#C#" : case "T#T#" : case "#L#T" : case "#T#L" : case "#C#T" : case "#T#C" : case "#T#T" : System.out.println("Yes a TamsMC with a 256 byte block device (MasterControl, HandControl, PhoneControl, ... ) waiting for a software update"); break; case "L?T?" : case "T?L?" : case "C?T?" : case "T?C?" : case "T?T?" : case "?L?T" : case "?T?L" : case "?C?T" : case "?T?C" : case "?T?T" : System.out.println("Yes a TamsMC with a 128 byte block device (XNControl, mControl, ... ) waiting for a software update"); break; default: System.out.println("A TamsMC with an unknown device waiting for a software update"); // TODO Dialog ausgliedern und DE/EN mbGeneric(this, "A TamsMC with an unknown device waiting for a software update", "Please report devicename and the following line to Tams", s, 0, true); } bGotoUpdate = (getZentrale() == c.cuMasterControl); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuMasterControl ); if( debugLevel > 0 ) { System.out.println("bVerifyXVer bGotoUpdate="+bGotoUpdate ); } return bGotoUpdate; } return false; } if( lenAntwort < 0 ) { System.out.println("Antwort["+numAnswers+"] : Länge ("+lenAntwort+") ist negativ -> Abbruch bVerifyXVer"); return false; } numAnswers++; byte[] bVersion = new byte[lenAntwort]; int lenVersion = lenAntwort; System.arraycopy(bIn, 1, bVersion, 0, lenAntwort); idx += lenAntwort; while( idx < lenIn ) { lenAntwort = (int) bIn[idx]; if( debugLevel > 0 ) { System.out.println("2880 Antwort["+numAnswers+"] ist "+lenAntwort+" Bytes lang"); } idx++; if( idx + lenAntwort <= lenIn ) { if( lenAntwort > 0 ) { numAnswers++; } else { if( debugLevel > 0 ) { System.out.println("2888 ENDE Xver : idx["+idx+"] + lenAntwort["+lenAntwort+"] <= lenIn["+lenIn+"]"); } } } else { // Ooops if( debugLevel > 0 ) { System.out.println("2894 Oooops : idx["+idx+"] + lenAntwort["+lenAntwort+"] <= lenIn["+lenIn+"]"); } } idx += lenAntwort; } if( debugLevel > 0 ) { System.out.println("numAnswers="+numAnswers); } switch( lenVersion ) { case 1: fwVersion = "0."+(bVersion[0] & 0xFF)+ ".0"; sSwVersion = "OpenDCC Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbGeneric( this, "Information", "Detected "+sSwVersion, "(Xfuncs="+bUseXfuncs+")", 5, false ); break; case 2: switch( numAnswers ) { case 1: // OpenDCC V0.15 until V0.23.8beta, (2 bytes version+serno) fwVersion = "0."+(bVersion[0] & 0xFF)+".0"; sSwVersion = "OpenDCC Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuOpenDCC ); break; case 2: // OpenDCC since V0.23.8 (2 bytes version + 1 byte serno) lSwVersion = (long) ((bVersion[0] & 0xFF) << 8 ) + (long) (bVersion[1] & 0xFF); if( lSwVersion >= 0x1708 ) { bUseXfuncs = true; } fwVersion = "0."+ (bVersion[0] & 0xFF) +"."+ (bVersion[1] & 0xFF); sSwVersion = "OpenDCC Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuOpenDCC ); break; default: // IB should have 6 answers lSwVersion = (long) ((bVersion[1] & 0xFF) << 8 ) + (long) (bVersion[0] & 0xFF); if( lSwVersion >= 0x2000 ) { bUseXfuncs = true; } fwVersion = String.format("%01x.%01x%02x", (bVersion[1]&0xF0)>>4, bVersion[1]&0x0F, bVersion[0]&0xFF); sSwVersion = "Intellibox Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuIntellibox1 ); break; } break; case 5: // Tams beta prerelease # bNum = (char) ( bVersion[4] & 0xFF ); case 4: // Tams beta release b = (char) ( bVersion[3] & 0xFF ); lSwVersion = (long) (bVersion[3] & 0xFF); case 3: // Tams official release lSwVersion += (long)((bVersion[0] & 0xFF) << 24 ); lSwVersion += (long)((bVersion[1] & 0xFF) << 16 ); lSwVersion += (long)((bVersion[2] & 0xFF) << 8 ); bUseXfuncs = ( lSwVersion >= c.MIN_MC_XFUNCS_VERSION ); bUseXm3sid = ( lSwVersion >= c.MIN_MC_XM3SID_VERSION ); bUseSo999 = ( lSwVersion >= c.MIN_MC_SO999_VERSION ); fwVersion = "" + (int) (bVersion[0] & 0xFF) +"." + (int) (bVersion[1] & 0xFF) +"." + (int) (bVersion[2] & 0xFF) + b + bNum; sSwVersion = "MasterControl Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuMasterControl ); break; default: System.out.println("Unbekannte Zentrale ausgelesen: Daten["+lenIn+" Bytes] = 0x"+printHexBinary(bIn)); return false; } if( lSwVersion > 0 ) { if( debugLevel > 0 ) { System.out.println("lSwVersion="+lSwVersion+" in HEX="+String.format("0x%16s", Long.toHexString(lSwVersion)).replace(' ', '0') ); System.out.println("bUseXfuncs="+bUseXfuncs+" bUseXm3sid="+bUseXm3sid); } } return true; } /** * * @param force force verify of control unit (use after changed parameters) */ public void verifyZentrale(Boolean force) { if( force ) bZentraleVerified = false; if( bZentraleVerified ) return; if( bVerifyZentraleInProgress ) return; bUseXfuncs = false; bUseXm3sid = false; KTUICom = safelyOpenCom( this, KTUICom ); if( (KTUICom != null) && KTUICom.isconnected() ) { flushReadBuffer( KTUICom ); byte[] wArray = new byte[2]; wArray[0] = (byte) 0x78; // x wArray[1] = (byte) 0xA0; // XVer KTUICom.write(wArray); bVerifyZentraleInProgress = true; timer.setInitialDelay(2000); timer.setDelay(2000); if( userTimer1 > 2000 ) timer.setInitialDelay(userTimer1); if( userTimer2 > 2000 ) timer.setDelay(userTimer2); startIOAction(); } } private void startIOAction() { // jButtonStart.setEnabled(false); jButtonOptions.setEnabled(false); jDecoderChooser.setEnabled(false); // set cursor to WAIT Cursor c = new Cursor(Cursor.WAIT_CURSOR); this.setCursor(c); //start timer timer.start(); } private void stopIOAction() { // stop timer timer.stop(); bVerifyZentraleInProgress = false; // set cursor Cursor c = new Cursor(Cursor.DEFAULT_CURSOR ); setCursor(c); // jButtonStart.setEnabled(true); jButtonOptions.setEnabled(true); jDecoderChooser.setEnabled(true); } public int flushReadBuffer( TwoWaySerialComm Com ) { int numBytes = 0; if( (Com != null) && Com.isconnected() ) { // flushReadBuffer byte[] bArray = new byte[0xFFFF]; numBytes = Com.read(bArray); if( debugLevel > 0 ) { System.out.println("2982 flushReadBuffer : "+numBytes+" Bytes" ); dumpbArray(bArray); } } return numBytes; } public void trackPowerOn( TwoWaySerialComm Com ) { Com.write( (byte) 0x60 ); checkTrackStatus( Com ); } public void trackPowerOff( TwoWaySerialComm Com ) { Com.write( (byte) 0x61 ); checkTrackStatus( Com ); } public void checkTrackStatus( TwoWaySerialComm Com ) { if( Com == null ) { return; } ExternalCom = Com ; flushReadBuffer( ExternalCom ); /* Abfrage mit 1 Byte Antwort ! */ byte[] wArray = new byte[2]; wArray[0] = (byte) 0x78; // x wArray[1] = (byte) 0xA2; // XStatus ExternalCom.write(wArray); bReadStatusBin = true; timer.setInitialDelay(500); timer.setDelay(500); if( userTimer1 > 2000 ) timer.setInitialDelay(userTimer1); if( userTimer2 > 2000 ) timer.setDelay(userTimer2); startIOAction(); } public int getTrackStatus() { if( forceTrackPowerOn ) { return c.cuPowerOn; } return trackStatus; } private void distributeTrackStatus() { if( frameInstanceDEVICE != null ) { String devName = frameInstanceDEVICE.getClass().getSimpleName() ; switch( devName ) { case "B_4": B_4 b4 = (B_4) frameInstanceDEVICE; System.out.println( "calling setStatus( "+trackStatus+" ) for "+devName ); b4.setStatus( getTrackStatus() ); break; case "BiDi_B": BiDi_B bidib = (BiDi_B) frameInstanceDEVICE; System.out.println( "calling setStatus( "+trackStatus+" ) for "+devName ); bidib.setStatus( getTrackStatus() ); break; default: System.out.println( "setStatus( "+trackStatus+" ) for UNKNOWN/UNSUPPORTED DEVICE "+devName ); } } } public void setSwitch( TwoWaySerialComm Com, int address, boolean straight, boolean coilOn ) { byte[] wArray = new byte[4]; wArray[0] = (byte) 0x78; // x wArray[1] = (byte) 0x90; // XTrnt wArray[2] = (byte) (address & 0xFF); // AdrLow wArray[3] = (byte) ( ( (address >> 8) & 0x07) | (straight?0x80:0x00) | (coilOn?0x40:0x00) ); // AdrHigh (3bits) + Bit8 = turnout, Bit7= coilOn Com.write( wArray ); if( debugLevel > 0 ) { System.out.println("Weiche "+address+" gerade="+straight+ " aktiv="+coilOn ); } dumpbArrayBIN(wArray, 4); } private static Boolean verifySelectionList() { // test decoder menu for correct idx in first column // if not some strange things might happen ! int decoderListSize = decoderList.values().length; int decoderListCount = 0; int errorsDetected = 0; for(decoderList co : decoderList.values()) { if( co.getIdx() != decoderListCount ) { System.out.printf("ERROR in decoderListCount %2d decoderList[%2d] [%2d] (%s) Const %10s Text %-35s %s\n", decoderListCount, co.ordinal(), co.getIdx(), co.isSelectable()?"X":" ", co, co.getMenutextGer(), co.getMenutextEng()); errorsDetected++; } decoderListCount++; } if( decoderListCount != decoderListSize ) { System.out.println("ERROR in decoderListCount != decoderListSize "+decoderListCount+" != "+decoderListSize); errorsDetected++; } if( errorsDetected != 0 ) { System.out.println(""+errorsDetected+" ERRORS in decoderList detected" ); return false; }else { System.out.println("decoderList verified successfully"); } return true; } private static void helpCommandLine() { System.out.println("CV-Navi [-d [<num>]] [-c] [-c Xfuncs] [-c Xm3sid ] [-b <num>] [-o]"); System.out.println("\t-d [<num>] \tdebuglevel (without num: increment by 1)" ); System.out.println("\t-c \tforce configured control unit (no check)"); System.out.println("\t-c Xfuncs \tforce enable XFuncs"); System.out.println("\t-c Xm3sid \tforce enable Xm3sid"); System.out.println("\t-b <num> \tuse preconfigured dummy datasets for debugging"); System.out.println("\t-o \tforce offline mode"); System.out.println("\t-p \tforce track power reported as on"); System.out.println("\t-t1 <num> \tread/write CVs: initial timeout [ms] (default: 2000)"); System.out.println("\t-t2 <num> \tread/write CVs: delay timeout [ms] (default: 500)"); System.out.println("\t-t3 <num> \tread/write CVs: extra pause [ms] between CV requests (default: 0)"); System.out.println("\t-tr <num> \tread/write CVs: number of retries with delay timeout (default: 9)"); System.out.println("\t-tfu <num> \ttimer interval during firmware updates (default: 250)"); System.out.println("\t-u \tupdate window always visible"); System.out.println("\t-usb1 \tuse USB-1 in RedBox/MasterControl -> no BaudRate changes on firmware updates (default: on)"); System.out.println("\t-usb2 \tuse USB-2 in RedBox -> BaudRate change to 38400 on firmware-updates (default: off)"); System.out.println("\t-rs232 \tuse RS232 in RedBox/MasterControl -> BaudRate change to 38400 on firmware-updates (default: off)"); System.out.println("\t-no17 \tdo not read CV17"); System.out.println("\t-no18 \tdo not read CV18"); } /** * @param args the command line arguments */ public static void main(final String args[]) { int argc = args.length; String sunModel = System.getProperty("sun.arch.data.model"); String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); System.out.println("model["+sunModel+"] osName["+osName+"] osArch["+osArch+"]"); System.out.println("argc="+ argc ); int n = 0; try { for ( n = 0 ; n < argc ; n++ ) { switch( args[n].toLowerCase() ) { case "-d": if( n == (argc-1) || args[n+1].startsWith("-") ){ debugLevel++; System.out.println("debugLevel set to "+debugLevel); break; } n++; debugLevel = Integer.parseInt(args[n]); System.out.println("debugLevel set to "+debugLevel); break; case "-c": if( n == (argc-1) || args[n+1].startsWith("-") ){ bZentraleVerified = true; System.out.println("bZentraleVerified set to "+bZentraleVerified); break; } n++; if( args[n].equalsIgnoreCase("Xfuncs")) { bZentraleVerified = true; bUseXfuncs = true; System.out.println("bUseXfuncs set to "+bUseXfuncs); } if( args[n].equalsIgnoreCase("Xm3sid")) { bZentraleVerified = true; bUseXm3sid = true; System.out.println("bUseXm3sid set to "+bUseXm3sid); } break; case "-b": if( n == (argc-1) || args[n+1].startsWith("-") ) { // "-b" ohne Parameter -> Zahl fehlt => ignorieren break; } n++; debugDummyData = Integer.parseInt(args[n]); System.out.println("debugDummyData set to "+debugDummyData); break; case "-o": debugOffline = true; System.out.println("debugOffline set to true"); break; case "-p": forceTrackPowerOn = true; System.out.println("forceTrackPowerOn set to true"); break; case "-t1": if( n == (argc-1) || args[n+1].startsWith("-") ) { // "-t1" ohne Parameter -> Zahl fehlt => ignorieren break; } n++; userTimer1 = Integer.parseInt(args[n]); System.out.println("userTimer1 set to "+userTimer1); break; case "-t2": if( n == (argc-1) || args[n+1].startsWith("-") ) { // ohne Parameter -> Zahl fehlt => ignorieren break; } n++; userTimer2 = Integer.parseInt(args[n]); System.out.println("userTimer2 set to "+userTimer2); break; case "-t3": if( n == (argc-1) || args[n+1].startsWith("-") ) { // ohne Parameter -> Zahl fehlt => ignorieren break; } n++; timer3 = Integer.parseInt(args[n]); System.out.println("userTimer3 set to "+userTimer3); break; case "-tr": if( n == (argc-1) || args[n+1].startsWith("-") ) { // ohne Parameter -> Zahl fehlt => ignorieren break; } n++; userTimerRetries = Integer.parseInt(args[n]); System.out.println("userTimerRetries set to "+userTimerRetries); break; case "-tfu": if( n == (argc-1) || args[n+1].startsWith("-") ) { // ohne Parameter -> Zahl fehlt => ignorieren break; } n++; userTimerFwUp = Integer.parseInt(args[n]); System.out.println("userTimerFwUp set to "+userTimerFwUp); break; case "-u": updateAlwaysVisible = true; System.out.println("updateVisible set to true"); break; case "-usb1": rs232_or_rb_usb_2 = false; System.out.println("force using usb-1 mode"); rs232_mode_was_forced = true; break; case "-usb2": case "-rs232": rs232_or_rb_usb_2 = true; System.out.println("force using usb-2/rs232 mode"); rs232_mode_was_forced = true; break; case "-no17": skipCV17 = true; System.out.println("skipCV17 set to "+skipCV17); break; case "-no18": skipCV18 = true; System.out.println("skipCV18 set to "+skipCV18); break; case "-h": helpCommandLine(); return; default: System.out.println("args["+n+"]=["+args[n]+"] UNHANDLED"); } } } catch (NumberFormatException ex) { System.out.println("inside parse args: numberFormatException ex["+ex+"] n="+n); helpCommandLine(); return; } if( debugLevel > 0 ) System.out.println("debugLevel="+debugLevel); if( verifySelectionList() == false ) return; String s = "javax.swing.plaf.metal.MetalLookAndFeel"; Properties prop = new Properties(); try { prop.loadFromXML(new FileInputStream(gsConfigFilename)); } catch (FileNotFoundException ex) { // Logger.getLogger(KlarTextUI.class.getName()).log(Level.INFO, null, ex); try { File f = new File(gsConfigDirectory); f.mkdir(); prop.storeToXML(new FileOutputStream(gsConfigFilename), gsConfigComment); } catch (IOException ex1) { // MsgBox messageBox = new MsgBox( (Frame) KlarTextUI.getFrames()[0] , true); MsgBox messageBox = new MsgBox( (Frame) null , true, null ); messageBox.jLabel1.setText("FEHLER"); messageBox.jLabel2.setText("Kann Konfigurationsdatei nicht anlegen"); messageBox.jLabel3.setText(gsConfigFilename); messageBox.setVisible(true); Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex1); try { Thread.sleep(5000); } catch (InterruptedException ex2) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex2); } // System.exit(1); } } catch (IOException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } switch (prop.getProperty("LookAndFeel","Metal")) { case "Motif": s = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; break; case "Nimbus": s = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"; break; case "Windows": s = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; break; } try { UIManager.setLookAndFeel(s); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new KlarTextUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel KlarTextMainPanel; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JTextField jBaudRate; private javax.swing.JTextField jBaudrateTitle; private javax.swing.JButton jButtonEnd; private javax.swing.JButton jButtonInfo; private javax.swing.JButton jButtonOptions; private javax.swing.JButton jButtonStart; private javax.swing.JList jDecoderChooser; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabelBuild; private javax.swing.JLabel jLabelOS; private javax.swing.JLabel jLabelProgName; private javax.swing.JLabel jLabelProgVersion; private javax.swing.JTextField jSchnittstelle; private javax.swing.JTextField jSchnittstelleTitle; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField jZentrale; private javax.swing.JTextField jZentraleTitle; // End of variables declaration//GEN-END:variables }
src/my/KlarText/KlarTextUI.java
/* * KlarTextUI.java * * Created on 20.01.2009, 17:34:06 */ package my.KlarText; import java.awt.Container; import java.awt.Cursor; import java.awt.Dialog.ModalExclusionType; import java.awt.Dimension; import java.awt.Frame; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextField; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import static javax.xml.bind.DatatypeConverter.printHexBinary; /** * * @author ktams */ // Konstanten definieren, die auch in switch-Anweisungen funktionieren ! // Etwas umständlich, aber sonst müssen alle switch-Anweisungen, // die KTUI.Decoder verwenden auf "if-then-else-if..." umgeschrieben werden :( // // Zuerst die Definition der Konstanten (nur hier stehen Zahlen für Menu und switch-Anweisungen !!!) // Erster Block ist für das Auswahlmenü: // Nur fortlaufende Nummern, beginnend mit 0 erlaubt // Die Nummer ist der Index in der Auswahlliste! // Das wird beim Programmstart als Erstes auf Plausibilität überprüft ! interface c { public static final int tLOK = 0; public static final int LD_G30 = 1; public static final int LD_G31 = 2; public static final int LD_W32 = 3; public static final int LD_W32_2 = 4; public static final int LD_G32 = 5; public static final int LD_G32_2 = 6; public static final int LD_W33 = 7; public static final int LD_G33 = 8; public static final int LD_G34 = 9; public static final int LD_G31Plus = 10; public static final int LD_G33Plus = 11; public static final int LD_G34Plus = 12; public static final int LD_G36Plus = 13; public static final int LINE_1 = 14; public static final int tFD = 15; public static final int FD_R = 16; public static final int FD_R2 = 17; public static final int FD_R_ex = 18; public static final int FD_M = 19; public static final int FD_XL = 20; public static final int FD_LED = 21; public static final int LINE_2 = 22; public static final int tZUB = 23; public static final int WD_34 = 24; public static final int WD_34_2 = 25; public static final int SD_34 = 26; public static final int SD_34_2 = 27; public static final int MultiDecoder = 28; public static final int LINE_3 = 29; public static final int tOTHER = 30; public static final int MC = 31; // MasterControl/RedBox public static final int B_4 = 32; public static final int BiDi_B = 33; public static final int WIB_30 = 34; // special numbers (used in SaveOpenDialog) public static final int MC_WR = 196; // special handling of MC config writes public static final int M3 = 197; // M3 uid/sid Liste public static final int KENN = 198; // (Motor-)Kennlinie public static final int HEX = 199; // Firmware public static final int TXT = 200; // Firmware // MC-Konstanten: public static final int MAX_SYSWRITES = 11; // #zu schreibende Variablen für ein Restore der Basiseinstellungen (ohne Listen) public static final int MAX_LOCS = 250; // Lokliste [0-249] public static final int MAX_TRACTIONS = 150; // Tracktionsliste [0..149] public static final int MAX_M3_ENTRIES = 512; // M3UID-SID-Pairs [0..511] public static final int MAX_LOC_NAME_LENGTH = 11; // maximum length of loco name // Zubehoerdecoder public static final int MAX_MM1_ACCMOD = 255; // 255 Module[0..254] =^= addr[1-1020] public static final int MAX_DCC_ACCMOD = 510; // 510 Module[0..509] "^° addr[1-2040] // Zentralen public static final int cuOpenDCC = 0; public static final int cuIntellibox1 = 1; public static final int cuMasterControl = 2; // Status public static final int cuPowerUnknown = -1; public static final int cuPowerOff = 0; public static final int cuPowerOn = 1; // S88 public static final int maxS88 = 52; // MessageBoxErrorCodes public static final int mbRDcancel = 1; public static final int mbWRcancel = 2; public static final int mbRDtimeout = 3; public static final int mbWRtimeout = 4; public static final int mbRDtooShort = 5; public static final int mbMCRDtimeout = 6; public static final int mbMCRDcommitErr = 7; public static final int mbMCWRtimeout = 8; public static final int mbRDverify = 9; // public static final long MIN_MC_XFUNCS_VERSION = 0x01040666; // 1.4.6f public static final long MIN_MC_XM3SID_VERSION = 0x01040762; // 1.4.7b public static final long MIN_MC_SO999_VERSION = 0x01040863; // 1.4.8c // other public static final int MAX_CV = 1024; public static final int MAX_M3_SID = 16383; public static final String ERR_PROBLEM_LEFT = "<- Problem !"; public static final String TamsFirmwareURL = "http://tams-online.de/epages/642f1858-c39b-4b7d-af86-f6a1feaca0e4.sf/de_DE/?ObjectPath=/Shops/642f1858-c39b-4b7d-af86-f6a1feaca0e4/Categories/Download1/Firmware"; } // Jetzt die Records mit und zu den Konstanten enum decoderList { // const menuIdx, selectable, german text, english (if different) tLOK (c.tLOK, false, "Lok-Decoder", "Loco-Decoder"), LD_G30 (c.LD_G30, true, " LD-G-30",""), LD_G31 (c.LD_G31, true, " LD-G-31",""), LD_W32 (c.LD_W32, true, " LD-W-32",""), LD_W32_2 (c.LD_W32_2, true, " LD-W-32.2",""), LD_G32 (c.LD_G32, true, " LD-G-32",""), LD_G32_2 (c.LD_G32_2, true, " LD-G-32.2",""), LD_W33 (c.LD_W33, true, " LD-W-33",""), LD_G33 (c.LD_G33, true, " LD-G-33",""), LD_G34 (c.LD_G34, true, " LD-G-34",""), LD_G31Plus (c.LD_G31Plus, true, " LD-G-31Plus",""), LD_G33Plus (c.LD_G33Plus, true, " LD-G-33Plus",""), LD_G34Plus (c.LD_G34Plus, true, " LD-G-34Plus",""), LD_G36Plus (c.LD_G36Plus, true, " LD-G-36Plus",""), line_1 (c.LINE_1, false, "____________",""), tFD (c.tFD, false, "Funktions-Dekoder","Function-Decoder"), FD_R (c.FD_R, true, " FD-R basic",""), FD_R2 (c.FD_R2, true, " FD-R basic 2",""), FD_R_ex (c.FD_R_ex,true, " FD-R extended",""), FD_M (c.FD_M, true, " FD-M",""), FD_XL (c.FD_XL, true, " FD-XL",""), FD_LED (c.FD_LED, true, " FD-LED",""), line_2 (c.LINE_2, false, "____________",""), tZUB (c.tZUB, false, "Zubehör-Decoder","Accessory-Decoder"), WD_34 (c.WD_34, true, " WD-34",""), WD_34_2 (c.WD_34_2, true, " WD-34.2",""), SD_34 (c.SD_34, true, " SD-34",""), SD_34_2 (c.SD_34_2, true, " SD-34.2",""), MultiDecoder (c.MultiDecoder, true, " MultiDecoder",""), line_3 (c.LINE_3, false, "____________",""), tOTHER (c.tOTHER, false, "Sonstiges","Other"), MC (c.MC, true, " MasterControl/RedBox",""), B_4 (c.B_4, true, " B-4",""), BiDi_B (c.BiDi_B, true, " BiDi-Booster",""), WIB_30 (c.WIB_30, true, " WIB-30er",""); private final int idx; private final Boolean selectable; private final String menuTextGer; private final String menuTextEng; decoderList(int idx, Boolean sel, String textGer, String textEng) { this.idx = idx; this.selectable = sel; this.menuTextGer = textGer; this.menuTextEng = textEng; } public int getIdx() {return idx;} public Boolean isSelectable() {return selectable;} public String getMenutextGer() { return menuTextGer; } public String getMenutextEng() { return menuTextEng.isEmpty() ? menuTextGer : menuTextEng; } } public class KlarTextUI extends javax.swing.JFrame { /** Creates new form KlarTextUI */ public int gsVersionMayor = 2; public int gsVersionMinor = 7; public JFrame frameInstanceDEVICE = null; public JFrame frameInstanceOPTIONS = null; public JFrame frameInstanceINFO = null; public int Decoder = 0; // better name would be Device, because MC and B4 are also handled public int currSelection = 0; public boolean bSpracheDE = true; //true -> deutsch, false -> englisch public static int debugLevel = 0; public static boolean debugOffline = false; public static boolean forceTrackPowerOn = false; public static int debugDummyData = 0; private static int userTimer1 = -1; private static int userTimer2 = -1; private static int userTimer3 = -1; private static int userTimerRetries = -1; public static int userTimerFwUp = 150; public static int MCtimer1 = -1; public static int MCtimer2 = -1; public static int timer1 = -1; public static int timer2 = -1; public static int timer3 = -1; public static int timerRetries = -1; public static boolean updateAlwaysVisible = false; public static boolean skipCV17 = false; public static boolean skipCV18 = false; private static int trackStatus = c.cuPowerUnknown; private boolean bReadStatusBin = false; public static boolean rs232_or_rb_usb_2 = false; public static boolean rs232_mode_was_forced = false; // Globale Variablen, die nur einmal eingelesen werden sollten // gs = GlobalSetting // Die ersten 3 Variablen sind static, da sie auch in main (static context) verwendet werden static String gsConfigDirectory = System.getProperty("user.home") + "/.CV-Navi/"; static String gsConfigFilename = System.getProperty("user.home") + "/.CV-Navi/" + "CV-Navi.xml"; static String gsConfigComment = "Tams CV Navi"; public String gsZentrale = "MasterControl"; private int lcZentrale = 2; private TwoWaySerialComm KTUICom = null; private TwoWaySerialComm ExternalCom = null; private Boolean bVerifyZentraleInProgress = false; private Timer timer = null; public static Boolean bZentraleVerified = false; public String fwVersion = null; public static Boolean bUseXfuncs = false; // MC >= 1.4.6f ; OpenDCC >= 23.08 ; IB >= 2.000 public static Boolean bUseXm3sid = false; // MC >= 1.4.7b public static Boolean bUseSo999 = false; // MC >= 1.4.8c public String gsSchnittstelle = "noCom"; public int gsBaudRate = -1 ; public boolean gsRtsCts = true; public String gsLastMcConfLoad = "NoData" ; public String gsLastMcConfSave = "NoData" ; public int gsDecoderIndex = -1 ; public String gsLookAndFeel = "Nothing" ; public String gsSaveOpenDirectory ; public String gsSaveOpenFilename ; public String gsSaveOpenKennDirectory ; public String gsSaveOpenKennFilename ; public String gsSaveOpenMcDirectory ; public String gsSaveOpenMcFilename ; public String gsSaveOpenM3Directory ; public String gsSaveOpenM3Filename ; public String gsOpenFirmwareDirectory ; public String gsOpenFirmwareFilename ; // public String gsReadBuffer; public Boolean lastSaveOpenDialogWasCancel; public Dimension SODlocalSize ; public Point mainWindowLocation; public boolean bGotoUpdate; public enum ModeZentrale { Halted, PwrOn, PwrOff, DCCprogram, Reset, UNKNOWN }; public enum MZ { UNKNOWN, STOP, GO }; public ModeZentrale gModeZentrale = ModeZentrale.UNKNOWN ; public MZ gMZvorAktion = MZ.UNKNOWN ; private ResourceBundle bundle; private int numS88 = 0; public KlarTextUI() { this.lastSaveOpenDialogWasCancel = false; mainWindowLocation = new Point(); ImageIcon i = new ImageIcon(getClass().getResource("/main.gif")); this.setIconImage(i.getImage()); initComponents(); jDecoderChooser.setSelectedIndex(c.MC); jLabelProgVersion.setText("Version " + gsVersionMayor + "." + gsVersionMinor); setLocationRelativeTo(null); fillMenuSelection(); bundle = java.util.ResourceBundle.getBundle("my.KlarText/Bundle"); if( debugLevel >= 3 ) { for(decoderList co : decoderList.values()) { System.out.printf("decoderList[%2d] [%2d] (%s) %10s Text %-35s %s\n", co.ordinal(), co.getIdx(), co.isSelectable()?"X":" ", co, co.getMenutextGer(), co.getMenutextEng()); } } } public void setZentrale( int newZentrale ) { switch (newZentrale) { case c.cuOpenDCC: lcZentrale = newZentrale; gsZentrale = "OpenDCC"; break; case c.cuIntellibox1: lcZentrale = newZentrale; gsZentrale = "Intellibox"; break; default: lcZentrale = c.cuMasterControl ; gsZentrale = "MasterControl"; } } public void setZentrale( String newZentrale ) { switch (newZentrale) { case "OpenDCC": lcZentrale = c.cuOpenDCC; gsZentrale = newZentrale; break; case "Intellibox": lcZentrale = c.cuIntellibox1; gsZentrale = newZentrale; break; default: // all other cases lcZentrale = c.cuMasterControl ; gsZentrale = "MasterControl"; break; } } public int getZentrale() { return lcZentrale; } public int getDecoderChooser() { return(jDecoderChooser.getSelectedIndex()); } public void setDecoderChooser( int n ) { if( n >= 0 ) jDecoderChooser.setSelectedIndex(n); } public boolean setModeZentrale( String mode ) { switch(mode) { // "Pwr off", "Halted!", "Pwr on", "DCC program" oder "RESET" case "Pwr on": gModeZentrale = ModeZentrale.PwrOn ; break; case "Halted!": gModeZentrale = ModeZentrale.Halted ; break; case "Pwr off": gModeZentrale = ModeZentrale.PwrOff ; break; case "DCC program": gModeZentrale = ModeZentrale.DCCprogram ; break; case "RESET": gModeZentrale = ModeZentrale.Reset ; break; default: System.out.println("setModeZentrale UNEXPECTED mode="+mode); return false; } return true; } public ModeZentrale getModeZentrale() { return gModeZentrale; } public MZ getMZ() { switch( gModeZentrale ) { case Halted: case PwrOn: return MZ.GO; case PwrOff: case DCCprogram: case Reset : return MZ.STOP; case UNKNOWN: default: return MZ.UNKNOWN; } } public String getModeZentraleAsStringLong() { switch( gModeZentrale ) { case Halted: return"Halted"; case PwrOn: return"PwrOn"; case PwrOff: return"PwrOff"; case DCCprogram: return"DCCprogram"; case Reset : return"Reset"; case UNKNOWN: default: return "???"; } } public String getModeZentraleAsStringShort() { switch( gModeZentrale ) { case Halted: case PwrOn: return"GO"; case PwrOff: case DCCprogram: case Reset : return"STOP"; case UNKNOWN: default: return "???"; } } public String getMenutext( decoderList dl ) { if( dl == null ) { return "CV-Navi"; } else { if( bSpracheDE ) { return dl.getMenutextGer(); } else { return dl.getMenutextEng(); } } } public int getNumS88() { return numS88; } public void setNumS88( int num ) { if( checkNumRange( num, 0, c.maxS88 ) ) { numS88 = num; } } public void mbTest( Container cont, Boolean modal ) { System.out.println("mbTest" ); MsgBox messageBox = new MsgBox( (Frame) this.getParent(), modal, cont); messageBox.jLabel1.setText("Test!"); messageBox.jLabel2.setText("Decoder: "+Decoder+" SS: " + gsSchnittstelle); messageBox.jLabel3.setText("Test."); messageBox.setVisible(true); } public void mbGeneric( Container cont, String s1 ) { mbGeneric( cont, s1, null, null, 0, true ); } public void mbGeneric( Container cont, String s1, Boolean modal ) { mbGeneric( cont, s1, null, null, 0, modal ); } public void mbGeneric( Container cont, String s1, int seconds ) { mbGeneric( cont, s1, null, null, seconds, true ); } public void mbGeneric( Container cont, String s1, int seconds, Boolean modal ) { mbGeneric( cont, s1, null, null, seconds, modal ); } public void mbGeneric( Container cont, String s1, String s2 ) { mbGeneric( cont, s1, s2, null, true ); } public void mbGeneric( Container cont, String s1, String s2, Boolean modal ) { mbGeneric( cont, s1, s2, null, modal ); } public void mbGeneric( Container cont, String s1, String s2, int seconds ) { mbGeneric( cont, s1, s2, null, seconds, true ); } public void mbGeneric( Container cont, String s1, String s2, int seconds, Boolean modal ) { mbGeneric( cont, s1, s2, null, seconds, modal ); } public void mbGeneric( Container cont, String s1, String s2, String s3 ) { mbGeneric( cont, s1, s2, s3, 0, true ); } public void mbGeneric( Container cont, String s1, String s2, String s3, Boolean modal ) { mbGeneric( cont, s1, s2, s3, 0, modal ); } public void mbGeneric( Container cont, String s1, String s2, String s3, int seconds ) { mbGeneric( cont, s1, s2, s3, seconds, true ); } public void mbGeneric( Container cont, String s1, String s2, String s3, int seconds, Boolean modal ) { // System.out.println("mbGeneric seconds="+seconds+" modal="+modal+" Container name="+c.getName()+" string=" +c.toString()); MsgBox messageBox = new MsgBox( (Frame) this.getParent(), modal, cont); messageBox.jLabel1.setText(s1==null?"":s1); messageBox.jLabel2.setText(s2==null?"":s2); messageBox.jLabel3.setText(s3==null?"":s3); messageBox.setCountdown(seconds); messageBox.pack(); messageBox.setLocationRelativeTo(cont); messageBox.setVisible(true); } public void mbVerifyXVer(Container cont, String verInfo, Boolean mismatch) { String dbgOptions =""; if( debugLevel > 0 ) { dbgOptions = "(Xfuncs="+bUseXfuncs+" Xm3sid="+bUseXm3sid+")"; } if( mismatch ) { mbGeneric(cont, bundle.getString("Configrationmismatch"), bundle.getString("Configured")+gsZentrale, bundle.getString("Detected")+verInfo+" "+dbgOptions, 0, true); } else { if( debugLevel > 0 ) { mbGeneric(cont, "Information", verInfo, "OK "+dbgOptions, 5, false); } } } public void mbNotAvailable( Container cont, String s3) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information"); messageBox.jLabel2.setText(bundle.getString("notavailable")); messageBox.jLabel3.setText(s3==null?"":s3); messageBox.setVisible(true); } public void mbDeviceConnectProblem( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Openfailed")); messageBox.setVisible(true); } public void mbDeviceConnectProblemOffline( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Openfailed") + "-> Offline Modus"); messageBox.setCountdown(5); messageBox.setVisible(true); } public void mbDeviceDisconnectProblem( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Closefailed")); messageBox.setVisible(true); } public void mbDeviceReadProblem( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Readfailed")); messageBox.setVisible(true); } public void mbDeviceWriteProblem( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Problemswithport") + gsSchnittstelle); messageBox.jLabel3.setText(bundle.getString("Writefailed")); messageBox.setVisible(true); } public void mbDeviceOwned( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText("Interface " + gsSchnittstelle + bundle.getString("busy")); messageBox.setVisible(true); } public void mbDeviceNotSupported( Container cont, int seconds ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Hinweis")); messageBox.jLabel2.setText(bundle.getString("notsupported")); messageBox.jLabel3.setText(""); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbUpdateWriteSuccess( Container cont, int block ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Hinweis")); messageBox.jLabel2.setText(bundle.getString("successful")); messageBox.jLabel3.setText("" + block + " " +bundle.getString("transferred")); messageBox.setCountdown(5); messageBox.setVisible(true); } public void mbUpdateWriteError( Container cont, char c ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont ); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Unexpected") + " " + c + " " + bundle.getString("empfangen")); messageBox.jLabel3.setText(bundle.getString("restartupdate")); messageBox.setVisible(true); } public void mbUpdateWriteError( Container cont, String s ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont ); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Unexpected") + " " + s + " " + bundle.getString("empfangen")); messageBox.jLabel3.setText(bundle.getString("restartupdate")); messageBox.setVisible(true); } public void mbUpdateReadAnswerError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Noanswer")); messageBox.jLabel3.setText(bundle.getString("Updatecancelled")); messageBox.setVisible(true); } public void mbConfigReadSuccess( Container cont ) { mbConfigReadSuccess( cont, 0); } public void mbConfigReadSuccess( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information:"); messageBox.jLabel2.setText(bundle.getString("successfullyread")); messageBox.jLabel3.setText(""); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigReadAbort( Container cont ) { mbConfigReadAbort( cont, 0); } public void mbConfigReadAbort(Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Problem!"); messageBox.jLabel2.setText(bundle.getString("readaborted")); messageBox.jLabel3.setText(bundle.getString("notprocessed")); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigReadCancelled( Container cont ) { mbConfigReadCancelled( cont, 0); } public void mbConfigReadCancelled( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information:"); messageBox.jLabel2.setText(bundle.getString("readaborted")); messageBox.jLabel3.setText(bundle.getString("incomplete")); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbRWCancelled( Container cont ) { mbRWCancelled( cont, 0); } public void mbRWCancelled( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information:"); messageBox.jLabel2.setText(bundle.getString("readwritecancelled")); messageBox.jLabel3.setText(bundle.getString("incomplete")); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigWriteCancelled( Container cont ) { mbConfigWriteCancelled( cont, 0); } public void mbConfigWriteCancelled( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information:"); messageBox.jLabel2.setText(bundle.getString("readwritecancelled")); messageBox.jLabel3.setText(bundle.getString("incomplete")); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigWriteSuccess( Container cont ) { mbConfigWriteSuccess( cont, 0); } public void mbConfigWriteSuccess( Container cont, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information"); messageBox.jLabel2.setText(bundle.getString("successfullywritten")); messageBox.jLabel3.setText(""); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbConfigWriteSuccessMcWithProblems( Container cont, int errBits ) { if( errBits == 0 ) { mbConfigWriteSuccess( cont ); return; } MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if( bSpracheDE) { messageBox.jLabel1.setText("Schreiben erfolgreich."); messageBox.jLabel2.setText("ACHTUNG! Einige Eingaben waren falsch und wurden korrigiert:"); String sFehler = "("; if((errBits & 0x0007) != 0 ) sFehler += "Adressfehler: "; if((errBits & 0x0001) == 0x0001 ){ sFehler += "DCC"; if((errBits & 0x0006) != 0) { sFehler += ", "; } } if((errBits & 0x0002) == 0x0002 ) { sFehler += "MM"; if((errBits & 0x0004) != 0) { sFehler += ", "; } } if((errBits & 0x0004) == 0x0004 ) sFehler += "m3"; if(((errBits & 0x00F8) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0008) == 0x0008 ) sFehler += "Formatfehler"; if(((errBits & 0x00F0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0010) == 0x0010 ) sFehler += "Fahrstufenfehler"; if(((errBits & 0x00E0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0020) == 0x0020 ) sFehler += "Name zu lang"; if(((errBits & 0x00C0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0040) == 0x0040 ) sFehler += "Adressfehler Doppeltraktion"; if(((errBits & 0x0080) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0080) == 0x0080 ) sFehler += "Formatfehler Acc-Decoder"; sFehler += ")"; messageBox.jLabel3.setText(sFehler); } else { messageBox.jLabel1.setText("Configuration data successfully sent."); messageBox.jLabel2.setText("ATTENTION! Some data was corrected while writing:"); String sFehler = "("; if((errBits & 0x0007) != 0) sFehler += "loco address error: "; if((errBits & 0x0001) == 0x0001 ) { sFehler += "DCC"; if((errBits & 0x0006) != 0) { sFehler += ", "; } } if((errBits & 0x0002) == 0x0002 ) { sFehler += "MM"; if((errBits & 0x0004) != 0) { sFehler += ", "; } } if((errBits & 0x0004) == 0x0004 ) sFehler += "m3"; if(((errBits & 0x00F8) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0008) == 0x0008 ) sFehler += "format error"; if(((errBits & 0x00F0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0010) == 0x0010 ) sFehler += "speed step error"; if(((errBits & 0x00E0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0020) == 0x0020 ) sFehler += "name too long"; if(((errBits & 0x00C0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0040) == 0x0040 ) sFehler += "traction address error"; if(((errBits & 0x0080) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0080) == 0x0080 ) sFehler += "accessory format error"; sFehler += ")"; messageBox.jLabel3.setText(sFehler); } messageBox.setVisible(true); } public void mbConfigWriteError( Container cont ) { mbConfigWriteError( cont, "", 0); } public void mbConfigWriteError( Container cont, String sError ) { mbConfigWriteError( cont, sError, 0); } public void mbConfigWriteError( Container cont, String sError, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Errorwriting")); if( (sError != null) && (sError.length() > 0 ) ) { messageBox.jLabel3.setText(sError); } else { messageBox.jLabel3.setText(""); } messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbM3TooMany( Container cont ) { mbGeneric( cont, "Problem", bundle.getString("UIDSIDPaare"), bundle.getString("MaxAnz")+c.MAX_M3_ENTRIES, 0, true); return; } public void mbTableCheckOK( Container cont, boolean repair, int seconds) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText("Information"); if( repair ) { messageBox.jLabel2.setText(bundle.getString("TabellenreparaturOK")); } else { messageBox.jLabel2.setText(bundle.getString("TablecheckedOK")); } messageBox.jLabel3.setText(""); messageBox.setCountdown(seconds); messageBox.setVisible(true); } public void mbTableCheck( Container cont, int errBits ) { mbTableCheck( cont, errBits, false, null ); return; } public void mbTableCheck( Container cont, int errBits, boolean repair ) { mbTableCheck( cont, errBits, repair, null ); return; } public void mbTableCheck( Container cont, int errBits, boolean repair, String sList ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if( bSpracheDE) { if( sList != null ) { messageBox.jLabel1.setText("Probleme in Zeile(n)"+sList+" festgestellt!"); } else { messageBox.jLabel1.setText("Probleme festgestellt!"); } if( repair ) messageBox.jLabel2.setText("ACHTUNG! Einige Eingaben waren falsch und wurden korrigiert:"); else messageBox.jLabel2.setText("ACHTUNG! Einige Eingaben sind falsch:"); String sFehler = "("; if((errBits & 0x0007) != 0 ) sFehler += "Adressfehler: "; if((errBits & 0x0001) == 0x0001 ){ sFehler += "DCC"; if((errBits & 0x0006) != 0) { sFehler += ", "; } } if((errBits & 0x0002) == 0x0002 ) { sFehler += "MM"; if((errBits & 0x0004) != 0) { sFehler += ", "; } } if((errBits & 0x0004) == 0x0004 ) sFehler += "m3"; if(((errBits & 0x00F8) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0008) == 0x0008 ) sFehler += "Formatfehler"; if((errBits & 0x0010) != 0) { if(sFehler.length() > 1) sFehler += " ; "; sFehler += "Fahrstufenfehler"; } if((errBits & 0x0020) != 0) { if(sFehler.length() > 1) sFehler += " ; "; sFehler += "Name zu lang"; } if((errBits & 0x0040) != 0) { if(sFehler.length() > 1) sFehler += " ; "; sFehler += "Adressfehler Doppeltraktion"; } if((errBits & 0x0080) != 0) { if(sFehler.length() > 1) sFehler += " ; "; sFehler += "Formatfehler Acc-Decoder"; } sFehler += ")"; messageBox.jLabel3.setText(sFehler); } else { if( sList != null ) { messageBox.jLabel1.setText("Problems in line(s)"+sList+" detected!"); } else { messageBox.jLabel1.setText("Problems detected!"); } if( repair ) messageBox.jLabel2.setText("ATTENTION! Some data was corrected:"); else messageBox.jLabel2.setText("ATTENTION! Some data is wrong:"); String sFehler = "("; if((errBits & 0x0007) != 0) sFehler += "loco address error: "; if((errBits & 0x0001) == 0x0001 ) { sFehler += "DCC"; if((errBits & 0x0006) != 0) { sFehler += ", "; } } if((errBits & 0x0002) == 0x0002 ) { sFehler += "MM"; if((errBits & 0x0004) != 0) { sFehler += ", "; } } if((errBits & 0x0004) == 0x0004 ) sFehler += "m3"; if(((errBits & 0x00F8) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0008) == 0x0008 ) sFehler += "format error"; if(((errBits & 0x00F0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0010) == 0x0010 ) sFehler += "speed step error"; if(((errBits & 0x00E0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0020) == 0x0020 ) sFehler += "name too long"; if(((errBits & 0x00C0) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0040) == 0x0040 ) sFehler += "traction address error"; if(((errBits & 0x0080) != 0)&& sFehler.length() > 1) sFehler += " ; "; if((errBits & 0x0080) == 0x0080 ) sFehler += "accessory format error"; sFehler += ")"; messageBox.jLabel3.setText(sFehler); } ModalExclusionType MET = messageBox.getModalExclusionType(); String t = "" + MET ; System.out.println("MET = ["+t+"]"); messageBox.setModalExclusionType(ModalExclusionType.APPLICATION_EXCLUDE); messageBox.setVisible(true); } public void mbFileNotFound( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Filenotfound")); messageBox.setVisible(true); } public void mbFileNotFound( Container cont, String name) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Filenotfound") + ": "+name); messageBox.setVisible(true); } public void mbFileOpenError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Filenotopenend")); messageBox.setVisible(true); } public void mbFileOpenError( Container cont, String name) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Filenotopenend") + ": "+name); messageBox.setVisible(true); } public void mbFileWriteError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Problemswriting")); messageBox.setVisible(true); } public void mbFileReadError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("Problemsreading")); messageBox.setVisible(true); } public void mbFileHexFormatError( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("noHEX")); messageBox.jLabel3.setText(bundle.getString("chooseHEX")); messageBox.setVisible(true); } public void mbFileReadBeginError( Container cont, String begin) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText(bundle.getString("notstarting") + begin ); messageBox.setVisible(true); } public void mbTimeout( Container cont ) { mbTimeout( cont, 0 ); } public void mbTimeout( Container cont, int errCode ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if(bSpracheDE) { messageBox.jLabel1.setText("Achtung!"); switch( errCode ) { case c.mbRDtimeout: messageBox.jLabel2.setText("Zentrale meldet Timeout beim Lesen!"); messageBox.jLabel3.setText("Auslesen abgebrochen."); break; case c.mbWRtimeout: messageBox.jLabel2.setText("Zentrale meldet Timeout beim Schreiben!"); messageBox.jLabel3.setText("Schreiben abgebrochen."); break; case c.mbMCRDtimeout: messageBox.jLabel2.setText("Timeout beim Lesen aus der Zentrale!"); messageBox.jLabel3.setText("Auslesen abgebrochen."); break; case c.mbRDtooShort: messageBox.jLabel2.setText("Antwort zu kurz beim Lesen aus der Zentrale!"); messageBox.jLabel3.setText("Auslesen abgebrochen."); break; case c.mbMCRDcommitErr: messageBox.jLabel2.setText("Timeout beim Warten auf eine Antwort der Zentrale!"); messageBox.jLabel3.setText("Bitte Verbindung überprüfen."); break; case c.mbMCWRtimeout: messageBox.jLabel2.setText("Timeout beim Schreiben in die Zentrale!"); messageBox.jLabel3.setText("Schreiben abgebrochen."); break; case c.mbRDverify: messageBox.jLabel2.setText("Timeout beim Verifizieren der Zentrale!"); messageBox.jLabel3.setText(""); break; default: messageBox.jLabel2.setText("Timeout aufgetreten!"); messageBox.jLabel3.setText(""); } } else { messageBox.jLabel1.setText("WARNING!"); switch( errCode ) { case c.mbRDtimeout: messageBox.jLabel2.setText("Control unit reports timeout on read!"); messageBox.jLabel3.setText("read cancelled"); break; case c.mbWRtimeout: messageBox.jLabel2.setText("Control unit reports timeout on write!"); messageBox.jLabel3.setText("write cancelled"); break; case c.mbMCRDtimeout: messageBox.jLabel2.setText("Timeout reading data from control unit!"); messageBox.jLabel3.setText("read cancelled"); break; case c.mbRDtooShort: messageBox.jLabel2.setText("Answer too short while reading data from control unit!"); messageBox.jLabel3.setText("read cancelled"); break; case c.mbMCRDcommitErr: messageBox.jLabel2.setText("Timeout waiting for an answer from control unit!"); messageBox.jLabel3.setText("Please check connection."); break; case c.mbMCWRtimeout: messageBox.jLabel2.setText("Timeout writing data to control unit!"); messageBox.jLabel3.setText("write cancelled"); break; case c.mbRDverify: messageBox.jLabel2.setText("Timeout verifying control unit!"); messageBox.jLabel3.setText(""); break; default: messageBox.jLabel2.setText("Timeout occured!"); messageBox.jLabel3.setText(""); } } messageBox.setVisible(true); } public void mbTimeoutMcUpdStart( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if(bSpracheDE) { messageBox.jLabel1.setText("keine Verbindung zur MasterControl!"); messageBox.jLabel2.setText("Bitte Verbindung überprüfen und"); messageBox.jLabel3.setText("MC in Update-Modus setzen (Stop + GO beim Einschalten drücken)!"); } else { messageBox.jLabel1.setText("No connection to MasterControl!"); messageBox.jLabel2.setText("Please check connectivity and "); messageBox.jLabel3.setText("set MC in update mode: Press Stop + GO while switching power on!"); } messageBox.setVisible(true); } public void mbEnablePower( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if(bSpracheDE) { messageBox.jLabel1.setText("Schienenspannung ist aus!"); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText("Bitte Schienenspannung einschalten und erneut probieren"); } else { messageBox.jLabel1.setText("Track Power is off!"); messageBox.jLabel2.setText(""); messageBox.jLabel3.setText("Please enable Power and try again"); } messageBox.setVisible(true); } public void mbNoTams( Container cont ) { mbNoTams( cont, 0 ); } public void mbNoTams( Container cont, int errCode ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); if(bSpracheDE) { messageBox.jLabel1.setText("Achtung!"); messageBox.jLabel2.setText("Dies ist kein Tams Decoder!"); switch( errCode ) { case c.mbRDcancel: messageBox.jLabel3.setText("weiteres Auslesen abgebrochen."); break; case c.mbWRcancel: messageBox.jLabel3.setText("weiteres Schreiben abgebrochen."); break; default: messageBox.jLabel3.setText(""); } } else { messageBox.jLabel1.setText("WARNING!"); messageBox.jLabel2.setText("This is no Tams device!"); switch( errCode ) { case c.mbRDcancel: messageBox.jLabel3.setText("read cancelled"); break; case c.mbWRcancel: messageBox.jLabel3.setText("write cancelled"); break; default: messageBox.jLabel3.setText(""); } } messageBox.setVisible(true); } public void mbNoTamsMC( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Fehler")); messageBox.jLabel2.setText(bundle.getString("Wrongcu") + gsZentrale + "\" "+bundle.getString("configured")); messageBox.jLabel3.setText(bundle.getString("PleaseSelectMC")); messageBox.setVisible(true); } public void mbNoS88modules( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("Information")); messageBox.jLabel2.setText(bundle.getString("NoS88modules")); messageBox.jLabel3.setText(bundle.getString("SkipS88monitor")); messageBox.setVisible(true); } public void mbInvalidValue( Container cont, int cv, int value, String validValues ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText("CV# "+cv+bundle.getString("invalidvalue")+value); if( validValues.length() > 0) { messageBox.jLabel3.setText(bundle.getString("Validvalues")+validValues); } messageBox.setVisible(true); } public void mbValueTooSmall( Container cont ) { mbValueTooSmall( cont, 0, 0, false); } public void mbValueTooSmall( Container cont, int low, int high, boolean showRange ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valuetoosmall")); if(bSpracheDE) { if( showRange ) { messageBox.jLabel3.setText("Bitte einen Wert zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" eingeben."); } else { messageBox.jLabel3.setText("Bitte einen größeren Wert eingeben."); } } else { if( showRange ) { messageBox.jLabel3.setText("Please enter a value between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Please enter a higher value."); } } messageBox.setVisible(true); } public void mbValueTooBig( Container cont ) { mbValueTooBig( cont, 0, 0, false); } public void mbValueTooBig( Container cont, int low, int high, boolean showRange ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valuetoobig")); if(bSpracheDE) { if( showRange ) { messageBox.jLabel3.setText("Bitte einen Wert zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" eingeben."); } else { messageBox.jLabel3.setText("Bitte einen kleineren Wert eingeben."); } } else { if( showRange ) { messageBox.jLabel3.setText("Please enter a value between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Please enter a lower value."); } } messageBox.setVisible(true); } public void mbValueNaN( Container cont ) { mbValueNaN( cont, 0, 0, false); } public void mbValueNaN( Container cont, int low, int high, boolean showRange ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valueinvalid")); if(bSpracheDE) { if( showRange ) { messageBox.jLabel3.setText("Bitte einen Wert zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" eingeben."); } else { messageBox.jLabel3.setText("Bitte einen korrekten Wert eingeben."); } } else { if( showRange ) { messageBox.jLabel3.setText("Please use a value between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Please use a valid value."); } } messageBox.setVisible(true); } public void mbValueNaNcv( Container cont, int low, int high, int cv, boolean showRange ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valueinvalid")); if(bSpracheDE) { if( showRange ) { messageBox.jLabel3.setText("CV#"+cv+" muß einen Wert zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" haben."); } else { messageBox.jLabel3.setText("Bitte einen korrekten Wert für CV#"+cv+" eingeben."); } } else { if( showRange ) { messageBox.jLabel3.setText("CV#"+cv+" must have a value between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Please use a valid value for CV#"+cv); } } messageBox.setVisible(true); } public void mbValueConsist( Container cont, int low, int high ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); messageBox.jLabel2.setText(bundle.getString("Valueinvalid")); if(bSpracheDE) { messageBox.jLabel3.setText("Gültige Werte für Consist-Adresse zwischen "+Integer.toString(low)+" und "+Integer.toString(high)+" ."); } else { messageBox.jLabel3.setText("Valid consist address is between "+Integer.toString(low)+" and "+Integer.toString(high)+" ."); } messageBox.setVisible(true); } public void mbAdr128MMonly( Container cont ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); if(bSpracheDE) { messageBox.jLabel2.setText("Nur für MM."); messageBox.jLabel3.setText("Bei kurzen Adressen zwischen 128 und 255 reagiert der Decoder nur noch auf MM-Befehle!"); } else { messageBox.jLabel2.setText("Only for MM."); messageBox.jLabel3.setText("Short addresses between 128 and 255 are for MM protocol only!"); } messageBox.setVisible(true); } public void mbBlinkFrequenz( Container cont, int dauer, int pause, String eingabe ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); if(bSpracheDE) { // "Wert \""+jBlink_Pausezeit_1.getText()+"\" ungültig.", "Bitte einen Wert zwischen 0 und Blinkfrequenz minus 2xein eingeben." messageBox.jLabel2.setText("Eingabe \""+eingabe+"\" für Frequenz ist ungültig."); messageBox.jLabel3.setText("Bitte einen Wert zwischen "+((dauer*2)+pause)+" und 255 eingeben. ( Minimum = ( Blinkdauer("+dauer+") * 2 ) plus Pause("+pause+") )"); } else { messageBox.jLabel2.setText("Input \""+eingabe+"\" for frequency is invalid."); messageBox.jLabel3.setText("Please use a value between "+((dauer*2)+pause)+" and 255. ( min = ( onTime("+dauer+") * 2 ) plus pause("+pause+") ) "); } messageBox.pack(); // resize to fit contents before making visible ;) messageBox.setVisible(true); } public void mbBlinkEinschaltzeit( Container cont, int freq, int pause, String eingabe ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); if(bSpracheDE) { // "Wert \""+jBlink_Pausezeit_1.getText()+"\" ungültig.", "Bitte einen Wert zwischen 0 und Blinkfrequenz minus 2xein eingeben." messageBox.jLabel2.setText("Eingabe \""+eingabe+"\" für Einschaltzeit ist ungültig."); messageBox.jLabel3.setText("Bitte einen Wert zwischen 0 und "+((freq-pause)/2)+" eingeben. ( = ( Blinkfrequenz("+freq+") minus Pause("+pause+") geteilt durch 2 ) )"); } else { messageBox.jLabel2.setText("Input \""+eingabe+"\" for onTime is invalid."); messageBox.jLabel3.setText("Please use a value between 0 and "+((freq-pause)/2)+" ( = ( flash freqeuncy("+freq+") minus pause("+pause+") ) / 2 )"); } messageBox.pack(); // resize to fit contents before making visible ;) messageBox.setVisible(true); } public void mbBlinkPausezeit( Container cont, int freq, int dauer, String eingabe ) { MsgBox messageBox = new MsgBox( (Frame) this.getParent(), true, cont); messageBox.jLabel1.setText(bundle.getString("ACHTUNG")); if(bSpracheDE) { // "Wert \""+jBlink_Pausezeit_1.getText()+"\" ungültig.", "Bitte einen Wert zwischen 0 und Blinkfrequenz minus 2xein eingeben." messageBox.jLabel2.setText("Eingabe \""+eingabe+"\" für Pause ist ungültig."); messageBox.jLabel3.setText("Bitte einen Wert zwischen 0 und "+(freq-(2*dauer))+" eingeben. ( = Blinkfrequenz("+freq+") minus 2 * Einschaltdauer("+dauer+") )"); } else { messageBox.jLabel2.setText("Input \""+eingabe+"\" for pause is invalid."); messageBox.jLabel3.setText("Please use a value between 0 and "+(freq-(2*dauer))+" ( = flash freqeuncy("+freq+") minus 2 * OnTime("+dauer+") )"); } messageBox.setVisible(true); } public int yesNoResetFactoryDefault() { int dialogResult = -1; if(bSpracheDE) { Object[] options = { "Ja", "Nein" }; dialogResult = JOptionPane.showOptionDialog( this, "Zurücksetzen aller Werte auf Auslieferungszustand.\n\nSind Sie sicher?", "Warnung", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1] ); } else { Object[] options = { "Yes", "No" }; dialogResult = JOptionPane.showOptionDialog( this, "Reset all values to factory defaults.\n\nAre you sure?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[1] ); } return dialogResult; } public int yesNoM3listSave() { int dialogResult = -1; if(bSpracheDE) { Object[] options = { "Ja", "Nein" }; dialogResult = JOptionPane.showOptionDialog( this, "M3 UID/SID-Liste wurde geändert.\n\nSoll die Liste gesichert werden?", "Warnung", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); } else { Object[] options = { "Yes", "No" }; dialogResult = JOptionPane.showOptionDialog( this, "M3 UID/SID list changed.\n\nDo you want to save?", "Warning", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, options, options[0] ); } return dialogResult; } // Checks public int checkTextFieldUnit( Container cont, JTextField textField, int minValue, int maxValue, int defValue, int unit, boolean show ) { int i = checkTextField( cont, textField, minValue, maxValue, defValue, show ); int j = (i/unit)*unit; if( i != j ) { textField.setText(Integer.toString(j)); } return j; } public int checkTextField( Container cont, JTextField textField, int minValue, int maxValue, int defValue, boolean show ) { int value; try { value = Integer.parseInt(textField.getText()); if(value < minValue) { if( show ) { mbValueTooSmall( cont, minValue, maxValue, true ); textField.grabFocus(); } value = minValue; textField.setText("" + value); } if(value > maxValue) { if( show ) { mbValueTooBig( cont, minValue, maxValue, true ); textField.grabFocus(); } value = maxValue; textField.setText("" + value); } } catch (NumberFormatException numberFormatException) { if( show ) { mbValueNaN( cont, minValue, maxValue, true ); textField.grabFocus(); } value = defValue; textField.setText("" + value); } return value; } public boolean checkNumRange( String sValue, int minValue, int maxValue ) { try { int value = Integer.parseInt(sValue); return( checkNumRange( value, minValue, maxValue ) ); } catch (NumberFormatException numberFormatException) { return false; } } public boolean checkNumRange( int value, int minValue, int maxValue ) { if(value < minValue) return false; if(value > maxValue) return false; return true; } public int checkAndGetStrNumRangeDef( Container cont, String sValue, int minValue, int maxValue, int defValue, boolean show ) { int value; try { value = Integer.parseInt(sValue); if(value < minValue) { if( show ) mbValueTooSmall( cont, minValue, maxValue, true ); value = minValue; } if(value > maxValue) { if( show ) mbValueTooBig( cont, minValue, maxValue, true ); value = maxValue; } } catch (NumberFormatException numberFormatException) { if( show ) mbValueNaN( cont, minValue, maxValue, true ); value = defValue; } return value; } public Boolean setCVvalue( int[][] CV, int cv, int value ) { if( CV == null ) { return false; } int CVlen = CV[0].length ; if( checkNumRange( cv, 1, CVlen) && checkNumRange( value, 0, 255) ) { CV[0][cv] = cv; CV[1][cv] = value ; return true; } return false; } public Boolean unsetCVvalue( int[][] CV, int cv ) { if( CV == null ) { return false; } int CVlen = CV[0].length ; if( checkNumRange( cv, 1, CVlen) ) { CV[0][cv] = 0; CV[1][cv] = 0 ; return true; } return false; } /** * * @param bArray answer from command station * @return CV value <b>OR</b> <br> -1 if bArray is null pointer or an invalid answer <br> -2 answer is incomplete */ public int checkPTRDAnswer( byte[] bArray ) { if( bArray == null ) { return -1; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = |\r|\\000"); if( debugLevel >= 3 ) { for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkPTRDAnswer 1622 strParts["+i+"]("+strParts[i].length()+")=\""+strParts[i]+"\""+((strParts[i].equals("]"))?" (ENDE)":"" )); } } int cvWert = -1; if( strParts.length > 0) { if( ! strParts[(strParts.length-1)].equals("]") ) { // answer is not complete ! if( debugLevel >= 3 ) { System.out.println("checkPTRDAnswer 1630 strParts.length="+strParts.length+" strParts["+(strParts.length-1)+"]=["+strParts[strParts.length-1]+"] INCOMPLETE"); } return -2; } // answer is complete if( debugLevel >= 4 ) { if( strParts[(strParts.length-1)].equals("]") ) { System.out.println("checkPTRDAnswer 1637 strParts[(strParts.length-1)].equals(\"[\") Yes"); } else { System.out.println("checkPTRDAnswer 1639 strParts[(strParts.length-1)].equals(\"[\") NO"); } } if( strParts[0].equalsIgnoreCase("No ack") ) { System.out.println("checkPTRDAnswer 1644 strParts[0]=["+strParts[0]+"]" ); return -1; } // convert first part to integer String s = ""; try { s = ""+strParts[0]; cvWert = Integer.parseInt(s); } catch (NumberFormatException ex) { System.out.println("checkPTRDAnswer 1516 Eception ex["+ex+"]"); for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkPTRDAnswer 1655 strParts["+i+"]=\""+strParts[i]+"\""+((strParts[i].startsWith("]"))?" (ENDE)":"" )); } } } return cvWert; } /** * * @param bArray answer from command station * @return true answer is complete (last answer line starts with "]") */ public boolean checkAnswerComplete( byte[] bArray ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = |\r|\\000"); if( debugLevel >= 3 ) { for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkAnswerComplete 1668 strParts["+i+"]=\""+strParts[i]+"\""+((strParts[i].startsWith("]"))?" (ENDE)":"" )); } } if( strParts.length > 0) { if( strParts[(strParts.length-1)].startsWith("]") ) { // answer is complete ! if( debugLevel >= 3 ) { System.out.println("checkAnswerComplete 1505 strParts.length="+strParts.length+" strParts["+(strParts.length-1)+"]=["+strParts[strParts.length-1]+"] COMPLETE"); } return true; } } return false; } /** * * @param bArray answer from command station * @return true answer is complete (last answer line starts with "]") */ public boolean checkReadComplete( byte[] bArray ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); int idxTerm = str_bArr.indexOf("\r]"); // line starting with "]" is end of data if( idxTerm >= 0 ) { return true; } return false; } /** * * @param bArray array of bytes (answer from command station) */ public void dumpbArray( byte[] bArray ) { if( bArray == null ) { return; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts //String[] strParts = str_bArr.split(" = |\r|\\000"); String[] strParts = str_bArr.split("\r|\\000"); dumpbArray( strParts ); } /** * * @param bArray array of bytes (answer from command station) */ public void dumpbArrayHex( byte[] bArray ) { if( bArray == null ) { return; } System.out.print("HEX: "); for (byte theByte : bArray) { System.out.printf( " %02x", theByte ); // System.out.print(Integer.toHexString(theByte)+" "); } System.out.println(""); } /** * * @param bArray array of bytes (answer from command station) * @return String with array in Hex */ public String dumpbArrayHexAsString( byte[] bArray ) { String sRet; String sTmp; String sTmp2; if( bArray == null ) { sRet = "null"; return sRet; } sTmp = ("HEX: "); for (byte theByte : bArray) { sTmp2 = String.format(" %02x", theByte); sTmp.concat(sTmp2); } sRet = sTmp; return sRet; } public void dumpbArrayBIN( byte[] bArray, int num ) { if( bArray == null ) { return; } for( int n = 0 ; n < num ; n++ ) { byte theByte = bArray[n]; System.out.printf( "HEX: 0x%02x BIN: %s\n", theByte, String.format("%8s", Integer.toBinaryString(theByte & 0xFF)).replace(' ', '0') ); } } /** * * @param strArray array of strings */ public void dumpbArray( String[] strArray ) { if( strArray == null ) { return; } for( int i = 0 ; i < strArray.length ; i++ ) { System.out.println("dumpbArray 1209 line["+i+"]("+strArray[i].length()+")=\""+strArray[i]+"\""+ (strArray[i].startsWith("]")?" (ENDE)":"") ); } } /** * * @param bArr array of bytes (answer from command station) * @param show if true show message box with raw error code * @return true if answer starts with 0x00 * * Liste der Error-Codes: 0x00 OK - kein Fehler, Befehl korrekt ausgeführt 0x02 XBADPRM - Parameterfehler (Parameterbyte außerhalb der zulässigen Werte) 0x06 XPWOFF - Befehl nicht ausgeführt, da MC im Modus STOP 0x07 XNOTSPC - Weichen-Queue ist voll, es können momentan keine weiterern Weichenbefehle angenommen werden. 0x08 XNOLSPC - Kein Platz im Kommandobuffer, Kommando später wiederholen 0x0A XNODATA - Lok ist nicht im Refresh-Buffer, daher kein Status verfügbar 0x0B XNOSLOT - Kein PLatz in der Refresh-Queue (Slot) 0x0D XLKBUSY - Lok wird bereits von einer anderen Unit kontrolliert 0x0E XBADTNP - Die Weichenadresse ist für das eingestellte Protokoll ungültig 0x41 XLKHALT - Lok-Kommando akzeptiert, aber nicht ausgeführt, da Steuerung im HALT-Modus ist. Die Geschwindigkeit wird auf 0 gesetzt. 0x42 XLKPOFF - Lok-Kommando akzeptiert, aber nicht ausgeführt, da Steuerung im STOP-Modus ist. Die Geschwindigkeit wird auf 0 gesetzt. */ public boolean checkMCAnswerByte( Container cont, byte[] bArr, Boolean show ) { if( bArr == null ) { if( show ) mbGeneric( cont, "checkMCAnswerByte", "invalid byteArray"); return false; } int len = bArr.length; if( len == 0 ) { if( show ) mbGeneric( cont, "checkMCAnswerByte", "byteArray is empty"); return false; } if( len > 1 ) { if( show ) mbGeneric( cont, "checkMCAnswerByte", "byteArray is too long (more than one byte)"); // was ist das denn ? } String errCode; errCode = bundle.getString("Errorcode"); if( debugLevel > 0 ) { System.out.println("checkMCAnswerByte: len="+len+" bArr[0]="+String.format("%02X ", bArr[0])); } switch( bArr[0] ) { case 0x00 : // OK return true; case 0x02 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XBADPRM"); break; case 0x06 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XPWOFF"); break; case 0x07 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XNOTSPC"); break; case 0x08 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XNOLSPC"); break; case 0x0A : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XNODATA"); break; case 0x0B : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XNOSLOT"); break; case 0x0D : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XLKBUSY"); break; case 0x0E : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XBADTNP"); break; case 0x41 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XLKHALT"); break; case 0x42 : if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode+" XLKPOFF"); // "Lok-Kommando akzeptiert, aber nicht ausgeführt, da Steuerung im STOP-Modus ist.\nDie Geschwindigkeit wird auf 0 gesetzt." ); break; default: if( show ) mbGeneric( cont, "checkMCAnswerByte", errCode, String.format(" %02X (unknown)", bArr[0])); } return false; } /** * * @param bArray array of bytes (answer from command station) * @return true if answer starts with "Ok" */ public boolean checkAnswerOK( byte[] bArray ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = |\r|\\000"); if( debugLevel >= 2 ) { for( int i = 0 ; i < strParts.length ; i++ ) { System.out.println("checkPTRDAnswer 1857 strParts["+i+"]("+strParts[i].length()+")=\""+strParts[i]+"\""+((strParts[i].startsWith("]"))?" (ENDE)":"" )); } } if( strParts.length > 0) { if( strParts[0].equalsIgnoreCase("Ok") ) { if( debugLevel >= 2 ) { System.out.println("checkPTWDAnswer 1232 strParts[0]=["+strParts[0]+"]" ); } return true; } } return false; } /** * * @param bArray array of bytes (answer from command station) * @return true if answer starts with "No ack" */ public boolean checkAnswerNoAck( byte[] bArray ) { if( bArray == null ) { return false; } // convert byteArray into a String String str_bArr = new String(bArray); // Split string into parts String[] strParts = str_bArr.split(" = |\r|\\000"); if( debugLevel >= 3 ) { dumpbArray( strParts ); } if( strParts.length > 0) { if( strParts[0].equalsIgnoreCase("No ack") ) { if( debugLevel >= 2 ) { System.out.println("checkPTWDAnswer 1258 strParts[0]=["+strParts[0]+"]"); } return true; } } return false; } public TwoWaySerialComm safelyOpenCom( Container cont, TwoWaySerialComm Com ) { return( safelyOpenCom( cont, Com, true)); } public TwoWaySerialComm safelyOpenCom( Container cont, TwoWaySerialComm Com, Boolean showMbox ) { if( debugLevel > 0 ) { System.out.println("safelyOpenCom: Com "+ Com==null?"=":"!" +"= null"); } if( Com != null ) { // valid Com -> check status connected try { if( Com.isconnected() ) { // already connected -> all OK return Com; } } catch (Exception | Error ex) { // problem COM is invalid } // problem COM is not connected Com = safelyCloseCom( cont, Com, showMbox ); } if( Com == null ) { try { Com = new TwoWaySerialComm(); Com.connect(this); if( ! Com.isconnected() ) { if( showMbox ) { mbDeviceConnectProblem( cont ); } Com = safelyCloseCom( cont, Com, showMbox ); return Com; } } catch (Exception | Error ex) { if( showMbox ) { mbDeviceConnectProblem( cont ); } Com = null; } } return Com; } public TwoWaySerialComm safelyCloseCom( Container cont, TwoWaySerialComm Com ) { return( safelyCloseCom( cont, Com, true)); } public TwoWaySerialComm safelyCloseCom( Container cont, TwoWaySerialComm Com, Boolean showMbox ) { if( debugLevel > 0 ) { System.out.println("safelyCloseCom: Com "+ Com==null?"=":"!" +"= null" ); System.out.println("cont name="+cont.getName() +" class="+cont.getClass() ); } if( Com != null ) { try { if( Com.isconnected() ) { Com.close(); } } catch (Exception | Error ex) { if( showMbox ) { mbDeviceDisconnectProblem( cont ); } } Com = null; } return Com; } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { buttonGroup1 = new javax.swing.ButtonGroup(); KlarTextMainPanel = new javax.swing.JPanel(); jButtonEnd = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); jDecoderChooser = new javax.swing.JList(); jLabelProgName = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); jButtonStart = new javax.swing.JButton(); jButtonOptions = new javax.swing.JButton(); jLabelProgVersion = new javax.swing.JLabel(); jButtonInfo = new javax.swing.JButton(); jZentraleTitle = new javax.swing.JTextField(); jZentrale = new javax.swing.JTextField(); jSchnittstelleTitle = new javax.swing.JTextField(); jSchnittstelle = new javax.swing.JTextField(); jBaudrateTitle = new javax.swing.JTextField(); jBaudRate = new javax.swing.JTextField(); jLabelBuild = new javax.swing.JLabel(); jLabelOS = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("my/KlarText/Bundle"); // NOI18N setTitle(bundle.getString("KlarTextUI.title")); // NOI18N addWindowListener(new java.awt.event.WindowAdapter() { public void windowOpened(java.awt.event.WindowEvent evt) { formWindowOpened(evt); } public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); KlarTextMainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder(null, bundle.getString("KlarTextUI.KlarTextMainPanel.border.title"), javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N KlarTextMainPanel.setName("CV-Navi"); // NOI18N jButtonEnd.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButtonEnd.setText(bundle.getString("KlarTextUI.jButtonEnd.text")); // NOI18N jButtonEnd.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonEndActionPerformed(evt); } }); jDecoderChooser.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jDecoderChooser.setModel(new javax.swing.AbstractListModel() { String[] strings = { "Lok-Decoder", ". LD-G-30", ". LD-G-31", ". LD-W-32", ". LD-G-32", ". LD-W-33", ". LD-G-33", ". LD-G-34", ". LD-G-31Plus", ". LD-G-33Plus", ". LD-G-34Plus", ". LD-G-36Plus", "____________", "Funktions-Decoder", ". FD-R basic", ". FD-R extended", ". FD-M", ". FD-XL", "____________", "Zubehör-Decoder", ". WD-34", ". SD-34", "____________", "Sonstiges", ". MasterControl", ". B-4", ". WIB-30er" }; public int getSize() { return strings.length; } public Object getElementAt(int i) { return strings[i]; } }); jDecoderChooser.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); jDecoderChooser.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseReleased(java.awt.event.MouseEvent evt) { jDecoderChooserMouseReleased(evt); } public void mouseClicked(java.awt.event.MouseEvent evt) { jDecoderChooserMouseClicked(evt); } }); jDecoderChooser.addKeyListener(new java.awt.event.KeyAdapter() { public void keyReleased(java.awt.event.KeyEvent evt) { jDecoderChooserKeyReleased(evt); } }); jScrollPane1.setViewportView(jDecoderChooser); jLabelProgName.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabelProgName.setText(bundle.getString("KlarTextUI.jLabelProgName.text")); // NOI18N jLabel2.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 0, 0)); jLabel2.setText(bundle.getString("KlarTextUI.jLabel2.text")); // NOI18N jLabel3.setFont(new java.awt.Font("Tahoma", 1, 48)); // NOI18N jLabel3.setText(bundle.getString("KlarTextUI.jLabel3.text")); // NOI18N jLabel4.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel4.setText(bundle.getString("KlarTextUI.jLabel4.text")); // NOI18N jLabel4.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT); jLabel4.setIconTextGap(0); jLabel5.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel5.setForeground(new java.awt.Color(255, 0, 0)); jLabel5.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel5.setText(bundle.getString("KlarTextUI.jLabel5.text")); // NOI18N jLabel5.setIconTextGap(0); jLabel6.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel6.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel6.setText(bundle.getString("KlarTextUI.jLabel6.text")); // NOI18N jLabel6.setIconTextGap(0); jButtonStart.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N jButtonStart.setText(bundle.getString("KlarTextUI.jButtonStart.text")); // NOI18N jButtonStart.setToolTipText(bundle.getString("KlarTextUI.jButtonStart.toolTipText")); // NOI18N jButtonStart.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonStartActionPerformed(evt); } }); jButtonOptions.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButtonOptions.setText(bundle.getString("KlarTextUI.jButtonOptions.text")); // NOI18N jButtonOptions.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonOptionsActionPerformed(evt); } }); jLabelProgVersion.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabelProgVersion.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelProgVersion.setText(bundle.getString("KlarTextUI.jLabelProgVersion.text")); // NOI18N jLabelProgVersion.setIconTextGap(0); jButtonInfo.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jButtonInfo.setText(bundle.getString("KlarTextUI.jButtonInfo.text")); // NOI18N jButtonInfo.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButtonInfoActionPerformed(evt); } }); jZentraleTitle.setEditable(false); jZentraleTitle.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N jZentraleTitle.setHorizontalAlignment(javax.swing.JTextField.LEFT); jZentraleTitle.setText(bundle.getString("KlarTextUI.jZentraleTitle.text")); // NOI18N jZentraleTitle.setToolTipText(bundle.getString("KlarTextUI.jZentraleTitle.toolTipText")); // NOI18N jZentraleTitle.setBorder(null); jZentrale.setEditable(false); jZentrale.setHorizontalAlignment(javax.swing.JTextField.CENTER); jZentrale.setText(bundle.getString("KlarTextUI.jZentrale.text")); // NOI18N jSchnittstelleTitle.setEditable(false); jSchnittstelleTitle.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N jSchnittstelleTitle.setHorizontalAlignment(javax.swing.JTextField.LEFT); jSchnittstelleTitle.setText(bundle.getString("KlarTextUI.jSchnittstelleTitle.text")); // NOI18N jSchnittstelleTitle.setToolTipText(bundle.getString("KlarTextUI.jSchnittstelleTitle.toolTipText")); // NOI18N jSchnittstelleTitle.setBorder(null); jSchnittstelle.setEditable(false); jSchnittstelle.setHorizontalAlignment(javax.swing.JTextField.CENTER); jSchnittstelle.setText(bundle.getString("KlarTextUI.jSchnittstelle.text")); // NOI18N jBaudrateTitle.setEditable(false); jBaudrateTitle.setFont(new java.awt.Font("Dialog", 1, 12)); // NOI18N jBaudrateTitle.setHorizontalAlignment(javax.swing.JTextField.LEFT); jBaudrateTitle.setText(bundle.getString("KlarTextUI.jBaudrateTitle.text")); // NOI18N jBaudrateTitle.setToolTipText(bundle.getString("KlarTextUI.jBaudrateTitle.toolTipText")); // NOI18N jBaudrateTitle.setBorder(null); jBaudRate.setEditable(false); jBaudRate.setHorizontalAlignment(javax.swing.JTextField.CENTER); jBaudRate.setText(bundle.getString("KlarTextUI.jBaudRate.text")); // NOI18N jBaudRate.setToolTipText(bundle.getString("KlarTextUI.jBaudRate.toolTipText")); // NOI18N jLabelBuild.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelBuild.setText("build"); jLabelBuild.setIconTextGap(0); jLabelOS.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabelOS.setText("os info"); jLabelOS.setIconTextGap(0); javax.swing.GroupLayout KlarTextMainPanelLayout = new javax.swing.GroupLayout(KlarTextMainPanel); KlarTextMainPanel.setLayout(KlarTextMainPanelLayout); KlarTextMainPanelLayout.setHorizontalGroup( KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addComponent(jLabel4) .addGap(0, 0, 0) .addComponent(jLabel5) .addGap(0, 0, 0) .addComponent(jLabel6) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButtonInfo, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jButtonEnd, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE) .addGap(18, 18, 18) .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addComponent(jLabelProgName) .addGap(0, 0, 0) .addComponent(jLabel2) .addGap(0, 0, 0) .addComponent(jLabel3)) .addComponent(jButtonStart, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButtonOptions, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jBaudrateTitle, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jBaudRate, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSchnittstelle, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jSchnittstelleTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 224, Short.MAX_VALUE) .addComponent(jZentrale, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jZentraleTitle, javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addGap(41, 41, 41) .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabelBuild, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelProgVersion, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabelOS, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))))) ); KlarTextMainPanelLayout.setVerticalGroup( KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, KlarTextMainPanelLayout.createSequentialGroup() .addContainerGap() .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(KlarTextMainPanelLayout.createSequentialGroup() .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabelProgName) .addComponent(jLabel3) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jLabelProgVersion) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelOS, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabelBuild, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 180, Short.MAX_VALUE) .addComponent(jButtonStart, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(46, 46, 46) .addComponent(jButtonOptions) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jZentraleTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jZentrale, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jSchnittstelleTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jSchnittstelle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(8, 8, 8) .addComponent(jBaudrateTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jBaudRate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1)) .addGap(18, 18, 18) .addGroup(KlarTextMainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER) .addComponent(jLabel4) .addComponent(jLabel5) .addComponent(jLabel6) .addComponent(jButtonInfo) .addComponent(jButtonEnd)) .addContainerGap()) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(KlarTextMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addComponent(KlarTextMainPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addContainerGap()) ); KlarTextMainPanel.getAccessibleContext().setAccessibleName(bundle.getString("KlarTextUI.KlarTextMainPanel.AccessibleContext.accessibleName")); // NOI18N pack(); }// </editor-fold>//GEN-END:initComponents private void jButtonEndActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEndActionPerformed stopIOAction(); mainWindowLocation = getLocationOnScreen(); System.out.println("jButtonEndActionPerformed mainWindowLocation="+mainWindowLocation); Properties prop = new Properties(); try { prop.loadFromXML(new FileInputStream(gsConfigFilename)); } catch (FileNotFoundException ex) { // Die XML-Config-Datei wird bei Bedarf beim Start des Programms in main() angelegt // deshalb hier keine weitere Behandlung Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } try { if ( -1 != jDecoderChooser.getSelectedIndex() ) { gsDecoderIndex = jDecoderChooser.getSelectedIndex(); } prop.setProperty("DecoderIndex", Integer.toString(gsDecoderIndex)); if( bSpracheDE ) { prop.setProperty("Language", "german") ; } else { prop.setProperty("Language", "english") ; } prop.setProperty("SaveOpenDirectory", gsSaveOpenDirectory); prop.setProperty("SaveOpenFilename", gsSaveOpenFilename); prop.setProperty("SaveOpenKennDirectory", gsSaveOpenKennDirectory); prop.setProperty("SaveOpenKennFilename", gsSaveOpenKennFilename); prop.setProperty("SaveOpenMcDirectory", gsSaveOpenMcDirectory); prop.setProperty("SaveOpenMcFilename", gsSaveOpenMcFilename); prop.setProperty("SaveOpenM3Directory", gsSaveOpenM3Directory); prop.setProperty("SaveOpenM3Filename", gsSaveOpenM3Filename); prop.setProperty("OpenFirmwareDirectory", gsOpenFirmwareDirectory); prop.setProperty("OpenFirmwareFilename", gsOpenFirmwareFilename); prop.setProperty("WindowLocationX", ""+mainWindowLocation.x); prop.setProperty("WindowLocationY", ""+mainWindowLocation.y); if( ! rs232_mode_was_forced ) { // only store if it was not forced on command line if( rs232_or_rb_usb_2 ) { prop.setProperty("DeviceForFwUpdate", "usb2"); } else { prop.setProperty("DeviceForFwUpdate", "usb1"); } } prop.storeToXML(new FileOutputStream(gsConfigFilename), gsConfigComment); } catch (IOException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } System.exit(0); }//GEN-LAST:event_jButtonEndActionPerformed public void fillMenuSelection() { int prevIdx = this.getDecoderChooser(); if( debugLevel > 0 ) { System.out.println("fillMenuSelection prevIdx="+prevIdx); } int coSize = decoderList.values().length; final String[] myStrings = new String[coSize]; for(decoderList co : decoderList.values()) { // System.out.printf("decoderList[%2d] [%2d] (%s) Const %10s Text %-35s %s\n",co.ordinal(), co.getIdx(), co.isSelectable()?"X":" ", co, co.getMenutextGer(), co.getMenutextEng()); myStrings[co.getIdx()] = bSpracheDE?co.getMenutextGer():co.getMenutextEng(); } if( bSpracheDE ) { jButtonOptions.setText("Optionen"); jButtonEnd.setText("Beenden"); jZentraleTitle.setText("Zentrale:"); jSchnittstelleTitle.setText("Schnittstelle:"); jBaudrateTitle.setText("Baudrate (seriell):"); } else { jButtonOptions.setText("Options"); jButtonEnd.setText("End"); jZentraleTitle.setText("control unit:"); jSchnittstelleTitle.setText("interface:"); jBaudrateTitle.setText("baud rate (serial):"); } if( ( fwVersion != null ) && ( fwVersion.length() > 0 ) ) { jZentrale.setText(gsZentrale+" ( "+fwVersion+ " )"); } else { jZentrale.setText(gsZentrale); } jSchnittstelle.setText(gsSchnittstelle); jBaudRate.setText(Integer.toString(gsBaudRate)); // TimerSettings 1. defaults MCtimer1 = 1; MCtimer2 = 1; timer1 = 2000; timer2 = 500; timer3 = -1; // timer3 is optional and may stay < 0 switch( lcZentrale ) { case c.cuIntellibox1: timerRetries = 20; break; case c.cuMasterControl: timerRetries = 9; break; case c.cuOpenDCC: timerRetries = 9; break; default: timerRetries = 20; } // if overridden by command-line, use user's values if( userTimer1 > 0 ){ MCtimer1 = userTimer1; timer1 = userTimer1; } if( userTimer2 > 0 ){ MCtimer2 = userTimer2; timer2 = userTimer2; } if( userTimer3 > 0 ) timer3 = userTimer3; if( userTimerRetries >= 0 ) timerRetries = userTimerRetries; if( debugLevel > 0 ) { System.out.println("timerSettings MCtimer1="+MCtimer1+" MCtimer2="+MCtimer2+" timer1="+timer1+" timer2="+timer2+" timer3="+timer3+" timerRetries="+timerRetries); } jDecoderChooser.setModel(new javax.swing.AbstractListModel() { public int getSize() { return myStrings.length; } public Object getElementAt(int i) { return myStrings[i]; } }); if( debugLevel > 0 ) { System.out.println("fillMenuSelection prevIdx("+prevIdx+")"); } this.setDecoderChooser(prevIdx); } private void jButtonStartActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonStartActionPerformed currSelection = jDecoderChooser.getSelectedIndex(); if( debugLevel > 0 ) { System.out.println("jButtonStartActionPerformed currSelection="+currSelection ); } if( this.frameInstanceDEVICE != null ) { this.frameInstanceDEVICE.toFront(); this.frameInstanceDEVICE.repaint(); if( debugLevel > 0 ) { System.out.println("jButtonStartActionPerformed: there is already an instance running for Decoder="+Decoder ); } return; } Decoder = currSelection; switch( Decoder ) { case c.LD_G30: // LD-G-30 case c.LD_W32: // LD-W-32 case c.LD_G32: // LD-G-32 case c.LD_W32_2: // LD-W-32.2 case c.LD_G32_2: // LD-G-32.2 LDG30 lDG30 = new LDG30(this); break; case c.LD_G31: // LD-G-31 LDG31 lDG31 = new LDG31(this); break; case c.LD_W33: // LD-W-33 case c.LD_G33: // LD-G-33 case c.LD_G34: // LD-G-34 case c.FD_XL: // FD-XL LDG33 lDG33 = new LDG33(this); break; case c.LD_G31Plus: // LD-G-31Plus case c.LD_G33Plus: // LD-G-33Plus case c.LD_G34Plus: // LD-G-33Plus case c.LD_G36Plus: // LD-G-33Plus LDG30erPlus lDG33Plus = new LDG30erPlus(this); break; case c.FD_R: // FD-R case c.FD_R2: // FD-R-basic2 FDR fDR = new FDR(this); break; case c.FD_R_ex: // FD-R extended FD_R_Extended fDRex = new FD_R_Extended(this); break; case c.FD_M: // FD-M FD_M fD_M = new FD_M(this); break; case c.FD_LED: //FD-LED FD_LED fD_LED = new FD_LED(this); break; /* case c.SD_22: // SD-22 break; */ case c.WD_34: // WD-34 case c.SD_34: // SD-34 case c.WD_34_2: // WD-34 case c.SD_34_2: // SD-34 WD34 wD34 = new WD34(this); break; case c.MultiDecoder: // MasterControl/RedBox MultiDec MD = new MultiDec(this); break; case c.MC: // MasterControl/RedBox MC mC = new MC(this); break; case c.B_4: // B-4 B_4 b_4 = new B_4(this); break; case c.BiDi_B: // BiDi-Booster BiDi_B BiDi_B = new BiDi_B(this); break; case c.WIB_30: // WIB-30er WIB_30 wib_30 = new WIB_30(this); break; default: mbDeviceNotSupported( this, 5 ); } }//GEN-LAST:event_jButtonStartActionPerformed private void jButtonOptionsActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonOptionsActionPerformed Options options = new Options(this); }//GEN-LAST:event_jButtonOptionsActionPerformed enum KTUImenuEvt { VK_UP, VK_DOWN } private void KTUImenuEvalKey(KTUImenuEvt key) { Boolean checkAgain = true; decoderList[] DLval = decoderList.values(); while( checkAgain ) { checkAgain = false; int n = jDecoderChooser.getSelectedIndex(); if( DLval[n].isSelectable() ) { // entry is selectable -> OK return; } if( key == KTUImenuEvt.VK_DOWN) { if( n < ( DLval.length - 1 )) { jDecoderChooser.setSelectedIndex(n+1); checkAgain = true; } if( n == ( DLval.length - 1 )) { // UUps, das Ende der Liste ist nicht selectable ! // wir muessen aufwaerts bis wieder ein selectable kommt while( --n > 0 ) { if( DLval[n].isSelectable() ) { jDecoderChooser.setSelectedIndex(n); return; } } } } if( key == KTUImenuEvt.VK_UP) { if( n > 0 ) { jDecoderChooser.setSelectedIndex(n-1); checkAgain = true; } if( n == 0 ) { // 1st entry is not selectable // change to first selectable choice while( ++n < ( DLval.length - 1 ) ) { if( DLval[n].isSelectable() ) { jDecoderChooser.setSelectedIndex(n); return; } } } } } } private void jDecoderChooserMouseReleased(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDecoderChooserMouseReleased // mouse event is treated like VK_DOWN KTUImenuEvalKey(KTUImenuEvt.VK_DOWN); }//GEN-LAST:event_jDecoderChooserMouseReleased private void jDecoderChooserKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jDecoderChooserKeyReleased if(evt.getKeyCode()== KeyEvent.VK_DOWN) { KTUImenuEvalKey(KTUImenuEvt.VK_DOWN); } if(evt.getKeyCode()== KeyEvent.VK_UP) { KTUImenuEvalKey(KTUImenuEvt.VK_UP); } }//GEN-LAST:event_jDecoderChooserKeyReleased private void jDecoderChooserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jDecoderChooserMouseClicked if(evt.getClickCount() == 2) { ActionEvent evnt = null; this.jButtonStartActionPerformed(evnt); } }//GEN-LAST:event_jDecoderChooserMouseClicked private void jButtonInfoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInfoActionPerformed jInfo jI = new jInfo( this ); }//GEN-LAST:event_jButtonInfoActionPerformed public void setFocus() { jButtonStart.grabFocus(); this.toFront(); this.repaint(); } private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened Properties prop = new Properties(); try { prop.loadFromXML(new FileInputStream(gsConfigFilename)); } catch (FileNotFoundException ex) { // Logger.getLogger(KlarTextUI.class.getName()).log(Level.INFO, null, ex); try { File f = new File(gsConfigDirectory); f.mkdir(); prop.storeToXML(new FileOutputStream(gsConfigFilename), gsConfigComment); } catch (IOException ex1) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex1); } } catch (IOException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } // Werte auslesen bzw. mit Defaults initialisieren setZentrale(prop.getProperty("Zentrale", "MasterControl")); gsSchnittstelle = prop.getProperty("Schnittstelle", "COM1"); gsBaudRate = Integer.parseInt( prop.getProperty("BaudRate","9600")); gsDecoderIndex = Integer.parseInt( prop.getProperty("DecoderIndex", Integer.toString(c.MC))); if(bundle.getString("Sprache").equals("Deutsch")) { bSpracheDE = true; } else { bSpracheDE = false; } gsLookAndFeel = prop.getProperty("LookAndFeel","Metal"); gsSaveOpenDirectory = prop.getProperty("SaveOpenDirectory",System.getProperty("user.home")); gsSaveOpenFilename = prop.getProperty("SaveOpenFilename"," "); gsSaveOpenKennDirectory = prop.getProperty("SaveOpenKennDirectory",System.getProperty("user.home")); gsSaveOpenKennFilename = prop.getProperty("SaveOpenKennFilename"," "); gsSaveOpenMcDirectory = prop.getProperty("SaveOpenMcDirectory",System.getProperty("user.home")); gsSaveOpenMcFilename = prop.getProperty("SaveOpenMcFilename"," "); gsSaveOpenM3Directory = prop.getProperty("SaveOpenM3Directory",System.getProperty("user.home")); gsSaveOpenM3Filename = prop.getProperty("SaveOpenM3Filename"," "); gsOpenFirmwareDirectory = prop.getProperty("OpenFirmwareDirectory",System.getProperty("user.home")); gsOpenFirmwareFilename = prop.getProperty("OpenFirmwareFilename"," "); if( ! rs232_mode_was_forced ) { // nur nach Änderung durch Benutzer zurückschreiben (Umstellung per Aufrufparameter ignorieren) rs232_or_rb_usb_2 = prop.getProperty("DeviceForFwUpdate","usb1").contentEquals("usb2"); } int x = Integer.parseInt( prop.getProperty("WindowLocationX", "-1" ) ); int y = Integer.parseInt( prop.getProperty("WindowLocationY", "-1" ) ); mainWindowLocation.setLocation(x, y); if( (mainWindowLocation.x >= 0 ) && (mainWindowLocation.y >= 0 ) ) { setLocation(mainWindowLocation); } fillMenuSelection(); jDecoderChooser.setSelectedIndex(gsDecoderIndex); jButtonStart.setSelected(true); jButtonStart.grabFocus(); SODlocalSize = new Dimension(); String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); String dataModel = System.getProperty("sun.arch.data.model"); String osInfo = "( "+osName+"["+osArch+"] , java "+dataModel+"bit )"; jLabelOS.setText(osInfo); String gsBuild ="beta 20180118b"; // use keyword "beta" or "release" System.out.println("Build: "+gsBuild); if( debugLevel > 0 || gsBuild.contains("beta") ) { jLabelBuild.setText(gsBuild); } else { jLabelBuild.setText(""); } // store pointer to instance in a final variable -> useable inside ActionListener final KlarTextUI outerThis = this; final ActionListener actionListener = new ActionListener() { public void actionPerformed(ActionEvent e) { if( debugLevel > 0 ) { System.out.println( "actionPerformed" ); } byte[] bArray = new byte[0xFFFF]; if( bReadStatusBin ) { if( debugLevel > 0 ) { System.out.println( "actionPerformed bReadStatusBin " ); } bReadStatusBin = false; stopIOAction(); int tmpBytesRead = ExternalCom.read(bArray); // Gbts was Neues ? ExternalCom = null; if( debugLevel > 0 ) { System.out.println( "actionPerformed bReadStatusBin tmpBytesRead="+tmpBytesRead ); } if( tmpBytesRead > 0 ) { dumpbArrayBIN(bArray, tmpBytesRead); if( (bArray[0]&0x08)==0x08) { trackStatus = c.cuPowerOn; } else { trackStatus = c.cuPowerOff; } } else { trackStatus = -1 ; } distributeTrackStatus(); } if( bVerifyZentraleInProgress ) { bVerifyZentraleInProgress = false; stopIOAction(); int nBytes = KTUICom.read(bArray); KTUICom = safelyCloseCom( outerThis, KTUICom ); if( debugDummyData == 1 ) { // DUMMY - Werte zum DEBUGGEN : Tams MC bArray[0] = 0x04; bArray[1] = 0x01; bArray[2] = 0x04; bArray[3] = 0x07; bArray[4] = 'b'; bArray[5] = 0x04; bArray[6] = 0x00; bArray[7] = 0x13; bArray[8] = 0x07; bArray[9] = 0x56; bArray[10] = 0x00; nBytes = 11; } if( debugDummyData == 2 ) { // DUMMY - Werte zum DEBUGGEN : OpenDCC neu bArray[0] = 0x02; bArray[1] = 0x17; bArray[2] = 0x08; bArray[3] = 0x01; bArray[4] = 0x2a; bArray[5] = 0x00; nBytes = 6; } if( debugDummyData == 3 ) { // DUMMY - Werte zum DEBUGGEN : IB /* For example, the IB replies with: 02h, <SPU version low>, <SPU version high>, 02h, <KPU version low>, <KPU version high>, 01h, <PPU version>, 01h, <LIPU version>, 01h, <DNG version>, 05h, <IB serial number: 5 bytes (digits 98, 76, 54, 32, 10)>, 00h A single byte version # is to be interpreted as: H.L For example: 10h -> version 1.0 A two byte version # (low/high) is to be interpreted as: H.HLL For example: 23h, 10h -> version 1.023 (the version numbers and the serial number are sent in BCD notation - Binary Coded Decimal). The serial number is to be interpreted as: '9876543210' - i.e. digit '9' is the most significant digit, etc... SPU = System Processing Unit (the IB 'heart') KPU = Keypad Processing Unit (user interface) PPU = Peripheral Processing Unit (digital signal generator) LIPU = Lokmaus/I2C Processing Unit DNG = Dispositivo di Nostra Gestione (sorry this is italian language!) */ bArray[0] = 0x02; bArray[1] = (byte) 0x92; bArray[2] = 0x20; bArray[3] = 0x01; bArray[4] = 0x02; bArray[5] = 0x01; bArray[6] = 0x03; bArray[7] = 0x01; bArray[8] = 0x04; bArray[9] = 0x01; bArray[10] = 0x05; bArray[11] = 0x01; bArray[12] = 0x06; bArray[13] = 0x00; nBytes = 14; } if( debugDummyData == 4 ) { // DUMMY - Werte zum DEBUGGEN : IB bArray[0] = 0x02; bArray[1] = 0x23; bArray[2] = 0x10; bArray[3] = 0x01; bArray[4] = 0x02; bArray[5] = 0x01; bArray[6] = 0x03; bArray[7] = 0x01; bArray[8] = 0x04; bArray[9] = 0x01; bArray[10] = 0x05; bArray[11] = 0x01; bArray[12] = 0x06; bArray[13] = 0x00; nBytes = 14; } if(nBytes < 1) { mbTimeout( outerThis, c.mbRDverify ); } else { if( debugLevel > 0 ) { System.out.println("Xver: finished bArraySize="+nBytes); } byte[] mYbArray = new byte[nBytes]; System.arraycopy(bArray, 0, mYbArray, 0, nBytes); Boolean ok = verifyXVer( mYbArray ); bZentraleVerified = true; fillMenuSelection(); if( ok && bGotoUpdate ) { if( debugLevel > 0 ) { System.out.println("bVerifyZentraleInProgress jDecoderChooser.setSelectedIndex="+c.MC ); } jDecoderChooser.setSelectedIndex(c.MC); jButtonStartActionPerformed( null ); } } return; } } }; timer = new javax.swing.Timer(5000, actionListener); timer.setRepeats(false); actionListener.actionPerformed(null); verifyZentrale(false); }//GEN-LAST:event_formWindowOpened private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing // leave through OS closing the app -> simulate exit-button event jButtonEndActionPerformed( null ); }//GEN-LAST:event_formWindowClosing private Boolean verifyXVer( byte[] bIn ) { int lenIn = bIn.length; int numAnswers = 0; int idx = 0; String sSwVersion = null; long lSwVersion = 0; char b = ' '; char bNum = ' '; /* * Version Info: * IB 6 answers first is 2 Bytes (BCD) * OpenDCC 1 answer 1 Bytes (BYTE) (until V0.14, only version) * OpenDCC 1 answer 2 Bytes (BYTE) (since V0.15, version+serno combined) * OpenDCC 2 answers first is 2 Bytes (BYTE) (since V0.23.8release) * Tams 2 answers first is 3 Bytes (BCD) or 4 Bytes (3*BCD + ASCII) * MoPi 2 answer 3 Bytes (BYTE) (stores version: major, minor, build) */ /* First in byte tells how much bytes are in next answer. */ if( debugLevel > 0 ) { System.out.println("bIn("+lenIn+")=0x"+printHexBinary(bIn)); } if( lenIn <= 0 ) { if( debugLevel > 0 ) { System.out.println("verifyXVer bIn is empty lenIn="+lenIn); } return false; } int lenAntwort = (int) bIn[idx]; idx++; if( debugLevel > 0 ) { System.out.println("Antwort["+numAnswers+"] ist "+lenAntwort+" Bytes lang"); } if( lenAntwort > lenIn ) { System.out.println("May be a TamsMC waiting for a software update..."); // meist zwischen 8 und 12 Bytes if( lenIn >= 5 ) { // 0x4C235423542354235423 T#L#T#T#T# // 10 MasterControl // 0x4C235423542354235423 L#T#T#T#T# T#L#T#T#T#T# // MC als HC T#T#T#T#T#T# // 0x54234323542354235423 C#T#T#T#T# T#C#T#T#T# // 10 HandControl / PhoneControl // 0x543F4C3F543F543F543F L?T?T?T?T? // 10 XN-Control / mControl T?C?T?T? C?T?T?T? T?L?T?T?T?T? T?L?T?T?T?T? // 0x23 = 35 = '#' Block wiederholen (256 Bytes) // 0x3F = 63 = '?' Block wiederholen (128 Bytes) // 0x43 = 67 = 'C' CRC Error // 0x4C = 76 = 'L' Length Error // 0x54 = 84 = 'T' Time out Error String s = new String( bIn ); String cs = s.substring(1, 5); if( debugLevel > 0 ) { System.out.println("bIN as String="+s+" len="+s.length()+" cs="+cs ); } // die ersten 4 Zeichen vergleichen switch( cs ) { case "L#T#" : case "T#L#" : case "C#T#" : case "T#C#" : case "T#T#" : case "#L#T" : case "#T#L" : case "#C#T" : case "#T#C" : case "#T#T" : System.out.println("Yes a TamsMC with a 256 byte block device (MasterControl, HandControl, PhoneControl, ... ) waiting for a software update"); break; case "L?T?" : case "T?L?" : case "C?T?" : case "T?C?" : case "T?T?" : case "?L?T" : case "?T?L" : case "?C?T" : case "?T?C" : case "?T?T" : System.out.println("Yes a TamsMC with a 128 byte block device (XNControl, mControl, ... ) waiting for a software update"); break; default: System.out.println("A TamsMC with an unknown device waiting for a software update"); // TODO Dialog ausgliedern und DE/EN mbGeneric(this, "A TamsMC with an unknown device waiting for a software update", "Please report devicename and the following line to Tams", s, 0, true); } bGotoUpdate = (getZentrale() == c.cuMasterControl); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuMasterControl ); if( debugLevel > 0 ) { System.out.println("bVerifyXVer bGotoUpdate="+bGotoUpdate ); } return bGotoUpdate; } return false; } if( lenAntwort < 0 ) { System.out.println("Antwort["+numAnswers+"] : Länge ("+lenAntwort+") ist negativ -> Abbruch bVerifyXVer"); return false; } numAnswers++; byte[] bVersion = new byte[lenAntwort]; int lenVersion = lenAntwort; System.arraycopy(bIn, 1, bVersion, 0, lenAntwort); idx += lenAntwort; while( idx < lenIn ) { lenAntwort = (int) bIn[idx]; if( debugLevel > 0 ) { System.out.println("2880 Antwort["+numAnswers+"] ist "+lenAntwort+" Bytes lang"); } idx++; if( idx + lenAntwort <= lenIn ) { if( lenAntwort > 0 ) { numAnswers++; } else { if( debugLevel > 0 ) { System.out.println("2888 ENDE Xver : idx["+idx+"] + lenAntwort["+lenAntwort+"] <= lenIn["+lenIn+"]"); } } } else { // Ooops if( debugLevel > 0 ) { System.out.println("2894 Oooops : idx["+idx+"] + lenAntwort["+lenAntwort+"] <= lenIn["+lenIn+"]"); } } idx += lenAntwort; } if( debugLevel > 0 ) { System.out.println("numAnswers="+numAnswers); } switch( lenVersion ) { case 1: fwVersion = "0."+(bVersion[0] & 0xFF)+ ".0"; sSwVersion = "OpenDCC Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbGeneric( this, "Information", "Detected "+sSwVersion, "(Xfuncs="+bUseXfuncs+")", 5, false ); break; case 2: switch( numAnswers ) { case 1: // OpenDCC V0.15 until V0.23.8beta, (2 bytes version+serno) fwVersion = "0."+(bVersion[0] & 0xFF)+".0"; sSwVersion = "OpenDCC Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuOpenDCC ); break; case 2: // OpenDCC since V0.23.8 (2 bytes version + 1 byte serno) lSwVersion = (long) ((bVersion[0] & 0xFF) << 8 ) + (long) (bVersion[1] & 0xFF); if( lSwVersion >= 0x1708 ) { bUseXfuncs = true; } fwVersion = "0."+ (bVersion[0] & 0xFF) +"."+ (bVersion[1] & 0xFF); sSwVersion = "OpenDCC Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuOpenDCC ); break; default: // IB should have 6 answers lSwVersion = (long) ((bVersion[1] & 0xFF) << 8 ) + (long) (bVersion[0] & 0xFF); if( lSwVersion >= 0x2000 ) { bUseXfuncs = true; } fwVersion = String.format("%01x.%01x%02x", (bVersion[1]&0xF0)>>4, bVersion[1]&0x0F, bVersion[0]&0xFF); sSwVersion = "Intellibox Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuIntellibox1 ); break; } break; case 5: // Tams beta prerelease # bNum = (char) ( bVersion[4] & 0xFF ); case 4: // Tams beta release b = (char) ( bVersion[3] & 0xFF ); lSwVersion = (long) (bVersion[3] & 0xFF); case 3: // Tams official release lSwVersion += (long)((bVersion[0] & 0xFF) << 24 ); lSwVersion += (long)((bVersion[1] & 0xFF) << 16 ); lSwVersion += (long)((bVersion[2] & 0xFF) << 8 ); bUseXfuncs = ( lSwVersion >= c.MIN_MC_XFUNCS_VERSION ); bUseXm3sid = ( lSwVersion >= c.MIN_MC_XM3SID_VERSION ); bUseSo999 = ( lSwVersion >= c.MIN_MC_SO999_VERSION ); fwVersion = "" + (int) (bVersion[0] & 0xFF) +"." + (int) (bVersion[1] & 0xFF) +"." + (int) (bVersion[2] & 0xFF) + b + bNum; sSwVersion = "MasterControl Version "+fwVersion; System.out.println("--- "+sSwVersion+" ---"); mbVerifyXVer( this, sSwVersion, getZentrale() != c.cuMasterControl ); break; default: System.out.println("Unbekannte Zentrale ausgelesen: Daten["+lenIn+" Bytes] = 0x"+printHexBinary(bIn)); return false; } if( lSwVersion > 0 ) { if( debugLevel > 0 ) { System.out.println("lSwVersion="+lSwVersion+" in HEX="+String.format("0x%16s", Long.toHexString(lSwVersion)).replace(' ', '0') ); System.out.println("bUseXfuncs="+bUseXfuncs+" bUseXm3sid="+bUseXm3sid); } } return true; } /** * * @param force force verify of control unit (use after changed parameters) */ public void verifyZentrale(Boolean force) { if( force ) bZentraleVerified = false; if( bZentraleVerified ) return; if( bVerifyZentraleInProgress ) return; bUseXfuncs = false; bUseXm3sid = false; KTUICom = safelyOpenCom( this, KTUICom ); if( (KTUICom != null) && KTUICom.isconnected() ) { flushReadBuffer( KTUICom ); byte[] wArray = new byte[2]; wArray[0] = (byte) 0x78; // x wArray[1] = (byte) 0xA0; // XVer KTUICom.write(wArray); bVerifyZentraleInProgress = true; timer.setInitialDelay(2000); timer.setDelay(2000); if( userTimer1 > 2000 ) timer.setInitialDelay(userTimer1); if( userTimer2 > 2000 ) timer.setDelay(userTimer2); startIOAction(); } } private void startIOAction() { // jButtonStart.setEnabled(false); jButtonOptions.setEnabled(false); jDecoderChooser.setEnabled(false); // set cursor to WAIT Cursor c = new Cursor(Cursor.WAIT_CURSOR); this.setCursor(c); //start timer timer.start(); } private void stopIOAction() { // stop timer timer.stop(); bVerifyZentraleInProgress = false; // set cursor Cursor c = new Cursor(Cursor.DEFAULT_CURSOR ); setCursor(c); // jButtonStart.setEnabled(true); jButtonOptions.setEnabled(true); jDecoderChooser.setEnabled(true); } public int flushReadBuffer( TwoWaySerialComm Com ) { int numBytes = 0; if( (Com != null) && Com.isconnected() ) { // flushReadBuffer byte[] bArray = new byte[0xFFFF]; numBytes = Com.read(bArray); if( debugLevel > 0 ) { System.out.println("2982 flushReadBuffer : "+numBytes+" Bytes" ); dumpbArray(bArray); } } return numBytes; } public void trackPowerOn( TwoWaySerialComm Com ) { Com.write( (byte) 0x60 ); checkTrackStatus( Com ); } public void trackPowerOff( TwoWaySerialComm Com ) { Com.write( (byte) 0x61 ); checkTrackStatus( Com ); } public void checkTrackStatus( TwoWaySerialComm Com ) { if( Com == null ) { return; } ExternalCom = Com ; flushReadBuffer( ExternalCom ); /* Abfrage mit 1 Byte Antwort ! */ byte[] wArray = new byte[2]; wArray[0] = (byte) 0x78; // x wArray[1] = (byte) 0xA2; // XStatus ExternalCom.write(wArray); bReadStatusBin = true; timer.setInitialDelay(500); timer.setDelay(500); if( userTimer1 > 2000 ) timer.setInitialDelay(userTimer1); if( userTimer2 > 2000 ) timer.setDelay(userTimer2); startIOAction(); } public int getTrackStatus() { if( forceTrackPowerOn ) { return c.cuPowerOn; } return trackStatus; } private void distributeTrackStatus() { if( frameInstanceDEVICE != null ) { String devName = frameInstanceDEVICE.getClass().getSimpleName() ; switch( devName ) { case "B_4": B_4 b4 = (B_4) frameInstanceDEVICE; System.out.println( "calling setStatus( "+trackStatus+" ) for "+devName ); b4.setStatus( getTrackStatus() ); break; case "BiDi_B": BiDi_B bidib = (BiDi_B) frameInstanceDEVICE; System.out.println( "calling setStatus( "+trackStatus+" ) for "+devName ); bidib.setStatus( getTrackStatus() ); break; default: System.out.println( "setStatus( "+trackStatus+" ) for UNKNOWN/UNSUPPORTED DEVICE "+devName ); } } } public void setSwitch( TwoWaySerialComm Com, int address, boolean straight, boolean coilOn ) { byte[] wArray = new byte[4]; wArray[0] = (byte) 0x78; // x wArray[1] = (byte) 0x90; // XTrnt wArray[2] = (byte) (address & 0xFF); // AdrLow wArray[3] = (byte) ( ( (address >> 8) & 0x07) | (straight?0x80:0x00) | (coilOn?0x40:0x00) ); // AdrHigh (3bits) + Bit8 = turnout, Bit7= coilOn Com.write( wArray ); if( debugLevel > 0 ) { System.out.println("Weiche "+address+" gerade="+straight+ " aktiv="+coilOn ); } dumpbArrayBIN(wArray, 4); } private static Boolean verifySelectionList() { // test decoder menu for correct idx in first column // if not some strange things might happen ! int decoderListSize = decoderList.values().length; int decoderListCount = 0; int errorsDetected = 0; for(decoderList co : decoderList.values()) { if( co.getIdx() != decoderListCount ) { System.out.printf("ERROR in decoderListCount %2d decoderList[%2d] [%2d] (%s) Const %10s Text %-35s %s\n", decoderListCount, co.ordinal(), co.getIdx(), co.isSelectable()?"X":" ", co, co.getMenutextGer(), co.getMenutextEng()); errorsDetected++; } decoderListCount++; } if( decoderListCount != decoderListSize ) { System.out.println("ERROR in decoderListCount != decoderListSize "+decoderListCount+" != "+decoderListSize); errorsDetected++; } if( errorsDetected != 0 ) { System.out.println(""+errorsDetected+" ERRORS in decoderList detected" ); return false; }else { System.out.println("decoderList verified successfully"); } return true; } private static void helpCommandLine() { System.out.println("CV-Navi [-d [<num>]] [-c] [-c Xfuncs] [-c Xm3sid ] [-b <num>] [-o]"); System.out.println("\t-d [<num>] \tdebuglevel (without num: increment by 1)" ); System.out.println("\t-c \tforce configured control unit (no check)"); System.out.println("\t-c Xfuncs \tforce enable XFuncs"); System.out.println("\t-c Xm3sid \tforce enable Xm3sid"); System.out.println("\t-b <num> \tuse preconfigured dummy datasets for debugging"); System.out.println("\t-o \tforce offline mode"); System.out.println("\t-p \tforce track power reported as on"); System.out.println("\t-t1 <num> \tread/write CVs: initial timeout [ms] (default: 2000)"); System.out.println("\t-t2 <num> \tread/write CVs: delay timeout [ms] (default: 500)"); System.out.println("\t-t3 <num> \tread/write CVs: extra pause [ms] between CV requests (default: 0)"); System.out.println("\t-tr <num> \tread/write CVs: number of retries with delay timeout (default: 9)"); System.out.println("\t-tfu <num> \ttimer interval during firmware updates (default: 250)"); System.out.println("\t-u \tupdate window always visible"); System.out.println("\t-usb1 \tuse USB-1 in RedBox/MasterControl -> no BaudRate changes on firmware updates (default: on)"); System.out.println("\t-usb2 \tuse USB-2 in RedBox -> BaudRate change to 38400 on firmware-updates (default: off)"); System.out.println("\t-rs232 \tuse RS232 in RedBox/MasterControl -> BaudRate change to 38400 on firmware-updates (default: off)"); System.out.println("\t-no17 \tdo not read CV17"); System.out.println("\t-no18 \tdo not read CV18"); } /** * @param args the command line arguments */ public static void main(final String args[]) { int argc = args.length; String sunModel = System.getProperty("sun.arch.data.model"); String osName = System.getProperty("os.name"); String osArch = System.getProperty("os.arch"); System.out.println("model["+sunModel+"] osName["+osName+"] osArch["+osArch+"]"); System.out.println("argc="+ argc ); int n = 0; try { for ( n = 0 ; n < argc ; n++ ) { switch( args[n].toLowerCase() ) { case "-d": if( n == (argc-1) || args[n+1].startsWith("-") ){ debugLevel++; System.out.println("debugLevel set to "+debugLevel); break; } n++; debugLevel = Integer.parseInt(args[n]); System.out.println("debugLevel set to "+debugLevel); break; case "-c": if( n == (argc-1) || args[n+1].startsWith("-") ){ bZentraleVerified = true; System.out.println("bZentraleVerified set to "+bZentraleVerified); break; } n++; if( args[n].equalsIgnoreCase("Xfuncs")) { bZentraleVerified = true; bUseXfuncs = true; System.out.println("bUseXfuncs set to "+bUseXfuncs); } if( args[n].equalsIgnoreCase("Xm3sid")) { bZentraleVerified = true; bUseXm3sid = true; System.out.println("bUseXm3sid set to "+bUseXm3sid); } break; case "-b": if( n == (argc-1) || args[n+1].startsWith("-") ) { // "-b" ohne Parameter -> Zahl fehlt => ignorieren break; } n++; debugDummyData = Integer.parseInt(args[n]); System.out.println("debugDummyData set to "+debugDummyData); break; case "-o": debugOffline = true; System.out.println("debugOffline set to true"); break; case "-p": forceTrackPowerOn = true; System.out.println("forceTrackPowerOn set to true"); break; case "-t1": if( n == (argc-1) || args[n+1].startsWith("-") ) { // "-t1" ohne Parameter -> Zahl fehlt => ignorieren break; } n++; userTimer1 = Integer.parseInt(args[n]); System.out.println("userTimer1 set to "+userTimer1); break; case "-t2": if( n == (argc-1) || args[n+1].startsWith("-") ) { // ohne Parameter -> Zahl fehlt => ignorieren break; } n++; userTimer2 = Integer.parseInt(args[n]); System.out.println("userTimer2 set to "+userTimer2); break; case "-t3": if( n == (argc-1) || args[n+1].startsWith("-") ) { // ohne Parameter -> Zahl fehlt => ignorieren break; } n++; timer3 = Integer.parseInt(args[n]); System.out.println("userTimer3 set to "+userTimer3); break; case "-tr": if( n == (argc-1) || args[n+1].startsWith("-") ) { // ohne Parameter -> Zahl fehlt => ignorieren break; } n++; userTimerRetries = Integer.parseInt(args[n]); System.out.println("userTimerRetries set to "+userTimerRetries); break; case "-tfu": if( n == (argc-1) || args[n+1].startsWith("-") ) { // ohne Parameter -> Zahl fehlt => ignorieren break; } n++; userTimerFwUp = Integer.parseInt(args[n]); System.out.println("userTimerFwUp set to "+userTimerFwUp); break; case "-u": updateAlwaysVisible = true; System.out.println("updateVisible set to true"); break; case "-usb1": rs232_or_rb_usb_2 = false; System.out.println("force using usb-1 mode"); rs232_mode_was_forced = true; break; case "-usb2": case "-rs232": rs232_or_rb_usb_2 = true; System.out.println("force using usb-2/rs232 mode"); rs232_mode_was_forced = true; break; case "-no17": skipCV17 = true; System.out.println("skipCV17 set to "+skipCV17); break; case "-no18": skipCV18 = true; System.out.println("skipCV18 set to "+skipCV18); break; case "-h": helpCommandLine(); return; default: System.out.println("args["+n+"]=["+args[n]+"] UNHANDLED"); } } } catch (NumberFormatException ex) { System.out.println("inside parse args: numberFormatException ex["+ex+"] n="+n); helpCommandLine(); return; } if( debugLevel > 0 ) System.out.println("debugLevel="+debugLevel); if( verifySelectionList() == false ) return; String s = "javax.swing.plaf.metal.MetalLookAndFeel"; Properties prop = new Properties(); try { prop.loadFromXML(new FileInputStream(gsConfigFilename)); } catch (FileNotFoundException ex) { // Logger.getLogger(KlarTextUI.class.getName()).log(Level.INFO, null, ex); try { File f = new File(gsConfigDirectory); f.mkdir(); prop.storeToXML(new FileOutputStream(gsConfigFilename), gsConfigComment); } catch (IOException ex1) { // MsgBox messageBox = new MsgBox( (Frame) KlarTextUI.getFrames()[0] , true); MsgBox messageBox = new MsgBox( (Frame) null , true, null ); messageBox.jLabel1.setText("FEHLER"); messageBox.jLabel2.setText("Kann Konfigurationsdatei nicht anlegen"); messageBox.jLabel3.setText(gsConfigFilename); messageBox.setVisible(true); Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex1); try { Thread.sleep(5000); } catch (InterruptedException ex2) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex2); } // System.exit(1); } } catch (IOException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } switch (prop.getProperty("LookAndFeel","Metal")) { case "Motif": s = "com.sun.java.swing.plaf.motif.MotifLookAndFeel"; break; case "Nimbus": s = "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel"; break; case "Windows": s = "com.sun.java.swing.plaf.windows.WindowsLookAndFeel"; break; } try { UIManager.setLookAndFeel(s); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { Logger.getLogger(KlarTextUI.class.getName()).log(Level.SEVERE, null, ex); } java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new KlarTextUI().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JPanel KlarTextMainPanel; private javax.swing.ButtonGroup buttonGroup1; private javax.swing.JTextField jBaudRate; private javax.swing.JTextField jBaudrateTitle; private javax.swing.JButton jButtonEnd; private javax.swing.JButton jButtonInfo; private javax.swing.JButton jButtonOptions; private javax.swing.JButton jButtonStart; private javax.swing.JList jDecoderChooser; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabelBuild; private javax.swing.JLabel jLabelOS; private javax.swing.JLabel jLabelProgName; private javax.swing.JLabel jLabelProgVersion; private javax.swing.JTextField jSchnittstelle; private javax.swing.JTextField jSchnittstelleTitle; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField jZentrale; private javax.swing.JTextField jZentraleTitle; // End of variables declaration//GEN-END:variables }
Versionsanpassung an 2.8
src/my/KlarText/KlarTextUI.java
Versionsanpassung an 2.8
<ide><path>rc/my/KlarText/KlarTextUI.java <ide> <ide> public class KlarTextUI extends javax.swing.JFrame { <ide> /** Creates new form KlarTextUI */ <del> public int gsVersionMayor = 2; <del> public int gsVersionMinor = 7; <add> public int gsVersionMayor = 2; // Version 2.8 <add> public int gsVersionMinor = 8; // Version 2.8 <ide> public JFrame frameInstanceDEVICE = null; <ide> public JFrame frameInstanceOPTIONS = null; <ide> public JFrame frameInstanceINFO = null;
Java
mit
82198d98f7fb4f73cfe9530fa1d5791cd668b642
0
iMinusMinus/tao
/** * MIT License * * Copyright (c) 2016 iMinusMinus * * 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. */ package ml.iamwhatiam.tao.ddd; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.StringWriter; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.template.Configuration; /** * ddd code generator: refer to mybatis generator, spring data, hibernate * * @author iMinusMinus * @since 2017-01-16 * @version 0.0.1 * */ public final class CodeGen { private static Logger log = LoggerFactory.getLogger(CodeGen.class); private final List<String> templates = new ArrayList<String>( Arrays.asList("Controller.ftl", "ServiceImpl.ftl", "DAOImpl.ftl", "VO.ftl", "Domain.ftl", "sqlMap.ftl", "TransformationHelper.ftl", "package-info.ftl")); private final List<String> directories = new ArrayList<String>(Arrays.asList("web", "service", "dao", "vo", "domain", "mapper", "support", "")); /** * generate source code or class file, or just runtime */ private GeneratePolicy policy; /** * dbms dialect */ private Dialect dialect; /** * templates */ private String[] tpls; /** * directories template will output to */ private String[] dirs; /** * generate files merged in one package */ private boolean samePackage; /** * package */ private String namespace; /** * SQL dataType mapping to java type */ private Map<String, String> dataTypeMapping; /** * directory source file generated in */ private String target; /** * class name with fixed[tableName] prefix or not */ private boolean withClassNamePrefix; private String[] sqlFiles; private Convension convension; private Framework framework; public CodeGen() { policy = GeneratePolicy.SOURCE; tpls = new String[] {"Controller.ftl", "ServiceImpl.ftl", "DAOImpl.ftl", "VO.ftl", "Domain.ftl", "sqlMap.ftl", "TransformationHelper.ftl", "package-info.ftl"}; dirs = new String[] {"web", "service", "dao", "vo", "domain", "mapper", "support", ""}; target = "src/main/java/ml/iamwhatiam/tao/ddd"; withClassNamePrefix = true; convension = new Convension() { public boolean isUseXml() {return true;} public boolean isUseAnnotation() {return true;} }; framework = new Framework() { public boolean useSpringMvc() {return true;} public boolean useStruts() {return false;} public boolean useSpring() {return true;} public boolean useIbatis() {return true;} public boolean useMyBatis() {return false;} public boolean useHibernate() {return false;} public String list() {return "[SpringMVC, Spring, iBatis]";} }; } public void registeDataTypeMapping() { if(dataTypeMapping != null) TransformationHelper.registeDataTypeMapping(dialect, dataTypeMapping); } public void generate() { SQLParser parser = new SQLParser(dialect); FileInputStream fis; try { fis = new FileInputStream(new File(sqlFiles[0])); } catch (FileNotFoundException e) { throw new RuntimeException(String.format("file [%s] not exist", sqlFiles[0])); } Map<String, Object> root = new HashMap<String, Object>(); Table table = parser.parse(fis); if(namespace == null) namespace = table.getCatalog() == null ? table.getSchema() : table.getCatalog(); if(namespace == null) { log.warn("use radon namespace while namespace not find"); namespace = Long.toHexString(System.currentTimeMillis()); } if(dialect != Dialect.POSTGRES) namespace = namespace.toLowerCase(); namespace = TransformationHelper.snake2camel(namespace); target = target + File.separator + namespace + File.separator; JavaBean bean = TransformationHelper.table2bean(table); root.put("table", table); root.put("bean", bean); root.put("namespace", namespace); root.put("date", new Date()); root.put("config", framework.list()); root.put("samePackage", samePackage); Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setClassForTemplateLoading(CodeGen.class, "/ml/iamwhatiam/tao/ddd"); for(int i = 0; i < tpls.length; i++) { String tpl = tpls[i]; Writer out = null; String name = null; try { switch(policy) { case SOURCE: String old = tpl.substring(0, tpl.indexOf(".") + 1); if("sqlMap.".equals(old)) name = old + ".xml"; else name = old + "java";//XxxPattern or Pattern? File file = null; if(!samePackage) file = new File(target + dirs[i] + File.separator + getFileName(bean.getName(), name)); else file = new File(target + getFileName(bean.getName(), name)); if(!file.getParentFile().exists()) file.getParentFile().mkdirs(); file.createNewFile(); out = new FileWriter(file); break; case CLASS: case RUNTIME: name = tpl.substring(0, tpl.indexOf(".") + 1) + "java"; out = new StringWriter(); break; default: } cfg.getTemplate(tpl).process(root, out); } catch (Exception e) { e.printStackTrace(); } } } public static void main(String[] args) { if(args == null) System.out.println("Try 'java -jar tao -h' or 'java -jar tao --help' for more information"); else if("-h".equals(args[0]) || "--help".equals(args[0])) { System.out.println("-d, --dialect specify sql dialect. MYSQL, POSTGRES, ORACLE, DB2, MS_SQL, SYBASE, INFOMIX expected."); System.out.println("-t, --target which directory generated fiels will be place in. if not specified, use /ml/iamwhatiam/tao/ddd."); System.out.println("-n, --namespace parent package of generated files. use table.schema or table.catalog by default."); System.out.println("-c, --config Annotation: 1, XML: 2, SpringMVC: 4, Spring: 8, iBatis: 16, Struts: 32, MyBatis: 64, Hibernate: 128"); System.out.println("-m, --mapping how sql data type mapping to java type. for example: TINYINT=byte;NUMBER=java.math.BigDecimal."); System.out.println("-s, --simple 1: no VO only DO, 2: no Controller, 4: no Service, 8: VO, DO, Controller, Service, DAO and sqlMap in same package"); } else if(args.length < 5) throw new RuntimeException("-d --dialect must be specified!"); CodeGen cg = new CodeGen(); Map<String, String> mapping = null; String tmp = null; int enabled = 0; int simplify = 0; for(int i = 0, j = args.length; i < j; i += 2) { if("-d".equals(args[i]) || "--dialect".equals(args[i])) { cg.setDialect(Dialect.valueOf(args[i + 1].toUpperCase())); } else if("-t".equals(args[i]) || "--target".equals(args[i])) { cg.setTarget(args[i + 1]); } else if("-m".equals(args[i]) || "--mapping".equals(args[i])) { tmp = args[i + 1]; } else if("-n".equals(args[i]) || "--namespace".equals(args[i])) { cg.setNamespace(args[i + 1]); } else if("-c".equals(args[i]) || "--config".equals(args[i])) { enabled = Integer.parseInt(args[i + 1]); final boolean useAnnotation = (enabled & 1) != 0; final boolean useXml = (enabled & 2) != 0; Convension convension = new Convension() { public boolean isUseXml() {return useXml;} public boolean isUseAnnotation() {return useAnnotation;} }; cg.setConvension(convension); final boolean useSpringMvc = (enabled & 4) != 0; final boolean useSpring = (enabled & 8) != 0; final boolean useIbatis = (enabled & 16) != 0; final boolean useStruts = (enabled & 32) != 0; final boolean useMyBatis = (enabled & 64) != 0; final boolean useHibernate = (enabled & 128) != 0; Framework framework = new Framework() { public boolean useSpringMvc() {return useSpringMvc;} public boolean useStruts() {return useStruts;} public boolean useSpring() {return useSpring;} public boolean useIbatis() {return useIbatis;} public boolean useMyBatis() {return useMyBatis;} public boolean useHibernate() {return useHibernate;} public String list() { StringBuilder sb = new StringBuilder("["); if(useSpringMvc) sb.append("SpringMVC").append(","); if(useSpring) sb.append("Spring").append(","); if(useIbatis) sb.append("iBatis").append(","); if(useStruts) sb.append("Struts").append(","); if(useMyBatis) sb.append("MyBatis").append(","); if(useHibernate) sb.append("Hibernate").append(","); return sb.append("]").toString(); } }; cg.setFramework(framework); } else if("-s".equals(args[i]) || "--simple".equals(args[i])) { simplify = Integer.parseInt(args[i + 1]); String[] tpls, dirs; if((simplify & 1) != 0) { int index = cg.templates.indexOf("VO.ftl"); cg.templates.remove(index); cg.directories.remove(index); } if((simplify & 2) != 0) { int index = cg.templates.indexOf("Controller.ftl"); cg.templates.remove(index); cg.directories.remove(index); } if((simplify & 4) != 0) { int index = cg.templates.indexOf("ServiceImpl.ftl"); cg.templates.remove(index); cg.directories.remove(index); } if((simplify & 8) != 0) cg.setSamePackage(true); tpls = new String[cg.templates.size()]; dirs = new String[cg.directories.size()]; cg.templates.toArray(tpls); cg.directories.toArray(dirs); cg.setTpls(tpls); cg.setDirs(dirs); } } if(tmp != null) { String[] pairs = tmp.trim().split(";"); mapping = new HashMap<String, String>(pairs.length); for(int i = 0, j = pairs.length; i < j; i++) { if(pairs[i] == null || pairs[i].trim().length() == 0) throw new IllegalArgumentException("mapping arguments not correct: " + tmp); String[] pair = pairs[i].split("="); if(pair.length != 2) throw new IllegalArgumentException("mapping arguments must be pair: " + pairs[i]); mapping.put(pair[0], pair[1]); } cg.setDataTypeMapping(mapping); cg.registeDataTypeMapping(); } cg.setSqlFiles(args[args.length - 1].split(";")); cg.generate(); } private static String getFileName(String prefix, String fileName) { StringBuilder sb = new StringBuilder(); if(!fileName.equals("package-info.java")) sb.append(capFirst(prefix)); sb.append(fileName); return sb.toString(); } private static String capFirst(String camelCase) { if(camelCase == null) return null; char[] array = camelCase.toCharArray(); if(array[0] >= 'a' && array[0] <= 'z') array[0] = Character.toUpperCase(array[0]); return new String(array); } public static interface Convension { /** * prefer xml configure application */ boolean isUseXml(); /** * prefer annotation configure application */ boolean isUseAnnotation(); } public static interface Framework { /** * prefer Spring MVC as MVC framework * @return */ boolean useSpringMvc(); /** * prefer Struts2 as MVC framework * @return */ boolean useStruts(); /** * prefer Spring as DI framework * @return */ boolean useSpring(); /** * prefer iBatis2 as ORM framework * @return */ boolean useIbatis(); /** * prefer MyBatis3 as ORM framework * @return */ boolean useMyBatis(); /** * prefer Hibernate as ORM framework * @return */ boolean useHibernate(); /** * list used framework as string * @return */ String list(); } public GeneratePolicy getPolicy() { return policy; } public void setPolicy(GeneratePolicy policy) { this.policy = policy; } public Dialect getDialect() { return dialect; } public void setDialect(Dialect dialect) { this.dialect = dialect; } public String[] getTpls() { return tpls; } public void setTpls(String[] tpls) { this.tpls = tpls; } public String[] getDirs() { return dirs; } public void setDirs(String[] dirs) { this.dirs = dirs; } public boolean isSamePackage() { return samePackage; } public void setSamePackage(boolean samePackage) { this.samePackage = samePackage; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public Map<String, String> getDataTypeMapping() { return dataTypeMapping; } public void setDataTypeMapping(Map<String, String> dataTypeMapping) { this.dataTypeMapping = dataTypeMapping; } public String getTarget() { return target; } public void setTarget(String target) { this.target = target; } public boolean isWithClassNamePrefix() { return withClassNamePrefix; } public void setWithClassNamePrefix(boolean withClassNamePrefix) { this.withClassNamePrefix = withClassNamePrefix; } public String[] getSqlFiles() { return sqlFiles; } public void setSqlFiles(String[] sqlFiles) { this.sqlFiles = sqlFiles; } public Convension getConvension() { return convension; } public void setConvension(Convension convension) { this.convension = convension; } public Framework getFramework() { return framework; } public void setFramework(Framework framework) { this.framework = framework; } }
src/main/java/ml/iamwhatiam/tao/ddd/CodeGen.java
/** * MIT License * * Copyright (c) 2016 iMinusMinus * * 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. */ package ml.iamwhatiam.tao.ddd; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import freemarker.template.Configuration; /** * ddd code generator: refer to mybatis generator, spring data, hibernate * * @author iMinusMinus * @since 2017-01-16 * @version 0.0.1 * */ public final class CodeGen { private static Logger log = LoggerFactory.getLogger(CodeGen.class); private GeneratePolicy policy; private Dialect dialect; private String[] tpls; private String[] dirs; public CodeGen() { policy = GeneratePolicy.SOURCE; tpls = new String[] {"Controller.ftl", "ServiceImpl.ftl", "DAOImpl.ftl", "VO.ftl", "Domain.ftl", "sqlMap.ftl", "TransformationHelper.ftl"}; dirs = new String[] {"web", "service", "dao", "vo", "domain", "mapper", "support"}; } public static void main(String[] args) { if(args == null) System.out.println("Try 'java -jar tao -h' or 'java -jar tao --help' for more information"); else if("-h".equals(args[0]) || "--help".equals(args[0])) { System.out.println("-d, --dialect specify sql dialect. MYSQL, POSTGRES, ORACLE, DB2, SQLSERVER, SYBASE, INFOMIX expected."); System.out.println("-t, --target which directory generated fiels will be place in. if not specified, use /ml/iamwhatiam/tao/ddd."); System.out.println("-n, --namespace parent package of generated files. use table.schema or table.catalog by default."); System.out.println("-c, --config Annotation: 1, XML: 2, SpringMVC: 4, Spring: 8, iBatis: 16, Struts: 32, MyBatis: 64, Hibernate: 128"); System.out.println("-m, --mapping how sql data type mapping to java type. for example: TINYINT=byte;NUMBER=java.math.BigDecimal."); System.out.println("-s, --simple 1: no VO only DO, 2: no Controller, 4: no Service, 8: VO, DO, Controller, Service, DAO and sqlMap in same package"); } else if(args.length < 5) throw new RuntimeException("-d --dialect must be specified!"); Dialect dialect = null; String target = null;//like src/main/java/ml/iamwhatiam/tao/ddd Map<String, String> mapping = null; String tmp = null; String namespace = null; int enabled = 0; int simplify = 0; StringBuilder config = new StringBuilder(); for(int i = 0, j = args.length; i < j; i += 2) { if("-d".equals(args[i]) || "--dialect".equals(args[i])) { dialect = Dialect.valueOf(args[i + 1].toUpperCase()); } else if("-t".equals(args[i]) || "--target".equals(args[i])) { target = args[i + 1]; } else if("-m".equals(args[i]) || "--mapping".equals(args[i])) { tmp = args[i + 1]; } else if("-n".equals(args[i]) || "--namespace".equals(args[i])) { namespace = args[i + 1]; } else if("-c".equals(args[i]) || "--config".equals(args[i])) { enabled = Integer.parseInt(args[i + 1]); String[] all = {"Annotation", "XML", "SpringMVC", "Spring", "iBatis", "Struts", "MyBatis", "Hibernate"}; int power = 0; while(power < all.length) { if((enabled & (1 << power)) != 0) config.append(all[power]).append(","); power++; } } else if("-s".equals(args[i]) || "--simple".equals(args[i])) { simplify = Integer.parseInt(args[i + 1]); } } if(tmp != null) { String[] pairs = tmp.trim().split(";"); mapping = new HashMap<String, String>(pairs.length); for(int i = 0, j = pairs.length; i < j; i++) { if(pairs[i] == null || pairs[i].trim().length() == 0) throw new IllegalArgumentException("mapping arguments not correct: " + tmp); String[] pair = pairs[i].split("="); if(pair.length != 2) throw new IllegalArgumentException("mapping arguments must be pair: " + pairs[i]); mapping.put(pair[0], pair[1]); } TransformationHelper.registeDataTypeMapping(dialect, mapping); } SQLParser parser = new SQLParser(dialect); FileInputStream fis; try { fis = new FileInputStream(new File(args[args.length - 1])); } catch (FileNotFoundException e) { throw new RuntimeException(String.format("file [%s] not exist", args[args.length - 1])); } Map<String, Object> root = new HashMap<String, Object>(); Table table = parser.parse(fis); if(namespace == null) namespace = table.getCatalog() == null ? table.getSchema() : table.getCatalog(); if(namespace == null) { log.warn("use radon namespace while namespace not find"); namespace = Long.toHexString(System.currentTimeMillis()); } if(dialect != Dialect.POSTGRES) namespace = namespace.toLowerCase(); namespace = TransformationHelper.snake2camel(namespace); target = target + File.separator + namespace + File.separator; JavaBean bean = TransformationHelper.table2bean(table); root.put("table", table); root.put("bean", bean); root.put("namespace", namespace); root.put("date", new Date()); root.put("config", config.toString()); root.put("samePackage", (simplify & 8) != 0); Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setClassForTemplateLoading(CodeGen.class, "/ml/iamwhatiam/tao/ddd"); CodeGen cg = new CodeGen(); for(int i = 0; i < cg.tpls.length; i++) { String tpl = cg.tpls[i]; Writer out = null; String name = null; if((simplify & 1) != 0 && (tpl.equals("VO.ftl") || tpl.equals("TransformationHelper.ftl"))) continue; if((simplify & 2) != 0 && (tpl.equals("Controller.ftl") || tpl.equals("JSP.ftl"))) continue; if((simplify & 4) != 0 && tpl.equals("Service.ftl")) continue; if(config.indexOf("SpringMVC") == 0 && tpl.equals("Controller.ftl")) continue;//Struts2 and so on if(config.indexOf("Batis") == 0 && (tpl.equals("sqlMap.ftl") || tpl.equals("DAO.ftl"))) continue;//Hibernate and so on try { switch(cg.policy) { case SOURCE: String old = tpl.substring(0, tpl.indexOf(".") + 1); if("sqlMap.".equals(old)) name = old + ".xml"; else name = old + "java";//XxxPattern or Pattern? File file = new File(target + cg.dirs[i] + File.separator + capFirst(bean.getName()) + name);//FIXME when Controller, Service etc. not in same package if(!file.getParentFile().exists()) file.getParentFile().mkdirs(); file.createNewFile(); out = new FileWriter(file); break; case CLASS: case RUNTIME: name = tpl.substring(0, tpl.indexOf(".") + 1) + "java"; out = new StringWriter(); break; default: } cfg.getTemplate(tpl).process(root, out); } catch (Exception e) { e.printStackTrace(); } } } private static String capFirst(String camelCase) { if(camelCase == null) return null; char[] array = camelCase.toCharArray(); if(array[0] >= 'a' && array[0] <= 'z') array[0] = Character.toUpperCase(array[0]); return new String(array); } }
codegen refactor
src/main/java/ml/iamwhatiam/tao/ddd/CodeGen.java
codegen refactor
<ide><path>rc/main/java/ml/iamwhatiam/tao/ddd/CodeGen.java <ide> import java.io.FileWriter; <ide> import java.io.StringWriter; <ide> import java.io.Writer; <add>import java.util.ArrayList; <add>import java.util.Arrays; <ide> import java.util.Date; <ide> import java.util.HashMap; <add>import java.util.List; <ide> import java.util.Map; <ide> <ide> import org.slf4j.Logger; <ide> <ide> private static Logger log = LoggerFactory.getLogger(CodeGen.class); <ide> <add> private final List<String> templates = new ArrayList<String>( <add> Arrays.asList("Controller.ftl", "ServiceImpl.ftl", "DAOImpl.ftl", "VO.ftl", "Domain.ftl", <add> "sqlMap.ftl", "TransformationHelper.ftl", "package-info.ftl")); <add> <add> private final List<String> directories = new ArrayList<String>(Arrays.asList("web", "service", "dao", "vo", "domain", "mapper", "support", "")); <add> <add> /** <add> * generate source code or class file, or just runtime <add> */ <ide> private GeneratePolicy policy; <ide> <add> /** <add> * dbms dialect <add> */ <ide> private Dialect dialect; <ide> <add> /** <add> * templates <add> */ <ide> private String[] tpls; <ide> <add> /** <add> * directories template will output to <add> */ <ide> private String[] dirs; <add> <add> /** <add> * generate files merged in one package <add> */ <add> private boolean samePackage; <add> <add> /** <add> * package <add> */ <add> private String namespace; <add> <add> /** <add> * SQL dataType mapping to java type <add> */ <add> private Map<String, String> dataTypeMapping; <add> <add> /** <add> * directory source file generated in <add> */ <add> private String target; <add> <add> /** <add> * class name with fixed[tableName] prefix or not <add> */ <add> private boolean withClassNamePrefix; <add> <add> private String[] sqlFiles; <add> <add> private Convension convension; <add> <add> private Framework framework; <ide> <ide> public CodeGen() { <ide> policy = GeneratePolicy.SOURCE; <del> tpls = new String[] {"Controller.ftl", "ServiceImpl.ftl", "DAOImpl.ftl", "VO.ftl", "Domain.ftl", "sqlMap.ftl", "TransformationHelper.ftl"}; <del> dirs = new String[] {"web", "service", "dao", "vo", "domain", "mapper", "support"}; <del> } <del> <del> public static void main(String[] args) { <del> if(args == null) System.out.println("Try 'java -jar tao -h' or 'java -jar tao --help' for more information"); <del> else if("-h".equals(args[0]) || "--help".equals(args[0])) { <del> System.out.println("-d, --dialect specify sql dialect. MYSQL, POSTGRES, ORACLE, DB2, SQLSERVER, SYBASE, INFOMIX expected."); <del> System.out.println("-t, --target which directory generated fiels will be place in. if not specified, use /ml/iamwhatiam/tao/ddd."); <del> System.out.println("-n, --namespace parent package of generated files. use table.schema or table.catalog by default."); <del> System.out.println("-c, --config Annotation: 1, XML: 2, SpringMVC: 4, Spring: 8, iBatis: 16, Struts: 32, MyBatis: 64, Hibernate: 128"); <del> System.out.println("-m, --mapping how sql data type mapping to java type. for example: TINYINT=byte;NUMBER=java.math.BigDecimal."); <del> System.out.println("-s, --simple 1: no VO only DO, 2: no Controller, 4: no Service, 8: VO, DO, Controller, Service, DAO and sqlMap in same package"); <del> } <del> else if(args.length < 5) throw new RuntimeException("-d --dialect must be specified!"); <del> Dialect dialect = null; <del> String target = null;//like src/main/java/ml/iamwhatiam/tao/ddd <del> Map<String, String> mapping = null; <del> String tmp = null; <del> String namespace = null; <del> int enabled = 0; <del> int simplify = 0; <del> StringBuilder config = new StringBuilder(); <del> for(int i = 0, j = args.length; i < j; i += 2) { <del> if("-d".equals(args[i]) || "--dialect".equals(args[i])) { <del> dialect = Dialect.valueOf(args[i + 1].toUpperCase()); <del> } <del> else if("-t".equals(args[i]) || "--target".equals(args[i])) { <del> target = args[i + 1]; <del> } <del> else if("-m".equals(args[i]) || "--mapping".equals(args[i])) { <del> tmp = args[i + 1]; <del> } <del> else if("-n".equals(args[i]) || "--namespace".equals(args[i])) { <del> namespace = args[i + 1]; <del> } <del> else if("-c".equals(args[i]) || "--config".equals(args[i])) { <del> enabled = Integer.parseInt(args[i + 1]); <del> String[] all = {"Annotation", "XML", "SpringMVC", "Spring", "iBatis", "Struts", "MyBatis", "Hibernate"}; <del> int power = 0; <del> while(power < all.length) { <del> if((enabled & (1 << power)) != 0) <del> config.append(all[power]).append(","); <del> power++; <del> } <del> } <del> else if("-s".equals(args[i]) || "--simple".equals(args[i])) { <del> simplify = Integer.parseInt(args[i + 1]); <del> } <del> } <del> if(tmp != null) { <del> String[] pairs = tmp.trim().split(";"); <del> mapping = new HashMap<String, String>(pairs.length); <del> for(int i = 0, j = pairs.length; i < j; i++) { <del> if(pairs[i] == null || pairs[i].trim().length() == 0) throw new IllegalArgumentException("mapping arguments not correct: " + tmp); <del> String[] pair = pairs[i].split("="); <del> if(pair.length != 2) throw new IllegalArgumentException("mapping arguments must be pair: " + pairs[i]); <del> mapping.put(pair[0], pair[1]); <del> } <del> TransformationHelper.registeDataTypeMapping(dialect, mapping); <del> } <add> tpls = new String[] {"Controller.ftl", "ServiceImpl.ftl", "DAOImpl.ftl", "VO.ftl", "Domain.ftl", "sqlMap.ftl", "TransformationHelper.ftl", "package-info.ftl"}; <add> dirs = new String[] {"web", "service", "dao", "vo", "domain", "mapper", "support", ""}; <add> target = "src/main/java/ml/iamwhatiam/tao/ddd"; <add> withClassNamePrefix = true; <add> convension = new Convension() { <add> public boolean isUseXml() {return true;} <add> public boolean isUseAnnotation() {return true;} <add> }; <add> framework = new Framework() { <add> public boolean useSpringMvc() {return true;} <add> public boolean useStruts() {return false;} <add> public boolean useSpring() {return true;} <add> public boolean useIbatis() {return true;} <add> public boolean useMyBatis() {return false;} <add> public boolean useHibernate() {return false;} <add> public String list() {return "[SpringMVC, Spring, iBatis]";} <add> }; <add> } <add> <add> public void registeDataTypeMapping() { <add> if(dataTypeMapping != null) <add> TransformationHelper.registeDataTypeMapping(dialect, dataTypeMapping); <add> } <add> <add> public void generate() { <ide> SQLParser parser = new SQLParser(dialect); <ide> FileInputStream fis; <ide> try { <del> fis = new FileInputStream(new File(args[args.length - 1])); <add> fis = new FileInputStream(new File(sqlFiles[0])); <ide> } catch (FileNotFoundException e) { <del> throw new RuntimeException(String.format("file [%s] not exist", args[args.length - 1])); <add> throw new RuntimeException(String.format("file [%s] not exist", sqlFiles[0])); <ide> } <ide> Map<String, Object> root = new HashMap<String, Object>(); <ide> Table table = parser.parse(fis); <ide> root.put("bean", bean); <ide> root.put("namespace", namespace); <ide> root.put("date", new Date()); <del> root.put("config", config.toString()); <del> root.put("samePackage", (simplify & 8) != 0); <add> root.put("config", framework.list()); <add> root.put("samePackage", samePackage); <ide> Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); <ide> cfg.setClassForTemplateLoading(CodeGen.class, "/ml/iamwhatiam/tao/ddd"); <del> CodeGen cg = new CodeGen(); <del> for(int i = 0; i < cg.tpls.length; i++) { <del> String tpl = cg.tpls[i]; <add> <add> for(int i = 0; i < tpls.length; i++) { <add> String tpl = tpls[i]; <ide> Writer out = null; <ide> String name = null; <del> if((simplify & 1) != 0 && (tpl.equals("VO.ftl") || tpl.equals("TransformationHelper.ftl"))) <del> continue; <del> if((simplify & 2) != 0 && (tpl.equals("Controller.ftl") || tpl.equals("JSP.ftl"))) <del> continue; <del> if((simplify & 4) != 0 && tpl.equals("Service.ftl")) <del> continue; <del> if(config.indexOf("SpringMVC") == 0 && tpl.equals("Controller.ftl")) continue;//Struts2 and so on <del> if(config.indexOf("Batis") == 0 && (tpl.equals("sqlMap.ftl") || tpl.equals("DAO.ftl"))) continue;//Hibernate and so on <ide> try { <del> switch(cg.policy) { <add> switch(policy) { <ide> case SOURCE: <ide> String old = tpl.substring(0, tpl.indexOf(".") + 1); <ide> if("sqlMap.".equals(old)) <ide> name = old + ".xml"; <ide> else name = old + "java";//XxxPattern or Pattern? <del> File file = new File(target + cg.dirs[i] + File.separator + capFirst(bean.getName()) + name);//FIXME when Controller, Service etc. not in same package <add> File file = null; <add> if(!samePackage) <add> file = new File(target + dirs[i] + File.separator + getFileName(bean.getName(), name)); <add> else file = new File(target + getFileName(bean.getName(), name)); <ide> if(!file.getParentFile().exists()) <ide> file.getParentFile().mkdirs(); <ide> file.createNewFile(); <ide> } <ide> } <ide> <add> public static void main(String[] args) { <add> if(args == null) System.out.println("Try 'java -jar tao -h' or 'java -jar tao --help' for more information"); <add> else if("-h".equals(args[0]) || "--help".equals(args[0])) { <add> System.out.println("-d, --dialect specify sql dialect. MYSQL, POSTGRES, ORACLE, DB2, MS_SQL, SYBASE, INFOMIX expected."); <add> System.out.println("-t, --target which directory generated fiels will be place in. if not specified, use /ml/iamwhatiam/tao/ddd."); <add> System.out.println("-n, --namespace parent package of generated files. use table.schema or table.catalog by default."); <add> System.out.println("-c, --config Annotation: 1, XML: 2, SpringMVC: 4, Spring: 8, iBatis: 16, Struts: 32, MyBatis: 64, Hibernate: 128"); <add> System.out.println("-m, --mapping how sql data type mapping to java type. for example: TINYINT=byte;NUMBER=java.math.BigDecimal."); <add> System.out.println("-s, --simple 1: no VO only DO, 2: no Controller, 4: no Service, 8: VO, DO, Controller, Service, DAO and sqlMap in same package"); <add> } <add> else if(args.length < 5) throw new RuntimeException("-d --dialect must be specified!"); <add> CodeGen cg = new CodeGen(); <add> Map<String, String> mapping = null; <add> String tmp = null; <add> int enabled = 0; <add> int simplify = 0; <add> for(int i = 0, j = args.length; i < j; i += 2) { <add> if("-d".equals(args[i]) || "--dialect".equals(args[i])) { <add> cg.setDialect(Dialect.valueOf(args[i + 1].toUpperCase())); <add> } <add> else if("-t".equals(args[i]) || "--target".equals(args[i])) { <add> cg.setTarget(args[i + 1]); <add> } <add> else if("-m".equals(args[i]) || "--mapping".equals(args[i])) { <add> tmp = args[i + 1]; <add> } <add> else if("-n".equals(args[i]) || "--namespace".equals(args[i])) { <add> cg.setNamespace(args[i + 1]); <add> } <add> else if("-c".equals(args[i]) || "--config".equals(args[i])) { <add> enabled = Integer.parseInt(args[i + 1]); <add> final boolean useAnnotation = (enabled & 1) != 0; <add> final boolean useXml = (enabled & 2) != 0; <add> Convension convension = new Convension() { <add> public boolean isUseXml() {return useXml;} <add> public boolean isUseAnnotation() {return useAnnotation;} <add> }; <add> cg.setConvension(convension); <add> final boolean useSpringMvc = (enabled & 4) != 0; <add> final boolean useSpring = (enabled & 8) != 0; <add> final boolean useIbatis = (enabled & 16) != 0; <add> final boolean useStruts = (enabled & 32) != 0; <add> final boolean useMyBatis = (enabled & 64) != 0; <add> final boolean useHibernate = (enabled & 128) != 0; <add> Framework framework = new Framework() { <add> public boolean useSpringMvc() {return useSpringMvc;} <add> public boolean useStruts() {return useStruts;} <add> public boolean useSpring() {return useSpring;} <add> public boolean useIbatis() {return useIbatis;} <add> public boolean useMyBatis() {return useMyBatis;} <add> public boolean useHibernate() {return useHibernate;} <add> public String list() { <add> StringBuilder sb = new StringBuilder("["); <add> if(useSpringMvc) sb.append("SpringMVC").append(","); <add> if(useSpring) sb.append("Spring").append(","); <add> if(useIbatis) sb.append("iBatis").append(","); <add> if(useStruts) sb.append("Struts").append(","); <add> if(useMyBatis) sb.append("MyBatis").append(","); <add> if(useHibernate) sb.append("Hibernate").append(","); <add> return sb.append("]").toString(); <add> } <add> }; <add> cg.setFramework(framework); <add> } <add> else if("-s".equals(args[i]) || "--simple".equals(args[i])) { <add> simplify = Integer.parseInt(args[i + 1]); <add> String[] tpls, dirs; <add> if((simplify & 1) != 0) { <add> int index = cg.templates.indexOf("VO.ftl"); <add> cg.templates.remove(index); <add> cg.directories.remove(index); <add> } <add> if((simplify & 2) != 0) { <add> int index = cg.templates.indexOf("Controller.ftl"); <add> cg.templates.remove(index); <add> cg.directories.remove(index); <add> } <add> if((simplify & 4) != 0) { <add> int index = cg.templates.indexOf("ServiceImpl.ftl"); <add> cg.templates.remove(index); <add> cg.directories.remove(index); <add> } <add> if((simplify & 8) != 0) cg.setSamePackage(true); <add> tpls = new String[cg.templates.size()]; <add> dirs = new String[cg.directories.size()]; <add> cg.templates.toArray(tpls); <add> cg.directories.toArray(dirs); <add> cg.setTpls(tpls); <add> cg.setDirs(dirs); <add> } <add> } <add> if(tmp != null) { <add> String[] pairs = tmp.trim().split(";"); <add> mapping = new HashMap<String, String>(pairs.length); <add> for(int i = 0, j = pairs.length; i < j; i++) { <add> if(pairs[i] == null || pairs[i].trim().length() == 0) throw new IllegalArgumentException("mapping arguments not correct: " + tmp); <add> String[] pair = pairs[i].split("="); <add> if(pair.length != 2) throw new IllegalArgumentException("mapping arguments must be pair: " + pairs[i]); <add> mapping.put(pair[0], pair[1]); <add> } <add> cg.setDataTypeMapping(mapping); <add> cg.registeDataTypeMapping(); <add> } <add> cg.setSqlFiles(args[args.length - 1].split(";")); <add> cg.generate(); <add> } <add> <add> private static String getFileName(String prefix, String fileName) { <add> StringBuilder sb = new StringBuilder(); <add> if(!fileName.equals("package-info.java")) <add> sb.append(capFirst(prefix)); <add> sb.append(fileName); <add> return sb.toString(); <add> } <add> <ide> private static String capFirst(String camelCase) { <ide> if(camelCase == null) return null; <ide> char[] array = camelCase.toCharArray(); <ide> array[0] = Character.toUpperCase(array[0]); <ide> return new String(array); <ide> } <add> <add> public static interface Convension { <add> <add> /** <add> * prefer xml configure application <add> */ <add> boolean isUseXml(); <add> <add> /** <add> * prefer annotation configure application <add> */ <add> boolean isUseAnnotation(); <add> <add> } <add> <add> public static interface Framework { <add> <add> /** <add> * prefer Spring MVC as MVC framework <add> * @return <add> */ <add> boolean useSpringMvc(); <add> <add> /** <add> * prefer Struts2 as MVC framework <add> * @return <add> */ <add> boolean useStruts(); <add> <add> /** <add> * prefer Spring as DI framework <add> * @return <add> */ <add> boolean useSpring(); <add> <add> /** <add> * prefer iBatis2 as ORM framework <add> * @return <add> */ <add> boolean useIbatis(); <add> <add> /** <add> * prefer MyBatis3 as ORM framework <add> * @return <add> */ <add> boolean useMyBatis(); <add> <add> /** <add> * prefer Hibernate as ORM framework <add> * @return <add> */ <add> boolean useHibernate(); <add> <add> /** <add> * list used framework as string <add> * @return <add> */ <add> String list(); <add> } <add> <add> public GeneratePolicy getPolicy() { <add> return policy; <add> } <add> <add> public void setPolicy(GeneratePolicy policy) { <add> this.policy = policy; <add> } <add> <add> public Dialect getDialect() { <add> return dialect; <add> } <add> <add> public void setDialect(Dialect dialect) { <add> this.dialect = dialect; <add> } <add> <add> public String[] getTpls() { <add> return tpls; <add> } <add> <add> public void setTpls(String[] tpls) { <add> this.tpls = tpls; <add> } <add> <add> public String[] getDirs() { <add> return dirs; <add> } <add> <add> public void setDirs(String[] dirs) { <add> this.dirs = dirs; <add> } <add> <add> public boolean isSamePackage() { <add> return samePackage; <add> } <add> <add> public void setSamePackage(boolean samePackage) { <add> this.samePackage = samePackage; <add> } <add> <add> public String getNamespace() { <add> return namespace; <add> } <add> <add> public void setNamespace(String namespace) { <add> this.namespace = namespace; <add> } <add> <add> public Map<String, String> getDataTypeMapping() { <add> return dataTypeMapping; <add> } <add> <add> public void setDataTypeMapping(Map<String, String> dataTypeMapping) { <add> this.dataTypeMapping = dataTypeMapping; <add> } <add> <add> public String getTarget() { <add> return target; <add> } <add> <add> public void setTarget(String target) { <add> this.target = target; <add> } <add> <add> public boolean isWithClassNamePrefix() { <add> return withClassNamePrefix; <add> } <add> <add> public void setWithClassNamePrefix(boolean withClassNamePrefix) { <add> this.withClassNamePrefix = withClassNamePrefix; <add> } <add> <add> public String[] getSqlFiles() { <add> return sqlFiles; <add> } <add> <add> public void setSqlFiles(String[] sqlFiles) { <add> this.sqlFiles = sqlFiles; <add> } <add> <add> public Convension getConvension() { <add> return convension; <add> } <add> <add> public void setConvension(Convension convension) { <add> this.convension = convension; <add> } <add> <add> public Framework getFramework() { <add> return framework; <add> } <add> <add> public void setFramework(Framework framework) { <add> this.framework = framework; <add> } <ide> <ide> }
Java
apache-2.0
454a133dbd748f7e1907922c9e3c7de1b3d043de
0
tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki,tateshitah/jspwiki
/* JSPWiki - a JSP-based WikiWiki clone. Copyright (C) 2005 Janne Jalkanen ([email protected]) 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.1 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ecyrd.jspwiki.search; import java.io.*; import java.util.*; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.MultiFieldQueryParser; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleHTMLEncoder; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.attachment.AttachmentManager; import com.ecyrd.jspwiki.providers.ProviderException; import com.ecyrd.jspwiki.providers.WikiPageProvider; import com.ecyrd.jspwiki.util.ClassUtil; import com.ecyrd.jspwiki.util.WikiBackgroundThread; /** * Interface for the search providers that handle searching the Wiki * * @author Arent-Jan Banck for Informatica * @since 2.2.21. */ public class LuceneSearchProvider implements SearchProvider { protected static final Logger log = Logger.getLogger(LuceneSearchProvider.class); private WikiEngine m_engine; // Lucene properties. /** Which analyzer to use. Default is StandardAnalyzer. */ public static final String PROP_LUCENE_ANALYZER = "jspwiki.lucene.analyzer"; private static final String PROP_LUCENE_INDEXDELAY = "jspwiki.lucene.indexdelay"; private static final String PROP_LUCENE_INITIALDELAY = "jspwiki.lucene.initialdelay"; private String m_analyzerClass = "org.apache.lucene.analysis.standard.StandardAnalyzer"; private static final String LUCENE_DIR = "lucene"; // Number of page updates before we optimize the index. public static final int LUCENE_OPTIMIZE_COUNT = 10; private static final String LUCENE_ID = "id"; private static final String LUCENE_PAGE_CONTENTS = "contents"; private static final String LUCENE_AUTHOR = "author"; private static final String LUCENE_ATTACHMENTS = "attachment"; private static final String LUCENE_PAGE_NAME = "name"; private String m_luceneDirectory = null; private int m_updateCount = 0; protected Vector m_updates = new Vector(); // Vector because multi-threaded. /** Maximum number of fragments from search matches. */ private static final int MAX_FRAGMENTS = 3; public void initialize(WikiEngine engine, Properties props) throws NoRequiredPropertyException, IOException { m_engine = engine; m_luceneDirectory = engine.getWorkDir()+File.separator+LUCENE_DIR; int initialDelay = TextUtil.getIntegerProperty( props, PROP_LUCENE_INITIALDELAY, LuceneUpdater.INITIAL_DELAY ); int indexDelay = TextUtil.getIntegerProperty( props, PROP_LUCENE_INDEXDELAY, LuceneUpdater.INDEX_DELAY ); m_analyzerClass = TextUtil.getStringProperty( props, PROP_LUCENE_ANALYZER, m_analyzerClass ); // FIXME: Just to be simple for now, we will do full reindex // only if no files are in lucene directory. File dir = new File(m_luceneDirectory); log.info("Lucene enabled, cache will be in: "+dir.getAbsolutePath()); try { if( !dir.exists() ) { dir.mkdirs(); } if( !dir.exists() || !dir.canWrite() || !dir.canRead() ) { log.error("Cannot write to Lucene directory, disabling Lucene: "+dir.getAbsolutePath()); throw new IOException( "Invalid Lucene directory." ); } String[] filelist = dir.list(); if( filelist == null ) { throw new IOException( "Invalid Lucene directory: cannot produce listing: "+dir.getAbsolutePath()); } } catch ( IOException e ) { log.error("Problem while creating Lucene index - not using Lucene.", e); } // Start the Lucene update thread, which waits first // for a little while before starting to go through // the Lucene "pages that need updating". LuceneUpdater updater = new LuceneUpdater( m_engine, this, initialDelay, indexDelay ); updater.start(); } /** * Performs a full Lucene reindex, if necessary. * @throws IOException */ protected void doFullLuceneReindex() throws IOException { File dir = new File(m_luceneDirectory); String[] filelist = dir.list(); if( filelist == null ) { throw new IOException( "Invalid Lucene directory: cannot produce listing: "+dir.getAbsolutePath()); } try { if( filelist.length == 0 ) { // // No files? Reindex! // Date start = new Date(); IndexWriter writer = null; log.info("Starting Lucene reindexing, this can take a couple minutes..."); // // Do lock recovery, in case JSPWiki was shut down forcibly // Directory luceneDir = FSDirectory.getDirectory(dir,false); if( IndexReader.isLocked(luceneDir) ) { log.info("JSPWiki was shut down while Lucene was indexing - unlocking now."); IndexReader.unlock( luceneDir ); } try { writer = new IndexWriter( m_luceneDirectory, getLuceneAnalyzer(), true ); Collection allPages = m_engine.getPageManager().getAllPages(); for( Iterator iterator = allPages.iterator(); iterator.hasNext(); ) { WikiPage page = (WikiPage) iterator.next(); String text = m_engine.getPageManager().getPageText( page.getName(), WikiProvider.LATEST_VERSION ); luceneIndexPage( page, text, writer ); } Collection allAttachments = m_engine.getAttachmentManager().getAllAttachments(); for( Iterator iterator = allAttachments.iterator(); iterator.hasNext(); ) { Attachment att = (Attachment) iterator.next(); String text = getAttachmentContent( att.getName(), WikiProvider.LATEST_VERSION ); luceneIndexPage( att, text, writer ); } writer.optimize(); } finally { try { if( writer != null ) writer.close(); } catch( IOException e ) {} } Date end = new Date(); log.info("Full Lucene index finished in " + (end.getTime() - start.getTime()) + " milliseconds."); } else { log.info("Files found in Lucene directory, not reindexing."); } } catch( NoClassDefFoundError e ) { log.info("Lucene libraries do not exist - not using Lucene."); } catch ( IOException e ) { log.error("Problem while creating Lucene index - not using Lucene.", e); } catch ( ProviderException e ) { log.error("Problem reading pages while creating Lucene index (JSPWiki won't start.)", e); throw new IllegalArgumentException("unable to create Lucene index"); } catch( ClassNotFoundException e ) { log.error("Illegal Analyzer specified:",e); } catch( Exception e ) { log.error("Unable to start lucene",e); } } /** * Fetches the attachment content from the repository. * Content is flat text that can be used for indexing/searching or display */ private String getAttachmentContent( String attachmentName, int version ) { AttachmentManager mgr = m_engine.getAttachmentManager(); try { Attachment att = mgr.getAttachmentInfo( attachmentName, version ); //FIXME: Find out why sometimes att is null if(att != null) { return getAttachmentContent( att ); } } catch (ProviderException e) { log.error("Attachment cannot be loaded", e); } // Something was wrong, no result is returned. return null; } /** * @param att Attachment to get content for. Filename extension is used to determine the type of the attachment. * @return String representing the content of the file. * FIXME This is a very simple implementation of some text-based attachment, mainly used for testing. * This should be replaced /moved to Attachment search providers or some other 'plugable' wat to search attachments */ private String getAttachmentContent( Attachment att ) { AttachmentManager mgr = m_engine.getAttachmentManager(); //FIXME: Add attachment plugin structure String filename = att.getFileName(); if(filename.endsWith(".txt") || filename.endsWith(".xml") || filename.endsWith(".ini") || filename.endsWith(".html")) { InputStream attStream; try { attStream = mgr.getAttachmentStream( att ); StringWriter sout = new StringWriter(); FileUtil.copyContents( new InputStreamReader(attStream), sout ); attStream.close(); sout.close(); return sout.toString(); } catch (ProviderException e) { log.error("Attachment cannot be loaded", e); return null; } catch (IOException e) { log.error("Attachment cannot be loaded", e); return null; } } return null; } protected synchronized void updateLuceneIndex( WikiPage page, String text ) { IndexWriter writer = null; log.debug("Updating Lucene index for page '" + page.getName() + "'..."); try { pageRemoved(page); // Now add back the new version. writer = new IndexWriter(m_luceneDirectory, getLuceneAnalyzer(), false); luceneIndexPage(page, text, writer); m_updateCount++; if( m_updateCount >= LUCENE_OPTIMIZE_COUNT ) { writer.optimize(); m_updateCount = 0; } } catch ( IOException e ) { log.error("Unable to update page '" + page.getName() + "' from Lucene index", e); } catch( Exception e ) { log.error("Unexpected Lucene exception - please check configuration!",e); } finally { try { if( writer != null ) writer.close(); } catch( IOException e ) {} } log.debug("Done updating Lucene index for page '" + page.getName() + "'."); } private Analyzer getLuceneAnalyzer() throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class clazz = ClassUtil.findClass( "", m_analyzerClass ); Analyzer analyzer = (Analyzer)clazz.newInstance(); return analyzer; } private void luceneIndexPage( WikiPage page, String text, IndexWriter writer ) throws IOException { // make a new, empty document Document doc = new Document(); if( text == null ) return; // Raw name is the keyword we'll use to refer to this document for updates. Field field = new Field(LUCENE_ID, page.getName(), Field.Store.YES, Field.Index.UN_TOKENIZED); doc.add( field ); // Body text. It is stored in the doc for search contexts. field = new Field(LUCENE_PAGE_CONTENTS, text, Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO); doc.add( field ); // Allow searching by page name. Both beautified and raw field = new Field(LUCENE_PAGE_NAME, TextUtil.beautifyString( page.getName() ) + " " + page.getName(), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO); doc.add( field ); // Allow searching by authorname if( page.getAuthor() != null ) { field = new Field(LUCENE_AUTHOR, page.getAuthor(), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO); doc.add( field ); } // Now add the names of the attachments of this page try { Collection attachments = m_engine.getAttachmentManager().listAttachments(page); String attachmentNames = ""; for( Iterator it = attachments.iterator(); it.hasNext(); ) { Attachment att = (Attachment) it.next(); attachmentNames += att.getName() + ";"; } field = new Field(LUCENE_ATTACHMENTS, attachmentNames, Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO); doc.add( field ); } catch(ProviderException e) { // Unable to read attachments log.error("Failed to get attachments for page", e); } writer.addDocument(doc); } public void pageRemoved( WikiPage page ) { try { // Must first remove existing version of page. IndexReader reader = IndexReader.open(m_luceneDirectory); reader.deleteDocuments(new Term(LUCENE_ID, page.getName())); reader.close(); } catch ( IOException e ) { log.error("Unable to update page '" + page.getName() + "' from Lucene index", e); } } /** * Adds a page-text pair to the lucene update queue. Safe to call always */ public void reindexPage( WikiPage page ) { if( page != null ) { String text; // TODO: Think if this was better done in the thread itself? if( page instanceof Attachment ) { text = getAttachmentContent( (Attachment) page ); } else { text = m_engine.getPureText( page ); } if( text != null ) { // Add work item to m_updates queue. Object[] pair = new Object[2]; pair[0] = page; pair[1] = text; m_updates.add(pair); log.debug("Scheduling page " + page.getName() + " for index update"); } } } public Collection findPages( String query ) throws ProviderException { Searcher searcher = null; ArrayList list = null; try { String[] queryfields = { LUCENE_PAGE_CONTENTS, LUCENE_PAGE_NAME, LUCENE_AUTHOR, LUCENE_ATTACHMENTS }; QueryParser qp = new MultiFieldQueryParser( queryfields, getLuceneAnalyzer() ); //QueryParser qp = new QueryParser( LUCENE_PAGE_CONTENTS, getLuceneAnalyzer() ); Query luceneQuery = qp.parse( query ); Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"searchmatch\">", "</span>"), new SimpleHTMLEncoder(), new QueryScorer(luceneQuery)); try { searcher = new IndexSearcher(m_luceneDirectory); } catch( Exception ex ) { log.info("Lucene not yet ready; indexing not started",ex); return null; } Hits hits = searcher.search(luceneQuery); list = new ArrayList(hits.length()); for ( int curr = 0; curr < hits.length(); curr++ ) { Document doc = hits.doc(curr); String pageName = doc.get(LUCENE_ID); WikiPage page = m_engine.getPage(pageName, WikiPageProvider.LATEST_VERSION); if(page != null) { if(page instanceof Attachment) { // Currently attachments don't look nice on the search-results page // When the search-results are cleaned up this can be enabled again. } int score = (int)(hits.score(curr) * 100); // Get highlighted search contexts String text = doc.get(LUCENE_PAGE_CONTENTS); String fragments[] = new String[0]; if (text != null) { TokenStream tokenStream = getLuceneAnalyzer() .tokenStream(LUCENE_PAGE_CONTENTS, new StringReader(text)); fragments = highlighter.getBestFragments(tokenStream, text, MAX_FRAGMENTS); } SearchResult result = new SearchResultImpl( page, score, fragments ); list.add(result); } else { log.error("Lucene found a result page '" + pageName + "' that could not be loaded, removing from Lucene cache"); pageRemoved(new WikiPage( m_engine, pageName )); } } } catch( IOException e ) { log.error("Failed during lucene search",e); } catch( InstantiationException e ) { log.error("Unable to get a Lucene analyzer",e); } catch( IllegalAccessException e ) { log.error("Unable to get a Lucene analyzer",e); } catch( ClassNotFoundException e ) { log.error("Specified Lucene analyzer does not exist",e); } catch( ParseException e ) { log.info("Broken query; cannot parse",e); throw new ProviderException("You have entered a query Lucene cannot process: "+e.getMessage()); } finally { if( searcher != null ) try { searcher.close(); } catch( IOException e ) {} } return list; } public String getProviderInfo() { return "LuceneSearchProvider"; } /** * Updater thread that updates Lucene indexes. */ private static class LuceneUpdater extends WikiBackgroundThread { protected static final int INDEX_DELAY = 1; protected static final int INITIAL_DELAY = 60; private final LuceneSearchProvider m_provider; private int initialDelay; private LuceneUpdater( WikiEngine engine, LuceneSearchProvider provider, int initialDelay, int indexDelay ) { super( engine, indexDelay ); m_provider = provider; setName("JSPWiki Lucene Indexer"); } public void startupTask() throws Exception { // Sleep initially... try { Thread.sleep( initialDelay * 1000L ); } catch( InterruptedException e ) { throw new InternalWikiException("Interrupted while waiting to start."); } // Reindex everything m_provider.doFullLuceneReindex(); } public void backgroundTask() throws Exception { synchronized ( m_provider.m_updates ) { while( m_provider.m_updates.size() > 0 ) { Object[] pair = ( Object[] ) m_provider.m_updates.remove(0); WikiPage page = ( WikiPage ) pair[0]; String text = ( String ) pair[1]; m_provider.updateLuceneIndex(page, text); } } } } // FIXME: This class is dumb; needs to have a better implementation private static class SearchResultImpl implements SearchResult { private WikiPage m_page; private int m_score; private String[] m_contexts; public SearchResultImpl( WikiPage page, int score, String[] contexts ) { m_page = page; m_score = score; m_contexts = contexts; } public WikiPage getPage() { return m_page; } /* (non-Javadoc) * @see com.ecyrd.jspwiki.SearchResult#getScore() */ public int getScore() { return m_score; } public String[] getContexts() { return m_contexts; } } }
src/com/ecyrd/jspwiki/search/LuceneSearchProvider.java
/* JSPWiki - a JSP-based WikiWiki clone. Copyright (C) 2005 Janne Jalkanen ([email protected]) 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.1 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ecyrd.jspwiki.search; import java.io.*; import java.util.*; import org.apache.log4j.Logger; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.TokenStream; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriter; import org.apache.lucene.index.Term; import org.apache.lucene.queryParser.MultiFieldQueryParser; import org.apache.lucene.queryParser.ParseException; import org.apache.lucene.queryParser.QueryParser; import org.apache.lucene.search.Hits; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.Searcher; import org.apache.lucene.search.highlight.Highlighter; import org.apache.lucene.search.highlight.QueryScorer; import org.apache.lucene.search.highlight.SimpleHTMLEncoder; import org.apache.lucene.search.highlight.SimpleHTMLFormatter; import org.apache.lucene.store.Directory; import org.apache.lucene.store.FSDirectory; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.attachment.Attachment; import com.ecyrd.jspwiki.attachment.AttachmentManager; import com.ecyrd.jspwiki.providers.ProviderException; import com.ecyrd.jspwiki.providers.WikiPageProvider; import com.ecyrd.jspwiki.util.ClassUtil; import com.ecyrd.jspwiki.util.WikiBackgroundThread; /** * Interface for the search providers that handle searching the Wiki * * @author Arent-Jan Banck for Informatica * @since 2.2.21. */ public class LuceneSearchProvider implements SearchProvider { protected static final Logger log = Logger.getLogger(LuceneSearchProvider.class); private WikiEngine m_engine; // Lucene properties. /** Which analyzer to use. Default is StandardAnalyzer. */ public static final String PROP_LUCENE_ANALYZER = "jspwiki.lucene.analyzer"; private static final String PROP_LUCENE_INDEXDELAY = "jspwiki.lucene.indexdelay"; private static final String PROP_LUCENE_INITIALDELAY = "jspwiki.lucene.initialdelay"; private String m_analyzerClass = "org.apache.lucene.analysis.standard.StandardAnalyzer"; private static final String LUCENE_DIR = "lucene"; // Number of page updates before we optimize the index. public static final int LUCENE_OPTIMIZE_COUNT = 10; private static final String LUCENE_ID = "id"; private static final String LUCENE_PAGE_CONTENTS = "contents"; private static final String LUCENE_AUTHOR = "author"; private static final String LUCENE_ATTACHMENTS = "attachment"; private static final String LUCENE_PAGE_NAME = "name"; private String m_luceneDirectory = null; private int m_updateCount = 0; protected Vector m_updates = new Vector(); // Vector because multi-threaded. /** Maximum number of fragments from search matches. */ private static final int MAX_FRAGMENTS = 3; public void initialize(WikiEngine engine, Properties props) throws NoRequiredPropertyException, IOException { m_engine = engine; m_luceneDirectory = engine.getWorkDir()+File.separator+LUCENE_DIR; int initialDelay = TextUtil.getIntegerProperty( props, PROP_LUCENE_INITIALDELAY, LuceneUpdater.INITIAL_DELAY ); int indexDelay = TextUtil.getIntegerProperty( props, PROP_LUCENE_INDEXDELAY, LuceneUpdater.INDEX_DELAY ); // FIXME: Just to be simple for now, we will do full reindex // only if no files are in lucene directory. File dir = new File(m_luceneDirectory); log.info("Lucene enabled, cache will be in: "+dir.getAbsolutePath()); try { if( !dir.exists() ) { dir.mkdirs(); } if( !dir.exists() || !dir.canWrite() || !dir.canRead() ) { log.error("Cannot write to Lucene directory, disabling Lucene: "+dir.getAbsolutePath()); throw new IOException( "Invalid Lucene directory." ); } String[] filelist = dir.list(); if( filelist == null ) { throw new IOException( "Invalid Lucene directory: cannot produce listing: "+dir.getAbsolutePath()); } } catch ( IOException e ) { log.error("Problem while creating Lucene index - not using Lucene.", e); } // Start the Lucene update thread, which waits first // for a little while before starting to go through // the Lucene "pages that need updating". LuceneUpdater updater = new LuceneUpdater( m_engine, this, initialDelay, indexDelay ); updater.start(); } /** * Performs a full Lucene reindex, if necessary. * @throws IOException */ protected void doFullLuceneReindex() throws IOException { File dir = new File(m_luceneDirectory); String[] filelist = dir.list(); if( filelist == null ) { throw new IOException( "Invalid Lucene directory: cannot produce listing: "+dir.getAbsolutePath()); } try { if( filelist.length == 0 ) { // // No files? Reindex! // Date start = new Date(); IndexWriter writer = null; log.info("Starting Lucene reindexing, this can take a couple minutes..."); // // Do lock recovery, in case JSPWiki was shut down forcibly // Directory luceneDir = FSDirectory.getDirectory(dir,false); if( IndexReader.isLocked(luceneDir) ) { log.info("JSPWiki was shut down while Lucene was indexing - unlocking now."); IndexReader.unlock( luceneDir ); } try { writer = new IndexWriter( m_luceneDirectory, getLuceneAnalyzer(), true ); Collection allPages = m_engine.getPageManager().getAllPages(); for( Iterator iterator = allPages.iterator(); iterator.hasNext(); ) { WikiPage page = (WikiPage) iterator.next(); String text = m_engine.getPageManager().getPageText( page.getName(), WikiProvider.LATEST_VERSION ); luceneIndexPage( page, text, writer ); } Collection allAttachments = m_engine.getAttachmentManager().getAllAttachments(); for( Iterator iterator = allAttachments.iterator(); iterator.hasNext(); ) { Attachment att = (Attachment) iterator.next(); String text = getAttachmentContent( att.getName(), WikiProvider.LATEST_VERSION ); luceneIndexPage( att, text, writer ); } writer.optimize(); } finally { try { if( writer != null ) writer.close(); } catch( IOException e ) {} } Date end = new Date(); log.info("Full Lucene index finished in " + (end.getTime() - start.getTime()) + " milliseconds."); } else { log.info("Files found in Lucene directory, not reindexing."); } } catch( NoClassDefFoundError e ) { log.info("Lucene libraries do not exist - not using Lucene."); } catch ( IOException e ) { log.error("Problem while creating Lucene index - not using Lucene.", e); } catch ( ProviderException e ) { log.error("Problem reading pages while creating Lucene index (JSPWiki won't start.)", e); throw new IllegalArgumentException("unable to create Lucene index"); } catch( ClassNotFoundException e ) { log.error("Illegal Analyzer specified:",e); } catch( Exception e ) { log.error("Unable to start lucene",e); } } /** * Fetches the attachment content from the repository. * Content is flat text that can be used for indexing/searching or display */ private String getAttachmentContent( String attachmentName, int version ) { AttachmentManager mgr = m_engine.getAttachmentManager(); try { Attachment att = mgr.getAttachmentInfo( attachmentName, version ); //FIXME: Find out why sometimes att is null if(att != null) { return getAttachmentContent( att ); } } catch (ProviderException e) { log.error("Attachment cannot be loaded", e); } // Something was wrong, no result is returned. return null; } /** * @param att Attachment to get content for. Filename extension is used to determine the type of the attachment. * @return String representing the content of the file. * FIXME This is a very simple implementation of some text-based attachment, mainly used for testing. * This should be replaced /moved to Attachment search providers or some other 'plugable' wat to search attachments */ private String getAttachmentContent( Attachment att ) { AttachmentManager mgr = m_engine.getAttachmentManager(); //FIXME: Add attachment plugin structure String filename = att.getFileName(); if(filename.endsWith(".txt") || filename.endsWith(".xml") || filename.endsWith(".ini") || filename.endsWith(".html")) { InputStream attStream; try { attStream = mgr.getAttachmentStream( att ); StringWriter sout = new StringWriter(); FileUtil.copyContents( new InputStreamReader(attStream), sout ); attStream.close(); sout.close(); return sout.toString(); } catch (ProviderException e) { log.error("Attachment cannot be loaded", e); return null; } catch (IOException e) { log.error("Attachment cannot be loaded", e); return null; } } return null; } protected synchronized void updateLuceneIndex( WikiPage page, String text ) { IndexWriter writer = null; log.debug("Updating Lucene index for page '" + page.getName() + "'..."); try { pageRemoved(page); // Now add back the new version. writer = new IndexWriter(m_luceneDirectory, getLuceneAnalyzer(), false); luceneIndexPage(page, text, writer); m_updateCount++; if( m_updateCount >= LUCENE_OPTIMIZE_COUNT ) { writer.optimize(); m_updateCount = 0; } } catch ( IOException e ) { log.error("Unable to update page '" + page.getName() + "' from Lucene index", e); } catch( Exception e ) { log.error("Unexpected Lucene exception - please check configuration!",e); } finally { try { if( writer != null ) writer.close(); } catch( IOException e ) {} } log.debug("Done updating Lucene index for page '" + page.getName() + "'."); } private Analyzer getLuceneAnalyzer() throws ClassNotFoundException, InstantiationException, IllegalAccessException { Class clazz = ClassUtil.findClass( "", m_analyzerClass ); Analyzer analyzer = (Analyzer)clazz.newInstance(); return analyzer; } private void luceneIndexPage( WikiPage page, String text, IndexWriter writer ) throws IOException { // make a new, empty document Document doc = new Document(); if( text == null ) return; // Raw name is the keyword we'll use to refer to this document for updates. Field field = new Field(LUCENE_ID, page.getName(), Field.Store.YES, Field.Index.UN_TOKENIZED); doc.add( field ); // Body text. It is stored in the doc for search contexts. field = new Field(LUCENE_PAGE_CONTENTS, text, Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO); doc.add( field ); // Allow searching by page name. Both beautified and raw field = new Field(LUCENE_PAGE_NAME, TextUtil.beautifyString( page.getName() ) + " " + page.getName(), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO); doc.add( field ); // Allow searching by authorname if( page.getAuthor() != null ) { field = new Field(LUCENE_AUTHOR, page.getAuthor(), Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO); doc.add( field ); } // Now add the names of the attachments of this page try { Collection attachments = m_engine.getAttachmentManager().listAttachments(page); String attachmentNames = ""; for( Iterator it = attachments.iterator(); it.hasNext(); ) { Attachment att = (Attachment) it.next(); attachmentNames += att.getName() + ";"; } field = new Field(LUCENE_ATTACHMENTS, attachmentNames, Field.Store.YES, Field.Index.TOKENIZED, Field.TermVector.NO); doc.add( field ); } catch(ProviderException e) { // Unable to read attachments log.error("Failed to get attachments for page", e); } writer.addDocument(doc); } public void pageRemoved( WikiPage page ) { try { // Must first remove existing version of page. IndexReader reader = IndexReader.open(m_luceneDirectory); reader.deleteDocuments(new Term(LUCENE_ID, page.getName())); reader.close(); } catch ( IOException e ) { log.error("Unable to update page '" + page.getName() + "' from Lucene index", e); } } /** * Adds a page-text pair to the lucene update queue. Safe to call always */ public void reindexPage( WikiPage page ) { if( page != null ) { String text; // TODO: Think if this was better done in the thread itself? if( page instanceof Attachment ) { text = getAttachmentContent( (Attachment) page ); } else { text = m_engine.getPureText( page ); } if( text != null ) { // Add work item to m_updates queue. Object[] pair = new Object[2]; pair[0] = page; pair[1] = text; m_updates.add(pair); log.debug("Scheduling page " + page.getName() + " for index update"); } } } public Collection findPages( String query ) throws ProviderException { Searcher searcher = null; ArrayList list = null; try { String[] queryfields = { LUCENE_PAGE_CONTENTS, LUCENE_PAGE_NAME, LUCENE_AUTHOR, LUCENE_ATTACHMENTS }; QueryParser qp = new MultiFieldQueryParser( queryfields, getLuceneAnalyzer() ); //QueryParser qp = new QueryParser( LUCENE_PAGE_CONTENTS, getLuceneAnalyzer() ); Query luceneQuery = qp.parse( query ); Highlighter highlighter = new Highlighter(new SimpleHTMLFormatter("<span class=\"searchmatch\">", "</span>"), new SimpleHTMLEncoder(), new QueryScorer(luceneQuery)); try { searcher = new IndexSearcher(m_luceneDirectory); } catch( Exception ex ) { log.info("Lucene not yet ready; indexing not started",ex); return null; } Hits hits = searcher.search(luceneQuery); list = new ArrayList(hits.length()); for ( int curr = 0; curr < hits.length(); curr++ ) { Document doc = hits.doc(curr); String pageName = doc.get(LUCENE_ID); WikiPage page = m_engine.getPage(pageName, WikiPageProvider.LATEST_VERSION); if(page != null) { if(page instanceof Attachment) { // Currently attachments don't look nice on the search-results page // When the search-results are cleaned up this can be enabled again. } int score = (int)(hits.score(curr) * 100); // Get highlighted search contexts String text = doc.get(LUCENE_PAGE_CONTENTS); String fragments[] = new String[0]; if (text != null) { TokenStream tokenStream = getLuceneAnalyzer() .tokenStream(LUCENE_PAGE_CONTENTS, new StringReader(text)); fragments = highlighter.getBestFragments(tokenStream, text, MAX_FRAGMENTS); } SearchResult result = new SearchResultImpl( page, score, fragments ); list.add(result); } else { log.error("Lucene found a result page '" + pageName + "' that could not be loaded, removing from Lucene cache"); pageRemoved(new WikiPage( m_engine, pageName )); } } } catch( IOException e ) { log.error("Failed during lucene search",e); } catch( InstantiationException e ) { log.error("Unable to get a Lucene analyzer",e); } catch( IllegalAccessException e ) { log.error("Unable to get a Lucene analyzer",e); } catch( ClassNotFoundException e ) { log.error("Specified Lucene analyzer does not exist",e); } catch( ParseException e ) { log.info("Broken query; cannot parse",e); throw new ProviderException("You have entered a query Lucene cannot process: "+e.getMessage()); } finally { if( searcher != null ) try { searcher.close(); } catch( IOException e ) {} } return list; } public String getProviderInfo() { return "LuceneSearchProvider"; } /** * Updater thread that updates Lucene indexes. */ private static class LuceneUpdater extends WikiBackgroundThread { protected static final int INDEX_DELAY = 1; protected static final int INITIAL_DELAY = 60; private final LuceneSearchProvider m_provider; private int initialDelay; private LuceneUpdater( WikiEngine engine, LuceneSearchProvider provider, int initialDelay, int indexDelay ) { super( engine, indexDelay ); m_provider = provider; setName("JSPWiki Lucene Indexer"); } public void startupTask() throws Exception { // Sleep initially... try { Thread.sleep( initialDelay * 1000L ); } catch( InterruptedException e ) { throw new InternalWikiException("Interrupted while waiting to start."); } // Reindex everything m_provider.doFullLuceneReindex(); } public void backgroundTask() throws Exception { synchronized ( m_provider.m_updates ) { while( m_provider.m_updates.size() > 0 ) { Object[] pair = ( Object[] ) m_provider.m_updates.remove(0); WikiPage page = ( WikiPage ) pair[0]; String text = ( String ) pair[1]; m_provider.updateLuceneIndex(page, text); } } } } // FIXME: This class is dumb; needs to have a better implementation private static class SearchResultImpl implements SearchResult { private WikiPage m_page; private int m_score; private String[] m_contexts; public SearchResultImpl( WikiPage page, int score, String[] contexts ) { m_page = page; m_score = score; m_contexts = contexts; } public WikiPage getPage() { return m_page; } /* (non-Javadoc) * @see com.ecyrd.jspwiki.SearchResult#getScore() */ public int getScore() { return m_score; } public String[] getContexts() { return m_contexts; } } }
Now actually reads the analyzer class from properties... git-svn-id: 6c0206e3b9edd104850923da33ebd73b435d374d@625749 13f79535-47bb-0310-9956-ffa450edef68
src/com/ecyrd/jspwiki/search/LuceneSearchProvider.java
Now actually reads the analyzer class from properties...
<ide><path>rc/com/ecyrd/jspwiki/search/LuceneSearchProvider.java <ide> int initialDelay = TextUtil.getIntegerProperty( props, PROP_LUCENE_INITIALDELAY, LuceneUpdater.INITIAL_DELAY ); <ide> int indexDelay = TextUtil.getIntegerProperty( props, PROP_LUCENE_INDEXDELAY, LuceneUpdater.INDEX_DELAY ); <ide> <add> m_analyzerClass = TextUtil.getStringProperty( props, PROP_LUCENE_ANALYZER, m_analyzerClass ); <ide> // FIXME: Just to be simple for now, we will do full reindex <ide> // only if no files are in lucene directory. <ide>
Java
agpl-3.0
f6de412f5787fceb223798005368742e0a9ef032
0
deepstupid/sphinx5
/* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.decoder.linguist; import edu.cmu.sphinx.util.SphinxProperties; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.knowledge.dictionary.Word; import edu.cmu.sphinx.knowledge.language.LanguageModel; import edu.cmu.sphinx.knowledge.language.WordSequence; import edu.cmu.sphinx.decoder.linguist.Grammar; import edu.cmu.sphinx.decoder.linguist.GrammarNode; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.Iterator; import java.util.ArrayList; /** * Defines a grammar based upon a lanaguage model * * This is a simple version that generates one grammar node per word. * This grammar can deal with unigram and bigram grammars of up to * 1000 or so words. * * Note that all probabilities are in the log math domain */ public class LMGrammar extends Grammar { /** * Creates the grammar from the language model. This Grammar * contains one word per grammar node. Each word (and grammar * node) is connected to all other words with the given * probability * * @return the initial grammar node */ protected GrammarNode createGrammar() throws IOException, NoSuchMethodException { Timer.start("LMGrammar.create"); LanguageModel languageModel = getLanguageModel(); GrammarNode firstNode = null; if (languageModel == null) { throw new Error("No language model for LMGramar"); } if (languageModel.getMaxDepth() > 2) { System.out.println("Warning: LMGrammar limited to bigrams"); } // if the language model log base doesn't match the log base of // this grammar, something lis probably wrong so we should just // abort. TODO: perhaps we should just adapt the probs. if (languageModel.getLogMath() != getLogMath()) { throw new Error("Mismatch log error in grammar"); } int identity = 0; List nodes = new ArrayList(); Set words = getLanguageModel().getVocabulary(); // create all of the word nodes for (Iterator i = words.iterator(); i.hasNext(); ) { String word = (String) i.next(); GrammarNode node = createGrammarNode(identity++, word); if (node != null && !node.isEmpty()) { if (node.getWord().isSentenceStart()) { firstNode = node; } else if (node.getWord().isSentenceEnd()) { node.setFinalNode(true); } nodes.add(node); } } if (firstNode == null) { throw new Error("No sentence start found in language model"); } System.out.println("In LMGrammar"); for (Iterator i = nodes.iterator(); i.hasNext(); ) { GrammarNode prevNode = (GrammarNode) i.next(); // don't add any branches out of the final node if (prevNode.isFinalNode()) { continue; } for (Iterator j = nodes.iterator(); j.hasNext(); ) { GrammarNode nextNode = (GrammarNode) j.next(); String prevWord = prevNode.getWord().getSpelling(); String nextWord = nextNode.getWord().getSpelling(); Word[] wordArray = {getDictionary().getWord(prevWord), getDictionary().getWord(nextWord)}; float logProbability = languageModel.getProbability (WordSequence.getWordSequence(wordArray)); prevNode.add(nextNode, logProbability); } } System.out.println("Out of LMGrammar"); Timer.stop("LMGrammar.create"); return firstNode; } }
edu/cmu/sphinx/decoder/linguist/LMGrammar.java
/* * Copyright 1999-2002 Carnegie Mellon University. * Portions Copyright 2002 Sun Microsystems, Inc. * Portions Copyright 2002 Mitsubishi Electronic Research Laboratories. * All Rights Reserved. Use is subject to license terms. * * See the file "license.terms" for information on usage and * redistribution of this file, and for a DISCLAIMER OF ALL * WARRANTIES. * */ package edu.cmu.sphinx.decoder.linguist; import edu.cmu.sphinx.util.SphinxProperties; import edu.cmu.sphinx.util.Timer; import edu.cmu.sphinx.knowledge.language.LanguageModel; import edu.cmu.sphinx.knowledge.language.WordSequence; import edu.cmu.sphinx.decoder.linguist.Grammar; import edu.cmu.sphinx.decoder.linguist.GrammarNode; import java.io.IOException; import java.util.List; import java.util.Set; import java.util.Iterator; import java.util.ArrayList; /** * Defines a grammar based upon a lanaguage model * * This is a simple version that generates one grammar node per word. * This grammar can deal with unigram and bigram grammars of up to * 1000 or so words. * * Note that all probabilities are in the log math domain */ public class LMGrammar extends Grammar { /** * Creates the grammar from the language model. This Grammar * contains one word per grammar node. Each word (and grammar * node) is connected to all other words with the given * probability * * @return the initial grammar node */ protected GrammarNode createGrammar() throws IOException, NoSuchMethodException { Timer.start("LMGrammar.create"); LanguageModel languageModel = getLanguageModel(); GrammarNode firstNode = null; if (languageModel == null) { throw new Error("No language model for LMGramar"); } if (languageModel.getMaxDepth() > 2) { System.out.println("Warning: LMGrammar limited to bigrams"); } // if the language model log base doesn't match the log base of // this grammar, something lis probably wrong so we should just // abort. TODO: perhaps we should just adapt the probs. if (languageModel.getLogMath() != getLogMath()) { throw new Error("Mismatch log error in grammar"); } int identity = 0; List nodes = new ArrayList(); Set words = getLanguageModel().getVocabulary(); // create all of the word nodes for (Iterator i = words.iterator(); i.hasNext(); ) { String word = (String) i.next(); GrammarNode node = createGrammarNode(identity++, word); if (node != null && !node.isEmpty()) { if (node.getWord().isSentenceStart()) { firstNode = node; } else if (node.getWord().isSentenceEnd()) { node.setFinalNode(true); } nodes.add(node); } } if (firstNode == null) { throw new Error("No sentence start found in language model"); } System.out.println("In LMGrammar"); for (Iterator i = nodes.iterator(); i.hasNext(); ) { GrammarNode prevNode = (GrammarNode) i.next(); // don't add any branches out of the final node if (prevNode.isFinalNode()) { continue; } for (Iterator j = nodes.iterator(); j.hasNext(); ) { GrammarNode nextNode = (GrammarNode) j.next(); String prevWord = prevNode.getWord().getSpelling(); String nextWord = nextNode.getWord().getSpelling(); int[] wordIDs = {getDictionary().getWordID(prevWord), getDictionary().getWordID(nextWord)}; float logProbability = languageModel.getProbability (WordSequence.getWordSequence(wordIDs)); prevNode.add(nextNode, logProbability); } } System.out.println("Out of LMGrammar"); Timer.stop("LMGrammar.create"); return firstNode; } }
Uses Word objects instead of word IDs. git-svn-id: a8b04003a33e1d3e001b9d20391fa392a9f62d91@1921 94700074-3cef-4d97-a70e-9c8c206c02f5
edu/cmu/sphinx/decoder/linguist/LMGrammar.java
Uses Word objects instead of word IDs.
<ide><path>du/cmu/sphinx/decoder/linguist/LMGrammar.java <ide> <ide> import edu.cmu.sphinx.util.SphinxProperties; <ide> import edu.cmu.sphinx.util.Timer; <add>import edu.cmu.sphinx.knowledge.dictionary.Word; <ide> import edu.cmu.sphinx.knowledge.language.LanguageModel; <ide> import edu.cmu.sphinx.knowledge.language.WordSequence; <ide> import edu.cmu.sphinx.decoder.linguist.Grammar; <ide> GrammarNode nextNode = (GrammarNode) j.next(); <ide> String prevWord = prevNode.getWord().getSpelling(); <ide> String nextWord = nextNode.getWord().getSpelling(); <del> int[] wordIDs = <del> {getDictionary().getWordID(prevWord), <del> getDictionary().getWordID(nextWord)}; <add> Word[] wordArray = <add> {getDictionary().getWord(prevWord), <add> getDictionary().getWord(nextWord)}; <ide> <ide> float logProbability = languageModel.getProbability <del> (WordSequence.getWordSequence(wordIDs)); <add> (WordSequence.getWordSequence(wordArray)); <ide> <ide> prevNode.add(nextNode, logProbability); <ide>
Java
apache-2.0
0f21a8225604a60244bc7c602b0a7fc52176ac98
0
wschaeferB/autopsy,esaunders/autopsy,esaunders/autopsy,wschaeferB/autopsy,rcordovano/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,rcordovano/autopsy,wschaeferB/autopsy,wschaeferB/autopsy,esaunders/autopsy,rcordovano/autopsy,esaunders/autopsy
/* * Autopsy Forensic Browser * * Copyright 2019 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obt ain 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.sleuthkit.autopsy.communications.relationships; import java.awt.Component; import java.awt.KeyboardFocusManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import javax.swing.JPanel; import static javax.swing.SwingUtilities.isDescendingFrom; import org.openide.explorer.ExplorerManager; import static org.openide.explorer.ExplorerUtils.createLookup; import org.openide.nodes.AbstractNode; import org.openide.nodes.Node; import org.openide.util.Lookup; import org.openide.util.NbBundle.Messages; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; import org.sleuthkit.autopsy.communications.ModifiableProxyLookup; import org.sleuthkit.autopsy.corecomponents.TableFilterNode; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.datamodel.BlackboardArtifactNode; import org.sleuthkit.autopsy.directorytree.DataResultFilterNode; import org.sleuthkit.datamodel.AbstractContent; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.CommunicationsManager; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.TskCoreException; /** * A Panel that shows the media (thumbnails) for the selected account. */ final class MediaViewer extends JPanel implements RelationshipsViewer, ExplorerManager.Provider, Lookup.Provider { private static final Logger logger = Logger.getLogger(MediaViewer.class.getName()); private final ExplorerManager tableEM = new ExplorerManager(); private final PropertyChangeListener focusPropertyListener; private final ModifiableProxyLookup proxyLookup; @Messages({ "MediaViewer_Name=Media" }) /** * Creates new form ThumbnailViewer */ public MediaViewer() { initComponents(); splitPane.setResizeWeight(0.5); splitPane.setDividerLocation(0.5); proxyLookup = new ModifiableProxyLookup(createLookup(tableEM, getActionMap())); // See org.sleuthkit.autopsy.timeline.TimeLineTopComponent for a detailed // explaination of focusPropertyListener focusPropertyListener = (final PropertyChangeEvent focusEvent) -> { if (focusEvent.getPropertyName().equalsIgnoreCase("focusOwner")) { final Component newFocusOwner = (Component) focusEvent.getNewValue(); if (newFocusOwner == null) { return; } if (isDescendingFrom(newFocusOwner, contentViewer)) { //if the focus owner is within the MessageContentViewer (the attachments table) proxyLookup.setNewLookups(createLookup(((MessageDataContent) contentViewer).getExplorerManager(), getActionMap())); } else if (isDescendingFrom(newFocusOwner, MediaViewer.this)) { //... or if it is within the Results table. proxyLookup.setNewLookups(createLookup(tableEM, getActionMap())); } } }; tableEM.addPropertyChangeListener((PropertyChangeEvent evt) -> { if (evt.getPropertyName().equals(ExplorerManager.PROP_SELECTED_NODES)) { handleNodeSelectionChange(); } }); thumbnailViewer.resetComponent(); } @Override public String getDisplayName() { return Bundle.MediaViewer_Name(); } @Override public JPanel getPanel() { return this; } @Override public void setSelectionInfo(SelectionInfo info) { final Set<Content> relationshipSources; CommunicationsManager communicationManager; Set<BlackboardArtifact> artifactList = new HashSet<>(); try { communicationManager = Case.getCurrentCaseThrows().getSleuthkitCase().getCommunicationsManager(); relationshipSources = communicationManager.getRelationshipSources(info.getAccountDevicesInstances(), info.getCommunicationsFilter()); relationshipSources.stream().filter((content) -> (content instanceof BlackboardArtifact)).forEachOrdered((content) -> { artifactList.add((BlackboardArtifact) content); }); } catch (TskCoreException | NoCurrentCaseException ex) { logger.log(Level.WARNING, "Unable to update selection." , ex); } thumbnailViewer.resetComponent(); thumbnailViewer.setNode(new TableFilterNode(new DataResultFilterNode(new AbstractNode(new AttachmentsChildren(artifactList)), tableEM), true, this.getClass().getName())); } @Override public ExplorerManager getExplorerManager() { return tableEM; } @Override public Lookup getLookup() { return proxyLookup; } @Override public void addNotify() { super.addNotify(); //add listener that maintains correct selection in the Global Actions Context KeyboardFocusManager.getCurrentKeyboardFocusManager() .addPropertyChangeListener("focusOwner", focusPropertyListener); } @Override public void removeNotify() { super.removeNotify(); KeyboardFocusManager.getCurrentKeyboardFocusManager() .removePropertyChangeListener("focusOwner", focusPropertyListener); } /** * Handle the change in thumbnail node selection. */ private void handleNodeSelectionChange() { final Node[] nodes = tableEM.getSelectedNodes(); if (nodes != null && nodes.length == 1) { AbstractContent thumbnail = nodes[0].getLookup().lookup(AbstractContent.class); if (thumbnail != null) { try { Content parentContent = thumbnail.getParent(); if (parentContent != null && parentContent instanceof BlackboardArtifact) { contentViewer.setNode(new BlackboardArtifactNode((BlackboardArtifact) parentContent)); } } catch (TskCoreException ex) { logger.log(Level.WARNING, "Unable to get parent Content from AbstraceContent instance.", ex); //NON-NLS } } } else { contentViewer.setNode(null); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; splitPane = new javax.swing.JSplitPane(); thumbnailViewer = new org.sleuthkit.autopsy.corecomponents.DataResultViewerThumbnail(tableEM); contentViewer = new MessageDataContent(); setLayout(new java.awt.GridBagLayout()); splitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); thumbnailViewer.setMinimumSize(new java.awt.Dimension(350, 102)); thumbnailViewer.setPreferredSize(new java.awt.Dimension(450, 400)); splitPane.setLeftComponent(thumbnailViewer); contentViewer.setPreferredSize(new java.awt.Dimension(450, 400)); splitPane.setRightComponent(contentViewer); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(splitPane, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private org.sleuthkit.autopsy.contentviewers.MessageContentViewer contentViewer; private javax.swing.JSplitPane splitPane; private org.sleuthkit.autopsy.corecomponents.DataResultViewerThumbnail thumbnailViewer; // End of variables declaration//GEN-END:variables }
Core/src/org/sleuthkit/autopsy/communications/relationships/MediaViewer.java
/* * Autopsy Forensic Browser * * Copyright 2019 Basis Technology Corp. * Contact: carrier <at> sleuthkit <dot> org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obt ain 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.sleuthkit.autopsy.communications.relationships; import java.awt.Component; import java.awt.KeyboardFocusManager; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.util.HashSet; import java.util.Set; import java.util.logging.Level; import javax.swing.JPanel; import static javax.swing.SwingUtilities.isDescendingFrom; import org.openide.explorer.ExplorerManager; import static org.openide.explorer.ExplorerUtils.createLookup; import org.openide.nodes.AbstractNode; import org.openide.nodes.Node; import org.openide.util.Lookup; import org.openide.util.NbBundle.Messages; import org.sleuthkit.autopsy.casemodule.Case; import org.sleuthkit.autopsy.casemodule.NoCurrentCaseException; import org.sleuthkit.autopsy.communications.ModifiableProxyLookup; import org.sleuthkit.autopsy.corecomponents.TableFilterNode; import org.sleuthkit.autopsy.coreutils.Logger; import org.sleuthkit.autopsy.datamodel.BlackboardArtifactNode; import org.sleuthkit.autopsy.directorytree.DataResultFilterNode; import org.sleuthkit.datamodel.AbstractContent; import org.sleuthkit.datamodel.BlackboardArtifact; import org.sleuthkit.datamodel.CommunicationsManager; import org.sleuthkit.datamodel.Content; import org.sleuthkit.datamodel.TskCoreException; /** * A Panel that shows the media (thumbnails) for the selected account. */ final class MediaViewer extends JPanel implements RelationshipsViewer, ExplorerManager.Provider, Lookup.Provider { private static final Logger logger = Logger.getLogger(MediaViewer.class.getName()); private final ExplorerManager tableEM = new ExplorerManager(); private final PropertyChangeListener focusPropertyListener; private final ModifiableProxyLookup proxyLookup; @Messages({ "MediaViewer_Name=Media" }) /** * Creates new form ThumbnailViewer */ public MediaViewer() { initComponents(); splitPane.setResizeWeight(0.5); splitPane.setDividerLocation(0.5); proxyLookup = new ModifiableProxyLookup(createLookup(tableEM, getActionMap())); // See org.sleuthkit.autopsy.timeline.TimeLineTopComponent for a detailed // explaination of focusPropertyListener focusPropertyListener = (final PropertyChangeEvent focusEvent) -> { if (focusEvent.getPropertyName().equalsIgnoreCase("focusOwner")) { final Component newFocusOwner = (Component) focusEvent.getNewValue(); if (newFocusOwner == null) { return; } if (isDescendingFrom(newFocusOwner, contentViewer)) { //if the focus owner is within the MessageContentViewer (the attachments table) proxyLookup.setNewLookups(createLookup(((MessageDataContent) contentViewer).getExplorerManager(), getActionMap())); } else if (isDescendingFrom(newFocusOwner, MediaViewer.this)) { //... or if it is within the Results table. proxyLookup.setNewLookups(createLookup(tableEM, getActionMap())); } } }; tableEM.addPropertyChangeListener((PropertyChangeEvent evt) -> { if (evt.getPropertyName().equals(ExplorerManager.PROP_SELECTED_NODES)) { handleNodeSelectionChange(); } }); thumbnailViewer.resetComponent(); } @Override public String getDisplayName() { return Bundle.MediaViewer_Name(); } @Override public JPanel getPanel() { return this; } @Override public void setSelectionInfo(SelectionInfo info) { final Set<Content> relationshipSources; CommunicationsManager communicationManager; Set<BlackboardArtifact> artifactList = new HashSet<>(); try { communicationManager = Case.getCurrentCaseThrows().getSleuthkitCase().getCommunicationsManager(); relationshipSources = communicationManager.getRelationshipSources(info.getAccountDevicesInstances(), info.getCommunicationsFilter()); relationshipSources.stream().filter((content) -> (content instanceof BlackboardArtifact)).forEachOrdered((content) -> { artifactList.add((BlackboardArtifact) content); }); } catch (TskCoreException | NoCurrentCaseException ex) { logger.log(Level.WARNING, "Unable to update selection." , ex); } if(artifactList.size() == 0) { thumbnailViewer.resetComponent(); } thumbnailViewer.setNode(new TableFilterNode(new DataResultFilterNode(new AbstractNode(new AttachmentsChildren(artifactList)), tableEM), true, this.getClass().getName())); } @Override public ExplorerManager getExplorerManager() { return tableEM; } @Override public Lookup getLookup() { return proxyLookup; } @Override public void addNotify() { super.addNotify(); //add listener that maintains correct selection in the Global Actions Context KeyboardFocusManager.getCurrentKeyboardFocusManager() .addPropertyChangeListener("focusOwner", focusPropertyListener); } @Override public void removeNotify() { super.removeNotify(); KeyboardFocusManager.getCurrentKeyboardFocusManager() .removePropertyChangeListener("focusOwner", focusPropertyListener); } /** * Handle the change in thumbnail node selection. */ private void handleNodeSelectionChange() { final Node[] nodes = tableEM.getSelectedNodes(); if (nodes != null && nodes.length == 1) { AbstractContent thumbnail = nodes[0].getLookup().lookup(AbstractContent.class); if (thumbnail != null) { try { Content parentContent = thumbnail.getParent(); if (parentContent != null && parentContent instanceof BlackboardArtifact) { contentViewer.setNode(new BlackboardArtifactNode((BlackboardArtifact) parentContent)); } } catch (TskCoreException ex) { logger.log(Level.WARNING, "Unable to get parent Content from AbstraceContent instance.", ex); //NON-NLS } } } else { contentViewer.setNode(null); } } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { java.awt.GridBagConstraints gridBagConstraints; splitPane = new javax.swing.JSplitPane(); thumbnailViewer = new org.sleuthkit.autopsy.corecomponents.DataResultViewerThumbnail(tableEM); contentViewer = new MessageDataContent(); setLayout(new java.awt.GridBagLayout()); splitPane.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT); thumbnailViewer.setMinimumSize(new java.awt.Dimension(350, 102)); thumbnailViewer.setPreferredSize(new java.awt.Dimension(450, 400)); splitPane.setLeftComponent(thumbnailViewer); contentViewer.setPreferredSize(new java.awt.Dimension(450, 400)); splitPane.setRightComponent(contentViewer); gridBagConstraints = new java.awt.GridBagConstraints(); gridBagConstraints.gridx = 0; gridBagConstraints.gridy = 0; gridBagConstraints.fill = java.awt.GridBagConstraints.BOTH; gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST; gridBagConstraints.weightx = 1.0; gridBagConstraints.weighty = 1.0; add(splitPane, gridBagConstraints); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private org.sleuthkit.autopsy.contentviewers.MessageContentViewer contentViewer; private javax.swing.JSplitPane splitPane; private org.sleuthkit.autopsy.corecomponents.DataResultViewerThumbnail thumbnailViewer; // End of variables declaration//GEN-END:variables }
Added resetComponent call to setSelectionInfo
Core/src/org/sleuthkit/autopsy/communications/relationships/MediaViewer.java
Added resetComponent call to setSelectionInfo
<ide><path>ore/src/org/sleuthkit/autopsy/communications/relationships/MediaViewer.java <ide> logger.log(Level.WARNING, "Unable to update selection." , ex); <ide> } <ide> <del> if(artifactList.size() == 0) { <del> thumbnailViewer.resetComponent(); <del> } <add> thumbnailViewer.resetComponent(); <ide> <ide> thumbnailViewer.setNode(new TableFilterNode(new DataResultFilterNode(new AbstractNode(new AttachmentsChildren(artifactList)), tableEM), true, this.getClass().getName())); <ide> }
Java
apache-2.0
18a9563b35ced1faa64e41e96170c9631171cf26
0
TremoloSecurity/OpenUnison,TremoloSecurity/OpenUnison,TremoloSecurity/OpenUnison,TremoloSecurity/OpenUnison,TremoloSecurity/OpenUnison
/* Copyright 2015 Tremolo Security, 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 com.tremolosecurity.proxy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.zip.GZIPOutputStream; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.logging.log4j.Logger; import org.joda.time.DateTime; import com.google.gson.Gson; import com.tremolosecurity.config.util.ConfigManager; import com.tremolosecurity.config.util.UrlHolder; import com.tremolosecurity.config.xml.ApplicationType; import com.tremolosecurity.config.xml.AuthChainType; import com.tremolosecurity.json.Token; import com.tremolosecurity.openunison.OpenUnisonConstants; import com.tremolosecurity.proxy.auth.AnonAuth; import com.tremolosecurity.proxy.auth.AuthController; import com.tremolosecurity.proxy.auth.AuthInfo; import com.tremolosecurity.proxy.logout.LogoutHandler; import com.tremolosecurity.proxy.logout.LogoutUtil; import com.tremolosecurity.proxy.util.ProxyConstants; import com.tremolosecurity.proxy.util.ProxyTools; public class SessionManagerImpl implements SessionManager { static Logger logger = org.apache.logging.log4j.LogManager.getLogger(SessionManagerImpl.class); private static final String AUTOIDM_KEY_SESSION = "AUTOIDM_KEY_SESSION"; public static final String TREMOLO_SESSION_LAST_ACCESSED = "TREMOLO_SESSION_LAST_ACCESSED"; SecureRandom random; private ConfigManager cfg; private AuthChainType anonChainType; private AnonAuth anonMech; ServletContext ctx; private ConcurrentHashMap<String, TremoloHttpSession> sessions; private SessionTimeoutChecker checker; /* * (non-Javadoc) * * @see com.tremolosecurity.proxy.SessionManager#invalidateSession(com. * tremolosecurity.proxy.TremoloHttpSession) */ @Override public void invalidateSession(TremoloHttpSession tsession) { //we need to run the logout handlers ArrayList<LogoutHandler> handlers = (ArrayList<LogoutHandler>) tsession.getAttribute(LogoutUtil.LOGOUT_HANDLERS); if (handlers != null) { for (LogoutHandler handler : handlers) { try { handler.handleLogout(null, null); } catch (ServletException e) { logger.warn("Could not run logout handler",e); } } } sessions.remove(tsession.getId()); } public SessionManagerImpl(ConfigManager cfg, ServletContext ctx) { sessions = new ConcurrentHashMap<String, TremoloHttpSession>(); this.ctx = ctx; try { this.random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { logger.error("Could not load secure random", e); } this.cfg = cfg; for (String key : this.cfg.getAuthChains().keySet()) { AuthChainType act = this.cfg.getAuthChains().get(key); if (act.getLevel() == 0) { this.anonChainType = act; String mechName = act.getAuthMech().get(0).getName(); this.anonMech = (AnonAuth) cfg.getAuthMech(cfg.getAuthMechs() .get(mechName).getUri()); } } if (this.anonMech == null) { this.anonChainType = new AuthChainType(); this.anonChainType.setFinishOnRequiredSucess(true); this.anonChainType.setLevel(0); this.anonChainType.setName("anon"); this.anonMech = new AnonAuth(); } checker = new SessionTimeoutChecker(this.cfg,this); checker.start(); if (cfg.getCfg().getApplications().getOpenSessionCookieName() == null) { cfg.getCfg().getApplications() .setOpenSessionCookieName("TREMOLO_SESSION"); } } /* * (non-Javadoc) * * @see * com.tremolosecurity.proxy.SessionManager#getSession(com.tremolosecurity * .config.util.UrlHolder, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, javax.servlet.ServletContext) */ @Override public HttpSession getSession(UrlHolder holder, HttpServletRequest request, HttpServletResponse response, ServletContext ctx) throws Exception { // if we are not using a secure session, use generic session if (holder.getApp().getCookieConfig() == null) { return request.getSession(); } String cookieName = holder.getApp().getCookieConfig() .getSessionCookieName(); if (cookieName == null || cookieName.length() == 0) { return request.getSession(); } HttpSession session = locateSession(holder, request, ctx, cookieName, response); if (session instanceof HttpSession) { ((TremoloHttpSession) session).refresh(ctx, this); } return session; } private HttpSession locateSession(UrlHolder holder, HttpServletRequest request, ServletContext ctx, String cookieName, HttpServletResponse resp) throws Exception { Cookie sessionCookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equalsIgnoreCase(cookieName)) { sessionCookie = cookie; break; } } } ConfigManager cfg = (ConfigManager) ctx .getAttribute(ProxyConstants.TREMOLO_CONFIG); ApplicationType app; if (holder != null) { app = holder.getApp(); } else { app = null; String appName = null; if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("autoIdmAppName")) { appName = URLDecoder.decode(cookies[i].getValue(), "UTF-8"); break; } } } if (appName == null) { // TODO create open session if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals(cfg.getCfg().getApplications().getOpenSessionCookieName())) { String sessionID = cookies[i].getValue(); TremoloHttpSession tsession = this.sessions .get(sessionID); // TODO add timeouts if (tsession == null) { return this.createOpenSession(request, resp, ctx); } else { return tsession; } } } } return createOpenSession(request, resp, ctx); } else { app = cfg.getApp(appName); if (app == null) { throw new Exception("No application named '" + appName + "' found"); } } } SecretKey encKey = cfg .getSecretKey(app.getCookieConfig().getKeyAlias()); // TremoloHttpSession tsession = (TremoloHttpSession) // request.getSession().getAttribute(app.getCookieConfig().getSessionCookieName()); if (sessionCookie == null) { // if (tsession != null) tsession.invalidate(); return createSession(app, request, resp, ctx, encKey); } else { HttpSession session = null; try { try { TremoloHttpSession tsession = findSessionFromCookie(sessionCookie, encKey,this); if (tsession == null) { return createSession(app, request, resp, ctx, encKey); } String fromSessionID = (String) tsession .getAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID); if (app.getCookieConfig().getTimeout() > 0) { DateTime lastAccessed = (DateTime) tsession .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); DateTime now = new DateTime(); if (now.minusSeconds(app.getCookieConfig().getTimeout()) .isAfter(lastAccessed)) { tsession.invalidate(); return createSession(app, request, resp, ctx, encKey); } else { tsession.setAttribute( SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED, now); session = tsession; } } else { session = tsession; } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Exception loading session", e); } return createSession(app, request, resp, ctx, encKey); } // this.sessions.put(session.getSessionID(), key); // } } catch (Exception e) { logger.error("Error generating session", e); } if (session == null) { // session.invalidate(); return createSession(app, request, resp, ctx, encKey); } // session.resetAccess(); return session; } } public static TremoloHttpSession findSessionFromCookie(Cookie sessionCookie, SecretKey encKey,SessionManagerImpl sessionMgr) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String tokenHeader = new String( org.bouncycastle.util.encoders.Base64 .decode(sessionCookie.getValue().getBytes( "UTF-8"))); Gson gson = new Gson(); Token token = gson.fromJson(tokenHeader, Token.class); byte[] iv = org.bouncycastle.util.encoders.Base64 .decode(token.getIv()); IvParameterSpec spec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, encKey, spec); byte[] encBytes = org.bouncycastle.util.encoders.Base64 .decode(token.getEncryptedRequest()); String requestToken = new String(cipher.doFinal(encBytes)); TremoloHttpSession tsession = sessionMgr.getSessions().get(requestToken); return tsession; } private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp, ServletContext ctx, SecretKey encKey) throws Exception { byte[] idBytes = new byte[20]; random.nextBytes(idBytes); StringBuffer b = new StringBuffer(); b.append('f').append(Hex.encodeHexString(idBytes)); String id = b.toString(); // HttpSession session = req.getSession(true); TremoloHttpSession tsession = new TremoloHttpSession(id); tsession.setAppName(app.getName()); tsession.refresh(this.ctx, this); tsession.setOpen(false); this.anonMech.createSession(tsession, this.anonChainType); AuthController actl = (AuthController) tsession .getAttribute(ProxyConstants.AUTH_CTL); AuthInfo auInfo = actl.getAuthInfo(); auInfo.setAuthComplete(true); // session.setAttribute(app.getCookieConfig().getSessionCookieName(), // tsession); tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id); tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout()); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, encKey); byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8")); String base64d = new String( org.bouncycastle.util.encoders.Base64.encode(encSessionKey)); Token token = new Token(); token.setEncryptedRequest(base64d); token.setIv(new String(org.bouncycastle.util.encoders.Base64 .encode(cipher.getIV()))); Gson gson = new Gson(); String cookie = gson.toJson(token); byte[] btoken = cookie.getBytes("UTF-8"); String encCookie = new String( org.bouncycastle.util.encoders.Base64.encode(btoken)); Cookie sessionCookie; sessionCookie = new Cookie( app.getCookieConfig().getSessionCookieName(), encCookie); // logger.debug("session size : " + // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length); String domain = ProxyTools.getInstance().getCookieDomain( app.getCookieConfig(), req); if (domain != null) { sessionCookie.setDomain(domain); } sessionCookie.setPath("/"); sessionCookie.setSecure(false); sessionCookie.setMaxAge(-1); sessionCookie.setSecure(app.getCookieConfig().isSecure()); sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly()); resp.addCookie(sessionCookie); // delete the opensession if it exists if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null && ! cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) { Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications() .getOpenSessionCookieName(), id); openSessionCookie.setPath("/"); openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure()); openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly()); openSessionCookie.setMaxAge(0); resp.addCookie(openSessionCookie); } sessions.put(id, tsession); return tsession; } private HttpSession createOpenSession(HttpServletRequest req, HttpServletResponse resp, ServletContext ctx) throws Exception { byte[] idBytes = new byte[20]; random.nextBytes(idBytes); StringBuffer b = new StringBuffer(); b.append('f').append(Hex.encodeHexString(idBytes)); String id = b.toString(); // HttpSession session = req.getSession(true); TremoloHttpSession tsession = new TremoloHttpSession(id); tsession.setOpen(true); tsession.refresh(this.ctx, this); this.anonMech.createSession(tsession, this.anonChainType); AuthController actl = (AuthController) tsession .getAttribute(ProxyConstants.AUTH_CTL); AuthInfo auInfo = actl.getAuthInfo(); auInfo.setAuthComplete(true); // session.setAttribute(app.getCookieConfig().getSessionCookieName(), // tsession); tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id); // TODO add global session timeout // tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout()); // TODO add global open session name Cookie sessionCookie = new Cookie(cfg.getCfg().getApplications() .getOpenSessionCookieName(), id); sessionCookie.setPath("/"); sessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure()); sessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly()); sessionCookie.setMaxAge(-1); // TODO add secure? // sessionCookie.setSecure(app.getCookieConfig().isSecure()); resp.addCookie(sessionCookie); sessions.put(id, tsession); return tsession; } /* * (non-Javadoc) * * @see * com.tremolosecurity.proxy.SessionManager#getSession(java.lang.String, * com.tremolosecurity.config.util.UrlHolder, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, javax.servlet.ServletContext) */ @Override public HttpSession getSession(String sessionCookieName, UrlHolder holder, HttpServletRequest request, HttpServletResponse response, ServletContext ctx) throws Exception { return this.locateSession(holder, request, ctx, sessionCookieName, response); } /* * (non-Javadoc) * * @see * com.tremolosecurity.proxy.SessionManager#writeSession(com.tremolosecurity * .config.util.UrlHolder, com.tremolosecurity.proxy.TremoloHttpSession, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void writeSession(UrlHolder holder, TremoloHttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { /* * Enumeration enumer = session.getAttributeNames(); while * (enumer.hasMoreElements()) { String name = (String) * enumer.nextElement(); String value = * session.getAttribute(name).toString(); logger.debug(name + "='" + * value + "'"); } */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(bos); ObjectOutputStream oos = new ObjectOutputStream(gzip); oos.writeObject(session); oos.flush(); oos.close(); byte[] encSession = new byte[0]; try { Cipher cipher = Cipher.getInstance("AES"); cipher.init( Cipher.ENCRYPT_MODE, holder.getConfig().getSecretKey( holder.getApp().getCookieConfig().getKeyAlias())); encSession = cipher.doFinal(bos.toByteArray()); } catch (Exception e) { e.printStackTrace(); } Cookie sessionCookie; sessionCookie = new Cookie(holder.getApp().getCookieConfig() .getSessionCookieName(), new String( Base64.encodeBase64(encSession))); // logger.debug("session size : " + // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length); String domain = ProxyTools.getInstance().getCookieDomain( holder.getApp().getCookieConfig(), request); if (domain != null) { sessionCookie.setDomain(domain); } sessionCookie.setPath("/"); sessionCookie.setSecure(false); sessionCookie.setMaxAge(-1); response.addCookie(sessionCookie); } /* * (non-Javadoc) * * @see * com.tremolosecurity.proxy.SessionManager#clearSession(com.tremolosecurity * .config.util.UrlHolder, javax.servlet.http.HttpSession, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void clearSession(UrlHolder holder, HttpSession sharedSession, HttpServletRequest request, HttpServletResponse response) { Cookie sessionCookie; sessionCookie = new Cookie(holder.getApp().getCookieConfig() .getSessionCookieName(), "LOGGED_OUT"); String domain = ProxyTools.getInstance().getCookieDomain( holder.getApp().getCookieConfig(), request); if (domain != null) { sessionCookie.setDomain(domain); } sessionCookie.setPath("/"); sessionCookie.setSecure(false); sessionCookie.setMaxAge(0); response.addCookie(sessionCookie); sharedSession.invalidate(); } @Override public void resetSessionChecker(ConfigManager cfg) { this.cfg = cfg; SessionTimeoutChecker checker = new SessionTimeoutChecker(this.cfg,this); checker.start(); } @Override public ConcurrentHashMap<String, TremoloHttpSession> getSessions() { return this.sessions; } @Override public void stopSessionChecker() { this.checker.stopChecker(); } } class SessionTimeoutChecker extends Thread { boolean stillRun; SessionManager sessionMgr; ConfigManager cfg; public SessionTimeoutChecker(ConfigManager cfg,SessionManager sessionManager) { this.sessionMgr = sessionManager; this.cfg = cfg; this.stillRun = true; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { stillRun = false; } }); } public void stopChecker() { this.stillRun = false; this.interrupt(); } @Override public void run() { while (stillRun) { try { ArrayList<String> toremove = new ArrayList<String>(); Set<String> keys = new HashSet<String>(); synchronized (this.sessionMgr.getSessions()) { keys.addAll(this.sessionMgr.getSessions().keySet()); } for (String key : keys) { TremoloHttpSession session = this.sessionMgr.getSessions().get(key); if (session == null) { continue; } ApplicationType app = cfg.getApp(session.getAppName()); if (session.isOpen()) { if (cfg.getCfg().getApplications() .getOpenSessionTimeout() > 0) { DateTime lastAccessed = (DateTime) session .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); if (lastAccessed == null) { lastAccessed = new DateTime(session.getCreationTime()); } DateTime now = new DateTime(); if (now.minusSeconds( cfg.getCfg().getApplications() .getOpenSessionTimeout()).isAfter( lastAccessed)) { session.invalidate(); toremove.add(key); } } } else { if (app == null) { StringBuffer b = new StringBuffer(); b.append("Session ").append(session.getId()) .append(" application ") .append(session.getAppName()) .append(" does not exist, invalidating"); SessionManagerImpl.logger.warn(b.toString()); toremove.add(key); session.invalidate(); } else { if (app.getCookieConfig().getTimeout() > 0) { DateTime lastAccessed = (DateTime) session .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); if (lastAccessed == null) { lastAccessed = new DateTime(session.getCreationTime()); } DateTime now = new DateTime(); if (now.minusSeconds( app.getCookieConfig().getTimeout()) .isAfter(lastAccessed)) { session.invalidate(); toremove.add(key); } } } } } synchronized (this.sessionMgr.getSessions()) { StringBuffer b = new StringBuffer(); b.append("Clearing ").append(toremove.size()).append(" sessions"); SessionManagerImpl.logger.warn(b.toString()); for (String key : toremove) { this.sessionMgr.getSessions().remove(key); } } try { Thread.sleep(60000); } catch (InterruptedException e) { } } catch (Throwable t) { SessionManagerImpl.logger.warn( "Exception while processing expired sessions", t); try { Thread.sleep(60000); } catch (InterruptedException e) { } } } } }
unison/unison-server-core/src/main/java/com/tremolosecurity/proxy/SessionManagerImpl.java
/* Copyright 2015 Tremolo Security, 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 com.tremolosecurity.proxy; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.zip.GZIPOutputStream; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.codec.binary.Base64; import org.apache.commons.codec.binary.Hex; import org.apache.logging.log4j.Logger; import org.joda.time.DateTime; import com.google.gson.Gson; import com.tremolosecurity.config.util.ConfigManager; import com.tremolosecurity.config.util.UrlHolder; import com.tremolosecurity.config.xml.ApplicationType; import com.tremolosecurity.config.xml.AuthChainType; import com.tremolosecurity.json.Token; import com.tremolosecurity.openunison.OpenUnisonConstants; import com.tremolosecurity.proxy.auth.AnonAuth; import com.tremolosecurity.proxy.auth.AuthController; import com.tremolosecurity.proxy.auth.AuthInfo; import com.tremolosecurity.proxy.logout.LogoutHandler; import com.tremolosecurity.proxy.logout.LogoutUtil; import com.tremolosecurity.proxy.util.ProxyConstants; import com.tremolosecurity.proxy.util.ProxyTools; public class SessionManagerImpl implements SessionManager { static Logger logger = org.apache.logging.log4j.LogManager.getLogger(SessionManagerImpl.class); private static final String AUTOIDM_KEY_SESSION = "AUTOIDM_KEY_SESSION"; public static final String TREMOLO_SESSION_LAST_ACCESSED = "TREMOLO_SESSION_LAST_ACCESSED"; SecureRandom random; private ConfigManager cfg; private AuthChainType anonChainType; private AnonAuth anonMech; ServletContext ctx; private ConcurrentHashMap<String, TremoloHttpSession> sessions; private SessionTimeoutChecker checker; /* * (non-Javadoc) * * @see com.tremolosecurity.proxy.SessionManager#invalidateSession(com. * tremolosecurity.proxy.TremoloHttpSession) */ @Override public void invalidateSession(TremoloHttpSession tsession) { //we need to run the logout handlers ArrayList<LogoutHandler> handlers = (ArrayList<LogoutHandler>) tsession.getAttribute(LogoutUtil.LOGOUT_HANDLERS); if (handlers != null) { for (LogoutHandler handler : handlers) { try { handler.handleLogout(null, null); } catch (ServletException e) { logger.warn("Could not run logout handler",e); } } } sessions.remove(tsession.getId()); } public SessionManagerImpl(ConfigManager cfg, ServletContext ctx) { sessions = new ConcurrentHashMap<String, TremoloHttpSession>(); this.ctx = ctx; try { this.random = SecureRandom.getInstance("SHA1PRNG"); } catch (NoSuchAlgorithmException e) { logger.error("Could not load secure random", e); } this.cfg = cfg; for (String key : this.cfg.getAuthChains().keySet()) { AuthChainType act = this.cfg.getAuthChains().get(key); if (act.getLevel() == 0) { this.anonChainType = act; String mechName = act.getAuthMech().get(0).getName(); this.anonMech = (AnonAuth) cfg.getAuthMech(cfg.getAuthMechs() .get(mechName).getUri()); } } if (this.anonMech == null) { this.anonChainType = new AuthChainType(); this.anonChainType.setFinishOnRequiredSucess(true); this.anonChainType.setLevel(0); this.anonChainType.setName("anon"); this.anonMech = new AnonAuth(); } checker = new SessionTimeoutChecker(this.cfg,this); checker.start(); if (cfg.getCfg().getApplications().getOpenSessionCookieName() == null) { cfg.getCfg().getApplications() .setOpenSessionCookieName("TREMOLO_SESSION"); } } /* * (non-Javadoc) * * @see * com.tremolosecurity.proxy.SessionManager#getSession(com.tremolosecurity * .config.util.UrlHolder, javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, javax.servlet.ServletContext) */ @Override public HttpSession getSession(UrlHolder holder, HttpServletRequest request, HttpServletResponse response, ServletContext ctx) throws Exception { // if we are not using a secure session, use generic session if (holder.getApp().getCookieConfig() == null) { return request.getSession(); } String cookieName = holder.getApp().getCookieConfig() .getSessionCookieName(); if (cookieName == null || cookieName.length() == 0) { return request.getSession(); } HttpSession session = locateSession(holder, request, ctx, cookieName, response); if (session instanceof HttpSession) { ((TremoloHttpSession) session).refresh(ctx, this); } return session; } private HttpSession locateSession(UrlHolder holder, HttpServletRequest request, ServletContext ctx, String cookieName, HttpServletResponse resp) throws Exception { Cookie sessionCookie = null; Cookie[] cookies = request.getCookies(); if (cookies != null) { for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; if (cookie.getName().equalsIgnoreCase(cookieName)) { sessionCookie = cookie; break; } } } ConfigManager cfg = (ConfigManager) ctx .getAttribute(ProxyConstants.TREMOLO_CONFIG); ApplicationType app; if (holder != null) { app = holder.getApp(); } else { app = null; String appName = null; if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("autoIdmAppName")) { appName = URLDecoder.decode(cookies[i].getValue(), "UTF-8"); break; } } } if (appName == null) { // TODO create open session if (cookies != null) { for (int i = 0; i < cookies.length; i++) { if (cookies[i].getName().equals("tremoloOpenSession")) { String sessionID = cookies[i].getValue(); TremoloHttpSession tsession = this.sessions .get(sessionID); // TODO add timeouts if (tsession == null) { return this.createOpenSession(request, resp, ctx); } else { return tsession; } } } } return createOpenSession(request, resp, ctx); } else { app = cfg.getApp(appName); if (app == null) { throw new Exception("No application named '" + appName + "' found"); } } } SecretKey encKey = cfg .getSecretKey(app.getCookieConfig().getKeyAlias()); // TremoloHttpSession tsession = (TremoloHttpSession) // request.getSession().getAttribute(app.getCookieConfig().getSessionCookieName()); if (sessionCookie == null) { // if (tsession != null) tsession.invalidate(); return createSession(app, request, resp, ctx, encKey); } else { HttpSession session = null; try { try { TremoloHttpSession tsession = findSessionFromCookie(sessionCookie, encKey,this); if (tsession == null) { return createSession(app, request, resp, ctx, encKey); } String fromSessionID = (String) tsession .getAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID); if (app.getCookieConfig().getTimeout() > 0) { DateTime lastAccessed = (DateTime) tsession .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); DateTime now = new DateTime(); if (now.minusSeconds(app.getCookieConfig().getTimeout()) .isAfter(lastAccessed)) { tsession.invalidate(); return createSession(app, request, resp, ctx, encKey); } else { tsession.setAttribute( SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED, now); session = tsession; } } else { session = tsession; } } catch (Exception e) { if (logger.isDebugEnabled()) { logger.debug("Exception loading session", e); } return createSession(app, request, resp, ctx, encKey); } // this.sessions.put(session.getSessionID(), key); // } } catch (Exception e) { logger.error("Error generating session", e); } if (session == null) { // session.invalidate(); return createSession(app, request, resp, ctx, encKey); } // session.resetAccess(); return session; } } public static TremoloHttpSession findSessionFromCookie(Cookie sessionCookie, SecretKey encKey,SessionManagerImpl sessionMgr) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException { String tokenHeader = new String( org.bouncycastle.util.encoders.Base64 .decode(sessionCookie.getValue().getBytes( "UTF-8"))); Gson gson = new Gson(); Token token = gson.fromJson(tokenHeader, Token.class); byte[] iv = org.bouncycastle.util.encoders.Base64 .decode(token.getIv()); IvParameterSpec spec = new IvParameterSpec(iv); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, encKey, spec); byte[] encBytes = org.bouncycastle.util.encoders.Base64 .decode(token.getEncryptedRequest()); String requestToken = new String(cipher.doFinal(encBytes)); TremoloHttpSession tsession = sessionMgr.getSessions().get(requestToken); return tsession; } private HttpSession createSession(ApplicationType app, HttpServletRequest req, HttpServletResponse resp, ServletContext ctx, SecretKey encKey) throws Exception { byte[] idBytes = new byte[20]; random.nextBytes(idBytes); StringBuffer b = new StringBuffer(); b.append('f').append(Hex.encodeHexString(idBytes)); String id = b.toString(); // HttpSession session = req.getSession(true); TremoloHttpSession tsession = new TremoloHttpSession(id); tsession.setAppName(app.getName()); tsession.refresh(this.ctx, this); tsession.setOpen(false); this.anonMech.createSession(tsession, this.anonChainType); AuthController actl = (AuthController) tsession .getAttribute(ProxyConstants.AUTH_CTL); AuthInfo auInfo = actl.getAuthInfo(); auInfo.setAuthComplete(true); // session.setAttribute(app.getCookieConfig().getSessionCookieName(), // tsession); tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id); tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout()); Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, encKey); byte[] encSessionKey = cipher.doFinal(id.getBytes("UTF-8")); String base64d = new String( org.bouncycastle.util.encoders.Base64.encode(encSessionKey)); Token token = new Token(); token.setEncryptedRequest(base64d); token.setIv(new String(org.bouncycastle.util.encoders.Base64 .encode(cipher.getIV()))); Gson gson = new Gson(); String cookie = gson.toJson(token); byte[] btoken = cookie.getBytes("UTF-8"); String encCookie = new String( org.bouncycastle.util.encoders.Base64.encode(btoken)); Cookie sessionCookie; sessionCookie = new Cookie( app.getCookieConfig().getSessionCookieName(), encCookie); // logger.debug("session size : " + // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length); String domain = ProxyTools.getInstance().getCookieDomain( app.getCookieConfig(), req); if (domain != null) { sessionCookie.setDomain(domain); } sessionCookie.setPath("/"); sessionCookie.setSecure(false); sessionCookie.setMaxAge(-1); sessionCookie.setSecure(app.getCookieConfig().isSecure()); sessionCookie.setHttpOnly(app.getCookieConfig().isHttpOnly() != null && app.getCookieConfig().isHttpOnly()); resp.addCookie(sessionCookie); // delete the opensession if it exists if (cfg.getCfg().getApplications().getOpenSessionCookieName() != null && ! cfg.getCfg().getApplications().getOpenSessionCookieName().isEmpty()) { Cookie openSessionCookie = new Cookie(cfg.getCfg().getApplications() .getOpenSessionCookieName(), id); openSessionCookie.setPath("/"); openSessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure()); openSessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly()); openSessionCookie.setMaxAge(0); resp.addCookie(openSessionCookie); } sessions.put(id, tsession); return tsession; } private HttpSession createOpenSession(HttpServletRequest req, HttpServletResponse resp, ServletContext ctx) throws Exception { byte[] idBytes = new byte[20]; random.nextBytes(idBytes); StringBuffer b = new StringBuffer(); b.append('f').append(Hex.encodeHexString(idBytes)); String id = b.toString(); // HttpSession session = req.getSession(true); TremoloHttpSession tsession = new TremoloHttpSession(id); tsession.setOpen(true); tsession.refresh(this.ctx, this); this.anonMech.createSession(tsession, this.anonChainType); AuthController actl = (AuthController) tsession .getAttribute(ProxyConstants.AUTH_CTL); AuthInfo auInfo = actl.getAuthInfo(); auInfo.setAuthComplete(true); // session.setAttribute(app.getCookieConfig().getSessionCookieName(), // tsession); tsession.setAttribute(OpenUnisonConstants.TREMOLO_SESSION_ID, id); // TODO add global session timeout // tsession.setMaxInactiveInterval(app.getCookieConfig().getTimeout()); // TODO add global open session name Cookie sessionCookie = new Cookie(cfg.getCfg().getApplications() .getOpenSessionCookieName(), id); sessionCookie.setPath("/"); sessionCookie.setSecure(cfg.getCfg().getApplications().isOpenSessionSecure()); sessionCookie.setHttpOnly(cfg.getCfg().getApplications().isOpenSessionHttpOnly()); sessionCookie.setMaxAge(-1); // TODO add secure? // sessionCookie.setSecure(app.getCookieConfig().isSecure()); resp.addCookie(sessionCookie); sessions.put(id, tsession); return tsession; } /* * (non-Javadoc) * * @see * com.tremolosecurity.proxy.SessionManager#getSession(java.lang.String, * com.tremolosecurity.config.util.UrlHolder, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, javax.servlet.ServletContext) */ @Override public HttpSession getSession(String sessionCookieName, UrlHolder holder, HttpServletRequest request, HttpServletResponse response, ServletContext ctx) throws Exception { return this.locateSession(holder, request, ctx, sessionCookieName, response); } /* * (non-Javadoc) * * @see * com.tremolosecurity.proxy.SessionManager#writeSession(com.tremolosecurity * .config.util.UrlHolder, com.tremolosecurity.proxy.TremoloHttpSession, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void writeSession(UrlHolder holder, TremoloHttpSession session, HttpServletRequest request, HttpServletResponse response) throws IOException { /* * Enumeration enumer = session.getAttributeNames(); while * (enumer.hasMoreElements()) { String name = (String) * enumer.nextElement(); String value = * session.getAttribute(name).toString(); logger.debug(name + "='" + * value + "'"); } */ ByteArrayOutputStream bos = new ByteArrayOutputStream(); GZIPOutputStream gzip = new GZIPOutputStream(bos); ObjectOutputStream oos = new ObjectOutputStream(gzip); oos.writeObject(session); oos.flush(); oos.close(); byte[] encSession = new byte[0]; try { Cipher cipher = Cipher.getInstance("AES"); cipher.init( Cipher.ENCRYPT_MODE, holder.getConfig().getSecretKey( holder.getApp().getCookieConfig().getKeyAlias())); encSession = cipher.doFinal(bos.toByteArray()); } catch (Exception e) { e.printStackTrace(); } Cookie sessionCookie; sessionCookie = new Cookie(holder.getApp().getCookieConfig() .getSessionCookieName(), new String( Base64.encodeBase64(encSession))); // logger.debug("session size : " + // org.apache.directory.shared.ldap.util.Base64.encode(encSession).length); String domain = ProxyTools.getInstance().getCookieDomain( holder.getApp().getCookieConfig(), request); if (domain != null) { sessionCookie.setDomain(domain); } sessionCookie.setPath("/"); sessionCookie.setSecure(false); sessionCookie.setMaxAge(-1); response.addCookie(sessionCookie); } /* * (non-Javadoc) * * @see * com.tremolosecurity.proxy.SessionManager#clearSession(com.tremolosecurity * .config.util.UrlHolder, javax.servlet.http.HttpSession, * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ @Override public void clearSession(UrlHolder holder, HttpSession sharedSession, HttpServletRequest request, HttpServletResponse response) { Cookie sessionCookie; sessionCookie = new Cookie(holder.getApp().getCookieConfig() .getSessionCookieName(), "LOGGED_OUT"); String domain = ProxyTools.getInstance().getCookieDomain( holder.getApp().getCookieConfig(), request); if (domain != null) { sessionCookie.setDomain(domain); } sessionCookie.setPath("/"); sessionCookie.setSecure(false); sessionCookie.setMaxAge(0); response.addCookie(sessionCookie); sharedSession.invalidate(); } @Override public void resetSessionChecker(ConfigManager cfg) { this.cfg = cfg; SessionTimeoutChecker checker = new SessionTimeoutChecker(this.cfg,this); checker.start(); } @Override public ConcurrentHashMap<String, TremoloHttpSession> getSessions() { return this.sessions; } @Override public void stopSessionChecker() { this.checker.stopChecker(); } } class SessionTimeoutChecker extends Thread { boolean stillRun; SessionManager sessionMgr; ConfigManager cfg; public SessionTimeoutChecker(ConfigManager cfg,SessionManager sessionManager) { this.sessionMgr = sessionManager; this.cfg = cfg; this.stillRun = true; Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { stillRun = false; } }); } public void stopChecker() { this.stillRun = false; this.interrupt(); } @Override public void run() { while (stillRun) { try { ArrayList<String> toremove = new ArrayList<String>(); Set<String> keys = new HashSet<String>(); synchronized (this.sessionMgr.getSessions()) { keys.addAll(this.sessionMgr.getSessions().keySet()); } for (String key : keys) { TremoloHttpSession session = this.sessionMgr.getSessions().get(key); if (session == null) { continue; } ApplicationType app = cfg.getApp(session.getAppName()); if (session.isOpen()) { if (cfg.getCfg().getApplications() .getOpenSessionTimeout() > 0) { DateTime lastAccessed = (DateTime) session .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); DateTime now = new DateTime(); if (now.minusSeconds( cfg.getCfg().getApplications() .getOpenSessionTimeout()).isAfter( lastAccessed)) { session.invalidate(); toremove.add(key); } } } else { if (app == null) { StringBuffer b = new StringBuffer(); b.append("Session ").append(session.getId()) .append(" application ") .append(session.getAppName()) .append(" does not exist, invalidating"); SessionManagerImpl.logger.warn(b.toString()); toremove.add(key); session.invalidate(); } else { if (app.getCookieConfig().getTimeout() > 0) { DateTime lastAccessed = (DateTime) session .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); DateTime now = new DateTime(); if (now.minusSeconds( app.getCookieConfig().getTimeout()) .isAfter(lastAccessed)) { session.invalidate(); toremove.add(key); } } } } } synchronized (this.sessionMgr.getSessions()) { StringBuffer b = new StringBuffer(); b.append("Clearing ").append(toremove.size()).append(" sessions"); SessionManagerImpl.logger.warn(b.toString()); for (String key : toremove) { this.sessionMgr.getSessions().remove(key); } } try { Thread.sleep(60000); } catch (InterruptedException e) { } } catch (Throwable t) { SessionManagerImpl.logger.warn( "Exception while processing expired sessions", t); try { Thread.sleep(60000); } catch (InterruptedException e) { } } } } }
for #271 added checks for other names
unison/unison-server-core/src/main/java/com/tremolosecurity/proxy/SessionManagerImpl.java
for #271 added checks for other names
<ide><path>nison/unison-server-core/src/main/java/com/tremolosecurity/proxy/SessionManagerImpl.java <ide> // TODO create open session <ide> if (cookies != null) { <ide> for (int i = 0; i < cookies.length; i++) { <del> if (cookies[i].getName().equals("tremoloOpenSession")) { <add> if (cookies[i].getName().equals(cfg.getCfg().getApplications().getOpenSessionCookieName())) { <ide> String sessionID = cookies[i].getValue(); <ide> TremoloHttpSession tsession = this.sessions <ide> .get(sessionID); <ide> .getOpenSessionTimeout() > 0) { <ide> DateTime lastAccessed = (DateTime) session <ide> .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); <add> <add> if (lastAccessed == null) { <add> lastAccessed = new DateTime(session.getCreationTime()); <add> } <add> <ide> DateTime now = new DateTime(); <ide> if (now.minusSeconds( <ide> cfg.getCfg().getApplications() <ide> if (app.getCookieConfig().getTimeout() > 0) { <ide> DateTime lastAccessed = (DateTime) session <ide> .getAttribute(SessionManagerImpl.TREMOLO_SESSION_LAST_ACCESSED); <add> <add> if (lastAccessed == null) { <add> lastAccessed = new DateTime(session.getCreationTime()); <add> } <add> <ide> DateTime now = new DateTime(); <ide> if (now.minusSeconds( <ide> app.getCookieConfig().getTimeout())
Java
epl-1.0
c312471ad197be322b778b0ddef11237ea6e53bc
0
qgears/opensource-utils,qgears/opensource-utils,qgears/opensource-utils,qgears/opensource-utils,qgears/opensource-utils
package hu.qgears.opengl.commons; import hu.qgears.commons.IDisposeable; import hu.qgears.commons.mem.DefaultJavaNativeMemory; import hu.qgears.images.ENativeImageAlphaStorageFormat; import hu.qgears.images.ENativeImageComponentOrder; import hu.qgears.images.NativeImage; import hu.qgears.images.SizeInt; import hu.qgears.images.text.RGBAColor; import hu.qgears.opengl.commons.context.EBlendFunc; import hu.qgears.opengl.commons.context.RGlContext; import java.nio.ByteBuffer; import java.nio.IntBuffer; import org.apache.log4j.Logger; import org.lwjgl.opengl.APPLEClientStorage; import org.lwjgl.opengl.ContextCapabilities; import org.lwjgl.opengl.EXTFramebufferObject; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; /** * An OpenGL texture that can be rendered on OpenGL context. * * Can contain pixel data of ENativeImageComponentOrder types. * The image can be rendered as a sprite. * * All methods must be called on OpenGL context thread. * * @author rizsi * */ public class Texture implements IDisposeable { private static final Logger LOG = Logger.getLogger(Texture.class); private boolean samplingNear; private int textureHandle; private EBlendFunc blendFunc=EBlendFunc.off; private boolean disposed = false; private int width, height; private NativeImage sourceImage; private EMipMapType sourceMipmapType; private ETextureWrapType sourceTextureWrapType; /** * Use for debug purpose only: number of allocated texture objects. */ private static int numberOfTextures=0; public EBlendFunc getBlendFunc() { return blendFunc; } public void setBlendFunc(EBlendFunc blendFunc) { this.blendFunc = blendFunc; } public int getTextureHandle() { return textureHandle; } public int getWidth() { return width; } public int getHeight() { return height; } public SizeInt getSize() { return new SizeInt(width, height); } public NativeImage getSourceImage() { return sourceImage; } public EMipMapType getSourceMipmapType() { return sourceMipmapType; } public ETextureWrapType getSourceTextureWrapType() { return sourceTextureWrapType; } private Texture(int textureHandle, int w, int h, int format, int border) { super(); this.textureHandle = textureHandle; this.width = w; this.height = h; this.formatInt = format; this.border = border; } public static int defaultAligment = 1; /** * Create texture object and upload the image to its content. * * @param image * @return */ public static Texture create(NativeImage image) { return create(image, EMipMapType.none); } public static Texture create(NativeImage rdtc, EMipMapType mtype) { return create(rdtc, mtype, ETextureWrapType.mirroredRepeat, false); } public static Texture create(NativeImage rdtc, EMipMapType mtype, ETextureWrapType wrapType, boolean appleClientStorage) { int maxSize = UtilGl.getMaxTextureSize(); int w = rdtc.getWidth(); int h = rdtc.getHeight(); if (w > maxSize || h > maxSize) { return null; } int handle=allocateTexture(); if (handle > 0) { Texture ret=new Texture(handle, w, h, GL11.GL_RGBA8, 0); ret.replaceContent(rdtc, mtype, wrapType, appleClientStorage); return ret; } return null; } public static Texture create(SizeInt size) { return create(size.getWidth(), size.getHeight()); } public static Texture create(int w, int h) { ByteBuffer pixels = UtilGl.allocBytes(w * h * 4); NativeImage image=new NativeImage( new DefaultJavaNativeMemory( pixels), new SizeInt(w, h), ENativeImageComponentOrder.RGBA, 4); int handle=makeTexture(image); if (handle > 0) { return new Texture(handle, w, h, GL11.GL_RGBA8, 0); } return null; } @Override public void dispose() { if (!disposed) { IntBuffer textureHandle=UtilGl.wrapTemp(this.textureHandle); textureHandle.flip(); GL11.glDeleteTextures(textureHandle); numberOfTextures--; disposed = true; } else { throw new RuntimeException("Already disposed!"); } } private static int makeTexture(NativeImage image) { ByteBuffer pixels = image.getBuffer().getJavaAccessor(); int w = image.getWidth(); int h = image.getHeight(); ENativeImageComponentOrder componentOrder = image.getComponentOrder(); // get a new empty texture int textureHandle = allocateTexture(); // preserve currently bound texture, so glBindTexture() below won't // affect anything) GL11.glPushAttrib(GL11.GL_TEXTURE_BIT); // 'select' the new texture by it's handle GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); // set texture parameters GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); int openGLtype = getOpenGLType(componentOrder); GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, // level of detail GL11.GL_RGBA8, // internal format for texture is RGB with // Alpha // GL13.GL_COMPRESSED_RGBA, // internal format for texture // is compressed RGB with Alpha w, h, // size of texture image 0, // no border openGLtype, // incoming pixel format: 4 bytes in RGBA // order GL11.GL_UNSIGNED_BYTE, // incoming pixel data type: unsigned // bytes pixels); // incoming pixels // restore previous texture settings GL11.glPopAttrib(); return textureHandle; } private static int getOpenGLType(ENativeImageComponentOrder componentOrder) { switch (componentOrder) { case RGB: return GL11.GL_RGB; case RGBA: return GL11.GL_RGBA; default: return GL11.GL_RGB; } } /** * Implement finalizer to detect textures not disposed. * In case a texture is finalized without beind disposed an error log * is written to stderr. * * The texture can not be disposed in the finalizer method because * the OpenGL resource must be freed on the OpenGL thread. * Calling dispose here would raise a threading exception in * OpenGL. */ @Override protected void finalize() throws Throwable { if(!disposed) { LOG.error("Texture not disposed before garbage collected!"); } super.finalize(); } /** * Allocate a texture (glGenTextures) and return the handle to it. */ private static int allocateTexture() { numberOfTextures++; return GL11.glGenTextures(); } /** * Draw the texture in ortho mode (2D) over the entire viewport area. * Converts the image to a texture and maps onto a viewport-sized quad. * Depth test is turned off, lighting is off, color is set to white. Alpha * blending is on, so transparent areas will be respected. * <P> * NOTE: By default the viewport is the same size as the window so this * function will draw the image over the entire window. If you setViewport() * to a custom size the image will be drawn into the custom viewport area. * To insure that the image is drawn truly full screen, call resetViewport() * before drawImageFullScreen(). * <P> * * @see loadImage(String) * @see setViewport(int,int,int,int) * @see resetViewport() */ public void drawTextureOnRectangle(TargetRectangle rectangle) { drawTextureOnRectangle(rectangle, true); } private Vector4f color=new Vector4f(1,1,1,1); public Vector4f getColor() { return color; } public void setColor(Vector4f color) { this.color = color; } /** * @since 3.0 */ public void setColor(RGBAColor color) { float[] c = color.toFloatVector(); this.color = new Vector4f(c[0],c[1],c[2],c[3]); } /** * Render the ractangle using its self settings of color and blendfunc. * @param rglContext * @param targetRectangle * @param sourceRectangle */ public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle targetRectangle, TargetRectangle sourceRectangle) { float maxU = sourceRectangle.getBottomRight().getX(); float maxV = sourceRectangle.getTopLeft().getY(); float minU = sourceRectangle.getTopLeft().getX(); float minV = sourceRectangle.getBottomRight().getY(); GL11.glEnable(GL11.GL_TEXTURE_2D); UtilGl.applyBlendFunc(blendFunc); UtilGl.setColor(color); // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV); } /** * Render the ractangle using its self settings of color and blendfunc. * @param rglContext * @param targetRectangle * @param sourceRectangle */ public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle2d targetRectangle, TargetRectangle2d sourceRectangle) { float maxU = sourceRectangle.right; float maxV = sourceRectangle.y; float minU = sourceRectangle.x; float minV = sourceRectangle.bottom; // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); UtilGl.setColor(color); // activate the image texture bindThisTexture(); if(samplingNear) { setNearestSampling(samplingNear); } // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV); if(samplingNear) { setNearestSampling(false); } rglContext.pop(); } private void setNearestSampling(boolean samplingNear) { if(samplingNear) { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); }else { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); } } /** * Render the texture on the GL context * * @param targetRectangle * the target rectangle to render the image in * @param sourceRectangle * the part of the image to render on the target rectangle * @param blendFunc * the blend function to use with alpha blending */ public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle targetRectangle, TargetRectangle sourceRectangle, EBlendFunc blendFunc) { float maxU = sourceRectangle.getBottomRight().getX(); float maxV = sourceRectangle.getTopLeft().getY(); float minU = sourceRectangle.getTopLeft().getX(); float minV = sourceRectangle.getBottomRight().getY(); // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); GL11.glColor4f(1, 1, 1, 1); // no color // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV); rglContext.pop(); } public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle2d targetRectangle, TargetRectangle2d sourceRectangle, EBlendFunc blendFunc) { float maxU = sourceRectangle.right; float maxV = sourceRectangle.y; float minU = sourceRectangle.x; float minV = sourceRectangle.bottom; // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); GL11.glColor4f(1, 1, 1, 1); // no color // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV); rglContext.pop(); } /** * Disable all texture selection - select texture id 0 instead of real textures before drawing. * Use only for performance measurement purpose. */ public static boolean disableAllTextures; private void bindThisTexture() { if(disableAllTextures) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); }else { GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); } } /** * Render the texture on the GL context * * @param targetRectangle * the target rectangle to render the image in * @param sourceRectangle * the part of the image to render on the target rectangle * @param blendFunc * the blend function to use with alpha blending * @param colors colors of the points: topLeft, topRight, bottomLeft, bottomRight */ public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle targetRectangle, TargetRectangle sourceRectangle, EBlendFunc blendFunc, Vector4f[] colors) { float maxU = sourceRectangle.getBottomRight().getX(); float maxV = sourceRectangle.getTopLeft().getY(); float minU = sourceRectangle.getTopLeft().getX(); float minV = sourceRectangle.getBottomRight().getY(); // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV, colors); rglContext.pop(); } public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle2d targetRectangle, TargetRectangle2d sourceRectangle, EBlendFunc blendFunc, Vector4f[] colors) { float maxU = sourceRectangle.right; float maxV = sourceRectangle.y; float minU = sourceRectangle.x; float minV = sourceRectangle.bottom; // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV, colors); rglContext.pop(); } public void drawTextureOnRectangle(TargetRectangle rectangle, boolean blend) { drawTextureOnRectangle(rectangle, blend, new Vector4f(1,1,1,1)); } public void drawTextureOnRectangle(TargetRectangle rectangle, boolean blend, Vector4f color) { float maxU = 1.0f; float maxV = 0.0f; float minU = 0.0f; float minV = 1.0f; GL11.glEnable(GL11.GL_TEXTURE_2D); // be sure textures are on UtilGl.setColor(color); GL11.glDisable(GL11.GL_LIGHTING); // no lighting if (blend) { GL11.glEnable(GL11.GL_BLEND); // enable transparency GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } else { GL11.glDisable(GL11.GL_BLEND); // disable transparency } // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(rectangle, maxU, maxV, minU, minV); // return to previous settings } /** * Renders the texture onto a specified surface ( {@link ITessellatedSurface} ). * * @param blend * @param color * @param maxU * @param maxV * @param minU * @param minV * @param surface */ public void drawTextureOnSurface(boolean blend, Vector4f color,float maxU, float maxV , float minU , float minV ,ITessellatedSurface surface) { GL11.glEnable(GL11.GL_TEXTURE_2D); // be sure textures are on UtilGl.setColor(color); GL11.glDisable(GL11.GL_LIGHTING); // no lighting //GL11.glDisable(GL11.GL_DEPTH_TEST); // no depth test if (blend) { GL11.glEnable(GL11.GL_BLEND); // enable transparency GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } else { GL11.glDisable(GL11.GL_BLEND); // disable transparency } // activate the image texture bindThisTexture(); int nrOfStepU = surface.getTesselU(); int nrOfStepV = surface.getTesselV(); GL11.glBegin(GL11.GL_QUADS); for (int i = 0;i < nrOfStepU;i++ ){ float u0 = (float)i / (float) nrOfStepU; float u1 = (float)(i+1) / (float) nrOfStepU; for (int j =0; j <nrOfStepV ; j++){ float v0 = (float)j / (float) nrOfStepV; float v1 = (float)(j+1) / (float) nrOfStepV; Vector3f p = surface.getPointAt (u0,v0); GL11.glTexCoord2f(u0, v0); GL11.glVertex3f(p.x,p.y,p.z ); p = surface.getPointAt (u0,v1); GL11.glTexCoord2f(u0, v1); GL11.glVertex3f(p.x,p.y,p.z ); GL11.glTexCoord2f(u1, v1); p = surface.getPointAt (u1,v1); GL11.glVertex3f(p.x,p.y,p.z ); GL11.glTexCoord2f(u1, v0); p = surface.getPointAt (u1,v0); GL11.glVertex3f(p.x,p.y,p.z ); } } GL11.glEnd(); } private void drawTextureOnRectangle(TargetRectangle rectangle, float maxU, float maxV, float minU, float minV, Vector4f[] colors) { GL11.glBegin(GL11.GL_QUADS); { UtilGl.setColor(colors[2]); GL11.glTexCoord2f(minU, minV); UtilGl.loadVertex(rectangle.getBottomLeft()); UtilGl.setColor(colors[3]); GL11.glTexCoord2f(maxU, minV); UtilGl.loadVertex(rectangle.getBottomRight()); UtilGl.setColor(colors[1]); GL11.glTexCoord2f(maxU, maxV); UtilGl.loadVertex(rectangle.getTopRight()); UtilGl.setColor(colors[0]); GL11.glTexCoord2f(minU, maxV); UtilGl.loadVertex(rectangle.getTopLeft()); } GL11.glEnd(); } private void drawTextureOnRectangle(TargetRectangle2d rectangle, float maxU, float maxV, float minU, float minV, Vector4f[] colors) { GL11.glBegin(GL11.GL_QUADS); { UtilGl.setColor(colors[2]); GL11.glTexCoord2f(minU, minV); GL11.glVertex2f(rectangle.x, rectangle.bottom); UtilGl.setColor(colors[3]); GL11.glTexCoord2f(maxU, minV); GL11.glVertex2f(rectangle.right, rectangle.bottom); UtilGl.setColor(colors[1]); GL11.glTexCoord2f(maxU, maxV); GL11.glVertex2f(rectangle.right, rectangle.y); UtilGl.setColor(colors[0]); GL11.glTexCoord2f(minU, maxV); GL11.glVertex2f(rectangle.x, rectangle.y); } GL11.glEnd(); } /** * This method does not bind the texture! * @param rectangle * @param maxU * @param maxV * @param minU * @param minV */ private void drawTextureOnRectangle(TargetRectangle rectangle, float maxU, float maxV, float minU, float minV) { GL11.glBegin(GL11.GL_QUADS); { GL11.glTexCoord2f(minU, minV); UtilGl.loadVertex(rectangle.getBottomLeft()); GL11.glTexCoord2f(maxU, minV); UtilGl.loadVertex(rectangle.getBottomRight()); GL11.glTexCoord2f(maxU, maxV); UtilGl.loadVertex(rectangle.getTopRight()); GL11.glTexCoord2f(minU, maxV); UtilGl.loadVertex(rectangle.getTopLeft()); } GL11.glEnd(); } private void drawTextureOnRectangle(TargetRectangle2d rectangle, float maxU, float maxV, float minU, float minV) { GL11.glBegin(GL11.GL_QUADS); { GL11.glTexCoord2f(minU, minV); GL11.glVertex2f(rectangle.x, rectangle.bottom); GL11.glTexCoord2f(maxU, minV); GL11.glVertex2f(rectangle.right, rectangle.bottom); GL11.glTexCoord2f(maxU, maxV); GL11.glVertex2f(rectangle.right, rectangle.y); GL11.glTexCoord2f(minU, maxV); GL11.glVertex2f(rectangle.x, rectangle.y); } GL11.glEnd(); } public void selectTecture() { // tweak settings GL11.glEnable(GL11.GL_TEXTURE_2D); // be sure textures are on // activate the image texture GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); } public void deSelectTecture() { // tweak settings GL11.glDisable(GL11.GL_TEXTURE_2D); // be sure textures are on } private int formatInt; private int border; public int getFormatInt() { return formatInt; } public int hasBorder() { return border; } public void replaceContent(NativeImage newimage) { replaceContent(newimage, EMipMapType.none, ETextureWrapType.mirroredRepeat, false); } public void replaceContent(NativeImage newimage, EMipMapType mtype, ETextureWrapType wrapType, boolean appleClientStorage) { this.sourceImage=newimage; this.sourceMipmapType=mtype; this.sourceTextureWrapType=wrapType; if(EMipMapType.standard.equals(mtype)) { ContextCapabilities cc=GLContext.getCapabilities(); if(!cc.OpenGL30&&!cc.GL_EXT_framebuffer_object) { mtype=EMipMapType.none; } } this.width = newimage.getWidth(); this.height = newimage.getHeight(); GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); switch (wrapType) { case clamp: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP); break; case clampYrepeatX: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP); break; case clampXrepeatY: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); break; case repeat: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); break; case mirroredRepeat: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL14.GL_MIRRORED_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL14.GL_MIRRORED_REPEAT); break; default: break; } switch (mtype) { case none: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); break; case standard: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); break; default: throw new RuntimeException("mipmapping type is not implemented: "+mtype); } int alignment=newimage.getAlignment(); GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, alignment); int pixel_format; int dataformat; pixel_format=componentOrderToOGL(newimage.getComponentOrder()); int internal_format=componentOrderTOIntarnalFormat(newimage.getComponentOrder()); boolean undoClientStorage=false; if(appleClientStorage) { ContextCapabilities cc=GLContext.getCapabilities(); if(cc.GL_APPLE_client_storage) { GL11.glPixelStorei(APPLEClientStorage.GL_UNPACK_CLIENT_STORAGE_APPLE, GL11.GL_TRUE); undoClientStorage=true; } } dataformat = GL11.GL_UNSIGNED_BYTE; GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, internal_format, width, height, 0, pixel_format, dataformat, newimage.getBuffer().getJavaAccessor()); switch (mtype) { case standard: // Using GL_GENERATE_MIPMAP instead causes my NVidia to process about 100% // CPU! Seems to use CPU to generate mipmap levels if(GLContext.getCapabilities().OpenGL30) { GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); }else { EXTFramebufferObject.glGenerateMipmapEXT(GL11.GL_TEXTURE_2D); } break; case none: default: //nothing to do break; } // Reset the default behaviour GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); if(undoClientStorage) { GL11.glPixelStorei(APPLEClientStorage.GL_UNPACK_CLIENT_STORAGE_APPLE, GL11.GL_FALSE); } } public static int componentOrderToOGL(ENativeImageComponentOrder co) { switch (co) { case RGB: return GL11.GL_RGB; case RGBA: return GL11.GL_RGBA; case MONO: return GL11.GL_LUMINANCE; case ALPHA: return GL11.GL_ALPHA; case BGR: return GL12.GL_BGR; case BGRA: return GL12.GL_BGRA; case ARGB: return GL12.GL_BGRA; default: throw new RuntimeException( "pixel format is unknown to opengl module: " + co); } } private int componentOrderTOIntarnalFormat( ENativeImageComponentOrder componentOrder) { switch (componentOrder) { case ARGB: case BGRA: case RGBA: return GL11.GL_RGBA8; case BGR: case RGB: return GL11.GL_RGB8; case ALPHA: return GL11.GL_ALPHA8; case MONO: return GL11.GL_LUMINANCE8; default: throw new RuntimeException( "pixel format is unknown to opengl module: " + componentOrder); } } /** * Generate mip-map for an existing texture. It is useful when the texture is rendered shrinked. */ public void generateMipMap() { ContextCapabilities cc=GLContext.getCapabilities(); if(cc.OpenGL30) { selectTecture(); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); deSelectTecture(); }else if(cc.GL_EXT_framebuffer_object) { selectTecture(); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); EXTFramebufferObject.glGenerateMipmapEXT(GL11.GL_TEXTURE_2D); deSelectTecture(); } } @Override public boolean isDisposed() { return disposed; } public void applyBlendFunc(ENativeImageAlphaStorageFormat alphaFormat) { if(ENativeImageAlphaStorageFormat.premultiplied.equals(alphaFormat)) { setBlendFunc(EBlendFunc.ALPHA_PREMULTIPLIED); }else { setBlendFunc(EBlendFunc.SRC_ALPHA__ONE_MINUS_SRC_ALPHA); } } public void setSamplingNear(boolean samplingNear) { this.samplingNear=samplingNear; } /** * Returns the number of allocated texture objects. * Use for debug purpose only! * @return the number of allocated texture objects. */ public static int getNumberOfTextures() { return numberOfTextures; } }
commons/hu.qgears.opengl.commons/src/hu/qgears/opengl/commons/Texture.java
package hu.qgears.opengl.commons; import hu.qgears.commons.IDisposeable; import hu.qgears.commons.mem.DefaultJavaNativeMemory; import hu.qgears.images.ENativeImageAlphaStorageFormat; import hu.qgears.images.ENativeImageComponentOrder; import hu.qgears.images.NativeImage; import hu.qgears.images.SizeInt; import hu.qgears.images.text.RGBAColor; import hu.qgears.opengl.commons.context.EBlendFunc; import hu.qgears.opengl.commons.context.RGlContext; import java.nio.ByteBuffer; import java.nio.IntBuffer; import org.apache.log4j.Logger; import org.lwjgl.opengl.APPLEClientStorage; import org.lwjgl.opengl.ContextCapabilities; import org.lwjgl.opengl.EXTFramebufferObject; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; import org.lwjgl.opengl.GL14; import org.lwjgl.opengl.GL30; import org.lwjgl.opengl.GLContext; import org.lwjgl.util.vector.Vector3f; import org.lwjgl.util.vector.Vector4f; /** * An OpenGL texture that can be rendered on OpenGL context. * * Can contain pixel data of ENativeImageComponentOrder types. * The image can be rendered as a sprite. * * All methods must be called on OpenGL context thread. * * @author rizsi * */ public class Texture implements IDisposeable { private static final Logger LOG = Logger.getLogger(Texture.class); private boolean samplingNear; private int textureHandle; private EBlendFunc blendFunc=EBlendFunc.off; private boolean disposed = false; private int width, height; public NativeImage sourceImage; public EMipMapType sourceMipmapType; public ETextureWrapType sourceTextureWrapType; /** * Use for debug purpose only: number of allocated texture objects. */ public static int numberOfTextures=0; public EBlendFunc getBlendFunc() { return blendFunc; } public void setBlendFunc(EBlendFunc blendFunc) { this.blendFunc = blendFunc; } public int getTextureHandle() { return textureHandle; } public int getWidth() { return width; } public int getHeight() { return height; } public SizeInt getSize() { return new SizeInt(width, height); } private Texture(int textureHandle, int w, int h, int format, int border) { super(); this.textureHandle = textureHandle; this.width = w; this.height = h; this.formatInt = format; this.border = border; } public static int defaultAligment = 1; /** * Create texture object and upload the image to its content. * * @param image * @return */ public static Texture create(NativeImage image) { return create(image, EMipMapType.none); } public static Texture create(NativeImage rdtc, EMipMapType mtype) { return create(rdtc, mtype, ETextureWrapType.mirroredRepeat, false); } public static Texture create(NativeImage rdtc, EMipMapType mtype, ETextureWrapType wrapType, boolean appleClientStorage) { int maxSize = UtilGl.getMaxTextureSize(); int w = rdtc.getWidth(); int h = rdtc.getHeight(); if (w > maxSize || h > maxSize) { return null; } int handle=allocateTexture(); if (handle > 0) { Texture ret=new Texture(handle, w, h, GL11.GL_RGBA8, 0); ret.replaceContent(rdtc, mtype, wrapType, appleClientStorage); return ret; } return null; } public static Texture create(SizeInt size) { return create(size.getWidth(), size.getHeight()); } public static Texture create(int w, int h) { ByteBuffer pixels = UtilGl.allocBytes(w * h * 4); NativeImage image=new NativeImage( new DefaultJavaNativeMemory( pixels), new SizeInt(w, h), ENativeImageComponentOrder.RGBA, 4); int handle=makeTexture(image); if (handle > 0) { return new Texture(handle, w, h, GL11.GL_RGBA8, 0); } return null; } @Override public void dispose() { if (!disposed) { IntBuffer textureHandle=UtilGl.wrapTemp(this.textureHandle); textureHandle.flip(); GL11.glDeleteTextures(textureHandle); numberOfTextures--; disposed = true; } else { throw new RuntimeException("Already disposed!"); } } private static int makeTexture(NativeImage image) { ByteBuffer pixels = image.getBuffer().getJavaAccessor(); int w = image.getWidth(); int h = image.getHeight(); ENativeImageComponentOrder componentOrder = image.getComponentOrder(); // get a new empty texture int textureHandle = allocateTexture(); // preserve currently bound texture, so glBindTexture() below won't // affect anything) GL11.glPushAttrib(GL11.GL_TEXTURE_BIT); // 'select' the new texture by it's handle GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); // set texture parameters GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); int openGLtype = getOpenGLType(componentOrder); GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, // level of detail GL11.GL_RGBA8, // internal format for texture is RGB with // Alpha // GL13.GL_COMPRESSED_RGBA, // internal format for texture // is compressed RGB with Alpha w, h, // size of texture image 0, // no border openGLtype, // incoming pixel format: 4 bytes in RGBA // order GL11.GL_UNSIGNED_BYTE, // incoming pixel data type: unsigned // bytes pixels); // incoming pixels // restore previous texture settings GL11.glPopAttrib(); return textureHandle; } private static int getOpenGLType(ENativeImageComponentOrder componentOrder) { switch (componentOrder) { case RGB: return GL11.GL_RGB; case RGBA: return GL11.GL_RGBA; default: return GL11.GL_RGB; } } /** * Implement finalizer to detect textures not disposed. * In case a texture is finalized without beind disposed an error log * is written to stderr. * * The texture can not be disposed in the finalizer method because * the OpenGL resource must be freed on the OpenGL thread. * Calling dispose here would raise a threading exception in * OpenGL. */ @Override protected void finalize() throws Throwable { if(!disposed) { LOG.error("Texture not disposed before garbage collected!"); } super.finalize(); } /** * Allocate a texture (glGenTextures) and return the handle to it. */ private static int allocateTexture() { numberOfTextures++; return GL11.glGenTextures(); } /** * Draw the texture in ortho mode (2D) over the entire viewport area. * Converts the image to a texture and maps onto a viewport-sized quad. * Depth test is turned off, lighting is off, color is set to white. Alpha * blending is on, so transparent areas will be respected. * <P> * NOTE: By default the viewport is the same size as the window so this * function will draw the image over the entire window. If you setViewport() * to a custom size the image will be drawn into the custom viewport area. * To insure that the image is drawn truly full screen, call resetViewport() * before drawImageFullScreen(). * <P> * * @see loadImage(String) * @see setViewport(int,int,int,int) * @see resetViewport() */ public void drawTextureOnRectangle(TargetRectangle rectangle) { drawTextureOnRectangle(rectangle, true); } private Vector4f color=new Vector4f(1,1,1,1); public Vector4f getColor() { return color; } public void setColor(Vector4f color) { this.color = color; } /** * @since 3.0 */ public void setColor(RGBAColor color) { float[] c = color.toFloatVector(); this.color = new Vector4f(c[0],c[1],c[2],c[3]); } /** * Render the ractangle using its self settings of color and blendfunc. * @param rglContext * @param targetRectangle * @param sourceRectangle */ public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle targetRectangle, TargetRectangle sourceRectangle) { float maxU = sourceRectangle.getBottomRight().getX(); float maxV = sourceRectangle.getTopLeft().getY(); float minU = sourceRectangle.getTopLeft().getX(); float minV = sourceRectangle.getBottomRight().getY(); GL11.glEnable(GL11.GL_TEXTURE_2D); UtilGl.applyBlendFunc(blendFunc); UtilGl.setColor(color); // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV); } /** * Render the ractangle using its self settings of color and blendfunc. * @param rglContext * @param targetRectangle * @param sourceRectangle */ public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle2d targetRectangle, TargetRectangle2d sourceRectangle) { float maxU = sourceRectangle.right; float maxV = sourceRectangle.y; float minU = sourceRectangle.x; float minV = sourceRectangle.bottom; // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); UtilGl.setColor(color); // activate the image texture bindThisTexture(); if(samplingNear) { setNearestSampling(samplingNear); } // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV); if(samplingNear) { setNearestSampling(false); } rglContext.pop(); } private void setNearestSampling(boolean samplingNear) { if(samplingNear) { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_NEAREST); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_NEAREST); }else { GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); } } /** * Render the texture on the GL context * * @param targetRectangle * the target rectangle to render the image in * @param sourceRectangle * the part of the image to render on the target rectangle * @param blendFunc * the blend function to use with alpha blending */ public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle targetRectangle, TargetRectangle sourceRectangle, EBlendFunc blendFunc) { float maxU = sourceRectangle.getBottomRight().getX(); float maxV = sourceRectangle.getTopLeft().getY(); float minU = sourceRectangle.getTopLeft().getX(); float minV = sourceRectangle.getBottomRight().getY(); // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); GL11.glColor4f(1, 1, 1, 1); // no color // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV); rglContext.pop(); } public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle2d targetRectangle, TargetRectangle2d sourceRectangle, EBlendFunc blendFunc) { float maxU = sourceRectangle.right; float maxV = sourceRectangle.y; float minU = sourceRectangle.x; float minV = sourceRectangle.bottom; // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); GL11.glColor4f(1, 1, 1, 1); // no color // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV); rglContext.pop(); } /** * Disable all texture selection - select texture id 0 instead of real textures before drawing. * Use only for performance measurement purpose. */ public static boolean disableAllTextures; private void bindThisTexture() { if(disableAllTextures) { GL11.glBindTexture(GL11.GL_TEXTURE_2D, 0); }else { GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); } } /** * Render the texture on the GL context * * @param targetRectangle * the target rectangle to render the image in * @param sourceRectangle * the part of the image to render on the target rectangle * @param blendFunc * the blend function to use with alpha blending * @param colors colors of the points: topLeft, topRight, bottomLeft, bottomRight */ public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle targetRectangle, TargetRectangle sourceRectangle, EBlendFunc blendFunc, Vector4f[] colors) { float maxU = sourceRectangle.getBottomRight().getX(); float maxV = sourceRectangle.getTopLeft().getY(); float minU = sourceRectangle.getTopLeft().getX(); float minV = sourceRectangle.getBottomRight().getY(); // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV, colors); rglContext.pop(); } public void drawTextureOnRectangle(RGlContext rglContext, TargetRectangle2d targetRectangle, TargetRectangle2d sourceRectangle, EBlendFunc blendFunc, Vector4f[] colors) { float maxU = sourceRectangle.right; float maxV = sourceRectangle.y; float minU = sourceRectangle.x; float minV = sourceRectangle.bottom; // preserve settings rglContext.push(); // tweak settings rglContext.setTexture2d(true); rglContext.setLightEnabled(false); rglContext.setDepthTest(false); rglContext.setBlendFunc(blendFunc); rglContext.apply(); // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(targetRectangle, maxU, maxV, minU, minV, colors); rglContext.pop(); } public void drawTextureOnRectangle(TargetRectangle rectangle, boolean blend) { drawTextureOnRectangle(rectangle, blend, new Vector4f(1,1,1,1)); } public void drawTextureOnRectangle(TargetRectangle rectangle, boolean blend, Vector4f color) { float maxU = 1.0f; float maxV = 0.0f; float minU = 0.0f; float minV = 1.0f; GL11.glEnable(GL11.GL_TEXTURE_2D); // be sure textures are on UtilGl.setColor(color); GL11.glDisable(GL11.GL_LIGHTING); // no lighting if (blend) { GL11.glEnable(GL11.GL_BLEND); // enable transparency GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } else { GL11.glDisable(GL11.GL_BLEND); // disable transparency } // activate the image texture bindThisTexture(); // draw a textured quad drawTextureOnRectangle(rectangle, maxU, maxV, minU, minV); // return to previous settings } /** * Renders the texture onto a specified surface ( {@link ITessellatedSurface} ). * * @param blend * @param color * @param maxU * @param maxV * @param minU * @param minV * @param surface */ public void drawTextureOnSurface(boolean blend, Vector4f color,float maxU, float maxV , float minU , float minV ,ITessellatedSurface surface) { GL11.glEnable(GL11.GL_TEXTURE_2D); // be sure textures are on UtilGl.setColor(color); GL11.glDisable(GL11.GL_LIGHTING); // no lighting //GL11.glDisable(GL11.GL_DEPTH_TEST); // no depth test if (blend) { GL11.glEnable(GL11.GL_BLEND); // enable transparency GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); } else { GL11.glDisable(GL11.GL_BLEND); // disable transparency } // activate the image texture bindThisTexture(); int nrOfStepU = surface.getTesselU(); int nrOfStepV = surface.getTesselV(); GL11.glBegin(GL11.GL_QUADS); for (int i = 0;i < nrOfStepU;i++ ){ float u0 = (float)i / (float) nrOfStepU; float u1 = (float)(i+1) / (float) nrOfStepU; for (int j =0; j <nrOfStepV ; j++){ float v0 = (float)j / (float) nrOfStepV; float v1 = (float)(j+1) / (float) nrOfStepV; Vector3f p = surface.getPointAt (u0,v0); GL11.glTexCoord2f(u0, v0); GL11.glVertex3f(p.x,p.y,p.z ); p = surface.getPointAt (u0,v1); GL11.glTexCoord2f(u0, v1); GL11.glVertex3f(p.x,p.y,p.z ); GL11.glTexCoord2f(u1, v1); p = surface.getPointAt (u1,v1); GL11.glVertex3f(p.x,p.y,p.z ); GL11.glTexCoord2f(u1, v0); p = surface.getPointAt (u1,v0); GL11.glVertex3f(p.x,p.y,p.z ); } } GL11.glEnd(); } private void drawTextureOnRectangle(TargetRectangle rectangle, float maxU, float maxV, float minU, float minV, Vector4f[] colors) { GL11.glBegin(GL11.GL_QUADS); { UtilGl.setColor(colors[2]); GL11.glTexCoord2f(minU, minV); UtilGl.loadVertex(rectangle.getBottomLeft()); UtilGl.setColor(colors[3]); GL11.glTexCoord2f(maxU, minV); UtilGl.loadVertex(rectangle.getBottomRight()); UtilGl.setColor(colors[1]); GL11.glTexCoord2f(maxU, maxV); UtilGl.loadVertex(rectangle.getTopRight()); UtilGl.setColor(colors[0]); GL11.glTexCoord2f(minU, maxV); UtilGl.loadVertex(rectangle.getTopLeft()); } GL11.glEnd(); } private void drawTextureOnRectangle(TargetRectangle2d rectangle, float maxU, float maxV, float minU, float minV, Vector4f[] colors) { GL11.glBegin(GL11.GL_QUADS); { UtilGl.setColor(colors[2]); GL11.glTexCoord2f(minU, minV); GL11.glVertex2f(rectangle.x, rectangle.bottom); UtilGl.setColor(colors[3]); GL11.glTexCoord2f(maxU, minV); GL11.glVertex2f(rectangle.right, rectangle.bottom); UtilGl.setColor(colors[1]); GL11.glTexCoord2f(maxU, maxV); GL11.glVertex2f(rectangle.right, rectangle.y); UtilGl.setColor(colors[0]); GL11.glTexCoord2f(minU, maxV); GL11.glVertex2f(rectangle.x, rectangle.y); } GL11.glEnd(); } /** * This method does not bind the texture! * @param rectangle * @param maxU * @param maxV * @param minU * @param minV */ private void drawTextureOnRectangle(TargetRectangle rectangle, float maxU, float maxV, float minU, float minV) { GL11.glBegin(GL11.GL_QUADS); { GL11.glTexCoord2f(minU, minV); UtilGl.loadVertex(rectangle.getBottomLeft()); GL11.glTexCoord2f(maxU, minV); UtilGl.loadVertex(rectangle.getBottomRight()); GL11.glTexCoord2f(maxU, maxV); UtilGl.loadVertex(rectangle.getTopRight()); GL11.glTexCoord2f(minU, maxV); UtilGl.loadVertex(rectangle.getTopLeft()); } GL11.glEnd(); } private void drawTextureOnRectangle(TargetRectangle2d rectangle, float maxU, float maxV, float minU, float minV) { GL11.glBegin(GL11.GL_QUADS); { GL11.glTexCoord2f(minU, minV); GL11.glVertex2f(rectangle.x, rectangle.bottom); GL11.glTexCoord2f(maxU, minV); GL11.glVertex2f(rectangle.right, rectangle.bottom); GL11.glTexCoord2f(maxU, maxV); GL11.glVertex2f(rectangle.right, rectangle.y); GL11.glTexCoord2f(minU, maxV); GL11.glVertex2f(rectangle.x, rectangle.y); } GL11.glEnd(); } public void selectTecture() { // tweak settings GL11.glEnable(GL11.GL_TEXTURE_2D); // be sure textures are on // activate the image texture GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); } public void deSelectTecture() { // tweak settings GL11.glDisable(GL11.GL_TEXTURE_2D); // be sure textures are on } private int formatInt; private int border; public int getFormatInt() { return formatInt; } public int hasBorder() { return border; } public void replaceContent(NativeImage newimage) { replaceContent(newimage, EMipMapType.none, ETextureWrapType.mirroredRepeat, false); } public void replaceContent(NativeImage newimage, EMipMapType mtype, ETextureWrapType wrapType, boolean appleClientStorage) { this.sourceImage=newimage; this.sourceMipmapType=mtype; this.sourceTextureWrapType=wrapType; if(EMipMapType.standard.equals(mtype)) { ContextCapabilities cc=GLContext.getCapabilities(); if(!cc.OpenGL30&&!cc.GL_EXT_framebuffer_object) { mtype=EMipMapType.none; } } this.width = newimage.getWidth(); this.height = newimage.getHeight(); GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); switch (wrapType) { case clamp: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP); break; case clampYrepeatX: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_CLAMP); break; case clampXrepeatY: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_CLAMP); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); break; case repeat: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL11.GL_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL11.GL_REPEAT); break; case mirroredRepeat: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_S, GL14.GL_MIRRORED_REPEAT); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_WRAP_T, GL14.GL_MIRRORED_REPEAT); break; default: break; } switch (mtype) { case none: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR); break; case standard: GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); break; default: throw new RuntimeException("mipmapping type is not implemented: "+mtype); } int alignment=newimage.getAlignment(); GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, alignment); int pixel_format; int dataformat; pixel_format=componentOrderToOGL(newimage.getComponentOrder()); int internal_format=componentOrderTOIntarnalFormat(newimage.getComponentOrder()); boolean undoClientStorage=false; if(appleClientStorage) { ContextCapabilities cc=GLContext.getCapabilities(); if(cc.GL_APPLE_client_storage) { GL11.glPixelStorei(APPLEClientStorage.GL_UNPACK_CLIENT_STORAGE_APPLE, GL11.GL_TRUE); undoClientStorage=true; } } dataformat = GL11.GL_UNSIGNED_BYTE; GL11.glTexImage2D(GL11.GL_TEXTURE_2D, 0, internal_format, width, height, 0, pixel_format, dataformat, newimage.getBuffer().getJavaAccessor()); switch (mtype) { case standard: // Using GL_GENERATE_MIPMAP instead causes my NVidia to process about 100% // CPU! Seems to use CPU to generate mipmap levels if(GLContext.getCapabilities().OpenGL30) { GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); }else { EXTFramebufferObject.glGenerateMipmapEXT(GL11.GL_TEXTURE_2D); } break; case none: default: //nothing to do break; } // Reset the default behaviour GL11.glPixelStorei(GL11.GL_UNPACK_ALIGNMENT, 1); if(undoClientStorage) { GL11.glPixelStorei(APPLEClientStorage.GL_UNPACK_CLIENT_STORAGE_APPLE, GL11.GL_FALSE); } } public static int componentOrderToOGL(ENativeImageComponentOrder co) { switch (co) { case RGB: return GL11.GL_RGB; case RGBA: return GL11.GL_RGBA; case MONO: return GL11.GL_LUMINANCE; case ALPHA: return GL11.GL_ALPHA; case BGR: return GL12.GL_BGR; case BGRA: return GL12.GL_BGRA; case ARGB: return GL12.GL_BGRA; default: throw new RuntimeException( "pixel format is unknown to opengl module: " + co); } } private int componentOrderTOIntarnalFormat( ENativeImageComponentOrder componentOrder) { switch (componentOrder) { case ARGB: case BGRA: case RGBA: return GL11.GL_RGBA8; case BGR: case RGB: return GL11.GL_RGB8; case ALPHA: return GL11.GL_ALPHA8; case MONO: return GL11.GL_LUMINANCE8; default: throw new RuntimeException( "pixel format is unknown to opengl module: " + componentOrder); } } /** * Generate mip-map for an existing texture. It is useful when the texture is rendered shrinked. */ public void generateMipMap() { ContextCapabilities cc=GLContext.getCapabilities(); if(cc.OpenGL30) { selectTecture(); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); GL30.glGenerateMipmap(GL11.GL_TEXTURE_2D); deSelectTecture(); }else if(cc.GL_EXT_framebuffer_object) { selectTecture(); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, GL11.GL_LINEAR); GL11.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, GL11.GL_LINEAR_MIPMAP_LINEAR); GL11.glBindTexture(GL11.GL_TEXTURE_2D, textureHandle); EXTFramebufferObject.glGenerateMipmapEXT(GL11.GL_TEXTURE_2D); deSelectTecture(); } } @Override public boolean isDisposed() { return disposed; } public void applyBlendFunc(ENativeImageAlphaStorageFormat alphaFormat) { if(ENativeImageAlphaStorageFormat.premultiplied.equals(alphaFormat)) { setBlendFunc(EBlendFunc.ALPHA_PREMULTIPLIED); }else { setBlendFunc(EBlendFunc.SRC_ALPHA__ONE_MINUS_SRC_ALPHA); } } public void setSamplingNear(boolean samplingNear) { this.samplingNear=samplingNear; } }
fixing 'squid:ClassVariableVisibilityCheck' - breaks API!
commons/hu.qgears.opengl.commons/src/hu/qgears/opengl/commons/Texture.java
fixing 'squid:ClassVariableVisibilityCheck' - breaks API!
<ide><path>ommons/hu.qgears.opengl.commons/src/hu/qgears/opengl/commons/Texture.java <ide> private EBlendFunc blendFunc=EBlendFunc.off; <ide> private boolean disposed = false; <ide> private int width, height; <del> public NativeImage sourceImage; <del> public EMipMapType sourceMipmapType; <del> public ETextureWrapType sourceTextureWrapType; <add> private NativeImage sourceImage; <add> private EMipMapType sourceMipmapType; <add> private ETextureWrapType sourceTextureWrapType; <ide> /** <ide> * Use for debug purpose only: number of allocated texture objects. <ide> */ <del> public static int numberOfTextures=0; <add> private static int numberOfTextures=0; <ide> <ide> public EBlendFunc getBlendFunc() { <ide> return blendFunc; <ide> public SizeInt getSize() <ide> { <ide> return new SizeInt(width, height); <add> } <add> <add> public NativeImage getSourceImage() { <add> return sourceImage; <add> } <add> <add> public EMipMapType getSourceMipmapType() { <add> return sourceMipmapType; <add> } <add> <add> public ETextureWrapType getSourceTextureWrapType() { <add> return sourceTextureWrapType; <ide> } <ide> <ide> private Texture(int textureHandle, int w, int h, int format, int border) { <ide> public void setSamplingNear(boolean samplingNear) { <ide> this.samplingNear=samplingNear; <ide> } <add> <add> /** <add> * Returns the number of allocated texture objects. <add> * Use for debug purpose only! <add> * @return the number of allocated texture objects. <add> */ <add> public static int getNumberOfTextures() { <add> return numberOfTextures; <add> } <ide> }
JavaScript
agpl-3.0
85fdfeccb028ad46d9be7522fd508311aca6d3e2
0
duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test,duaneking/rockstar_test
8a8e4c6c-2e64-11e5-9284-b827eb9e62be
helloWorld.js
8a88b554-2e64-11e5-9284-b827eb9e62be
8a8e4c6c-2e64-11e5-9284-b827eb9e62be
helloWorld.js
8a8e4c6c-2e64-11e5-9284-b827eb9e62be
<ide><path>elloWorld.js <del>8a88b554-2e64-11e5-9284-b827eb9e62be <add>8a8e4c6c-2e64-11e5-9284-b827eb9e62be
JavaScript
mit
7e64f642a1d82a7628e4cdf2d518c8dc27c74726
0
stinaq/education,stinaq/education
(function (window, $) { "use strict"; var quizData = []; var buildQuestionMarkup = function (questionItem, index) { return [ '<div class="question-wrapper" id="', index, '">', '<p>', questionItem.question, '</p>', '<div>', '<div>', '<input type="checkbox" value="A">', questionItem.a, '</div>', '<div>', '<input type="checkbox" value="B">', questionItem.b, '</div>', '<div>', '<input type="checkbox" value="C">', questionItem.c, '</div>', '<div>', '<input type="checkbox" value="D">', questionItem.d, '</div>', '</div>', '<div>', '<input type="submit" value="Check my answer">', '</div>', '</div>' ].join(''); }; var checkAnswer = function (index, answers) { alert('Your answer was ' + answers + ' and the correct answers were ' + quizData[index].answer); }; var addEvents = function (quizWrapper) { quizWrapper.on('click', 'input[type=submit]', function (event) { var questionElement = window.bla = $(event.currentTarget).parents('.question-wrapper'); var questionIndex = questionElement.attr('id'); var answers = $.map(questionElement.find('input[type=checkbox]:checked'), function (inputElement, key) { return $(inputElement).val(); }); checkAnswer(questionIndex, answers); }); }; var renderQuestion = function (markup) { var quizWrapper = $('#quiz-wrapper'); quizWrapper.html(markup); addEvents(quizWrapper); }; var success = function (data) { var finishedMarkup = ''; quizData = data; $.each(quizData, function(index, element) { finishedMarkup += buildQuestionMarkup(element, index); }); renderQuestion(finishedMarkup); }; var getData = function() { $.ajax({ url: 'data.json', success: success, error: console.log, dataType: 'json' }); }; var initialize = function () { getData(); }; initialize(); })(window, jQuery);
JavaScript/quizapp/quizapp.js
(function (window, $) { "use strict"; var buildQuestionMarkup = function (questionItem, index) { return [ '<div class="question-wrapper" id="', index, '">', '<p>', questionItem.question, '</p>', '<div>', '<div>', '<input type="checkbox" value="A">', questionItem.a, '</div>', '<div>', '<input type="checkbox" value="B">', questionItem.b, '</div>', '<div>', '<input type="checkbox" value="C">', questionItem.c, '</div>', '<div>', '<input type="checkbox" value="D">', questionItem.d, '</div>', '</div>', '<div>', '<input type="submit" value="Check">', '</div>', '</div>' ].join(''); }; var addEvents = function (quizWrapper) { quizWrapper.on('click', 'input[type=submit]', function () { console.log('i was clicked'); }); }; var renderQuestion = function (markup) { var quizWrapper = $('#quiz-wrapper'); quizWrapper.html(markup); addEvents(quizWrapper); }; var success = function (data) { var finishedMarkup = ''; $.each(data, function(index, element) { finishedMarkup += buildQuestionMarkup(element, index); }); renderQuestion(finishedMarkup); }; var getData = function() { $.ajax({ url: 'data.json', success: success, error: console.log, dataType: 'json' }); }; var initialize = function () { getData(); }; initialize(); })(window, jQuery);
App now shows your answer and the correct answer
JavaScript/quizapp/quizapp.js
App now shows your answer and the correct answer
<ide><path>avaScript/quizapp/quizapp.js <ide> (function (window, $) { <del> "use strict"; <add> "use strict"; <add> var quizData = []; <ide> <del> var buildQuestionMarkup = function (questionItem, index) { <del> return [ <del> '<div class="question-wrapper" id="', index, '">', <del> '<p>', <del> questionItem.question, <del> '</p>', <del> '<div>', <del> '<div>', <del> '<input type="checkbox" value="A">', <del> questionItem.a, <del> '</div>', <del> '<div>', <del> '<input type="checkbox" value="B">', <del> questionItem.b, <del> '</div>', <del> '<div>', <del> '<input type="checkbox" value="C">', <del> questionItem.c, <del> '</div>', <del> '<div>', <del> '<input type="checkbox" value="D">', <del> questionItem.d, <del> '</div>', <del> '</div>', <del> '<div>', <del> '<input type="submit" value="Check">', <del> '</div>', <del> '</div>' <del> ].join(''); <del> }; <add> var buildQuestionMarkup = function (questionItem, index) { <add> return [ <add> '<div class="question-wrapper" id="', index, '">', <add> '<p>', <add> questionItem.question, <add> '</p>', <add> '<div>', <add> '<div>', <add> '<input type="checkbox" value="A">', <add> questionItem.a, <add> '</div>', <add> '<div>', <add> '<input type="checkbox" value="B">', <add> questionItem.b, <add> '</div>', <add> '<div>', <add> '<input type="checkbox" value="C">', <add> questionItem.c, <add> '</div>', <add> '<div>', <add> '<input type="checkbox" value="D">', <add> questionItem.d, <add> '</div>', <add> '</div>', <add> '<div>', <add> '<input type="submit" value="Check my answer">', <add> '</div>', <add> '</div>' <add> ].join(''); <add> }; <ide> <del> var addEvents = function (quizWrapper) { <del> quizWrapper.on('click', 'input[type=submit]', function () { <del> console.log('i was clicked'); <del> }); <del> }; <add> var checkAnswer = function (index, answers) { <add> alert('Your answer was ' + answers + ' and the correct answers were ' + quizData[index].answer); <add> }; <ide> <del> var renderQuestion = function (markup) { <del> var quizWrapper = $('#quiz-wrapper'); <del> quizWrapper.html(markup); <del> addEvents(quizWrapper); <del> }; <add> var addEvents = function (quizWrapper) { <add> quizWrapper.on('click', 'input[type=submit]', function (event) { <add> var questionElement = window.bla = $(event.currentTarget).parents('.question-wrapper'); <add> var questionIndex = questionElement.attr('id'); <add> var answers = $.map(questionElement.find('input[type=checkbox]:checked'), function (inputElement, key) { <add> return $(inputElement).val(); <add> }); <add> checkAnswer(questionIndex, answers); <add> }); <add> }; <ide> <del> var success = function (data) { <del> var finishedMarkup = ''; <del> $.each(data, function(index, element) { <del> finishedMarkup += buildQuestionMarkup(element, index); <del> }); <del> renderQuestion(finishedMarkup); <del> }; <add> var renderQuestion = function (markup) { <add> var quizWrapper = $('#quiz-wrapper'); <add> quizWrapper.html(markup); <add> addEvents(quizWrapper); <add> }; <ide> <del> var getData = function() { <del> $.ajax({ <del> url: 'data.json', <del> success: success, <del> error: console.log, <del> dataType: 'json' <del> }); <del> }; <add> var success = function (data) { <add> var finishedMarkup = ''; <add> quizData = data; <add> $.each(quizData, function(index, element) { <add> finishedMarkup += buildQuestionMarkup(element, index); <add> }); <add> renderQuestion(finishedMarkup); <add> }; <ide> <del> var initialize = function () { <del> getData(); <del> }; <add> var getData = function() { <add> $.ajax({ <add> url: 'data.json', <add> success: success, <add> error: console.log, <add> dataType: 'json' <add> }); <add> }; <ide> <del> initialize(); <add> var initialize = function () { <add> getData(); <add> }; <add> <add> initialize(); <ide> <ide> })(window, jQuery);
Java
apache-2.0
ddfeaf9a11fc82cb3b1225a5754285435f2f7fab
0
apache/bookkeeper,apache/bookkeeper,apache/bookkeeper,apache/bookkeeper,apache/bookkeeper,apache/bookkeeper
/** * 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.bookkeeper.util; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.bookkeeper.util.BookKeeperConstants.AVAILABLE_NODE; import static org.apache.bookkeeper.util.BookKeeperConstants.READONLY; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.common.component.ComponentInfoPublisher; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.discover.BookieServiceInfo; import org.apache.bookkeeper.discover.BookieServiceInfo.Endpoint; import org.apache.bookkeeper.meta.zk.ZKMetadataDriverBase; import org.apache.bookkeeper.proto.BookieServer; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.server.service.BookieService; import org.apache.bookkeeper.shims.zk.ZooKeeperServerShim; import org.apache.bookkeeper.shims.zk.ZooKeeperServerShimFactory; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.zookeeper.ZooKeeperClient; import org.apache.commons.io.FileUtils; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; import org.apache.zookeeper.ZooDefs.Ids; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Local Bookkeeper. */ public class LocalBookKeeper { protected static final Logger LOG = LoggerFactory.getLogger(LocalBookKeeper.class); public static final int CONNECTION_TIMEOUT = 30000; private static String newMetadataServiceUri(String zkServers, int port, String layout, String ledgerPath) { return "zk+" + layout + "://" + zkServers + ":" + port + ledgerPath; } int numberOfBookies; public LocalBookKeeper() { this(3); } public LocalBookKeeper(int numberOfBookies) { this(numberOfBookies, 5000, new ServerConfiguration(), defaultLocalBookiesConfigDir); } public LocalBookKeeper( int numberOfBookies, int initialPort, ServerConfiguration baseConf, String localBookiesConfigDirName) { this.numberOfBookies = numberOfBookies; this.initialPort = initialPort; this.localBookiesConfigDir = new File(localBookiesConfigDirName); this.baseConf = baseConf; LOG.info("Running {} bookie(s) on zk ensemble = '{}:{}'.", this.numberOfBookies, zooKeeperDefaultHost, zooKeeperDefaultPort); } private static String zooKeeperDefaultHost = "127.0.0.1"; private static int zooKeeperDefaultPort = 2181; private static int zkSessionTimeOut = 5000; private static Integer bookieDefaultInitialPort = 5000; private static String defaultLocalBookiesConfigDir = "/tmp/localbookies-config"; //BookKeeper variables File[] journalDirs; BookieServer[] bs; ServerConfiguration[] bsConfs; Integer initialPort = 5000; private ServerConfiguration baseConf; File localBookiesConfigDir; /** * @param maxCC * Max Concurrency of Client * @param zookeeperPort * ZooKeeper Server Port */ public static ZooKeeperServerShim runZookeeper(int maxCC, int zookeeperPort) throws IOException { File zkTmpDir = IOUtils.createTempDir("zookeeper", "localbookkeeper"); return runZookeeper(maxCC, zookeeperPort, zkTmpDir); } public static ZooKeeperServerShim runZookeeper(int maxCC, int zookeeperPort, File zkDir) throws IOException { LOG.info("Starting ZK server"); ZooKeeperServerShim server = ZooKeeperServerShimFactory.createServer(zkDir, zkDir, zookeeperPort, maxCC); server.start(); boolean b = waitForServerUp(InetAddress.getLoopbackAddress().getHostAddress() + ":" + zookeeperPort, CONNECTION_TIMEOUT); if (LOG.isDebugEnabled()) { LOG.debug("ZooKeeper server up: {}", b); } return server; } @SuppressWarnings("deprecation") private void initializeZookeeper(String zkHost, int zkPort) throws IOException { LOG.info("Instantiate ZK Client"); //initialize the zk client with values try (ZooKeeperClient zkc = ZooKeeperClient.newBuilder() .connectString(zkHost + ":" + zkPort) .sessionTimeoutMs(zkSessionTimeOut) .build()) { String zkLedgersRootPath = ZKMetadataDriverBase.resolveZkLedgersRootPath(baseConf); ZkUtils.createFullPathOptimistic(zkc, zkLedgersRootPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); List<Op> multiOps = Lists.newArrayListWithExpectedSize(2); multiOps.add( Op.create(zkLedgersRootPath + "/" + AVAILABLE_NODE, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)); multiOps.add( Op.create(zkLedgersRootPath + "/" + AVAILABLE_NODE + "/" + READONLY, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)); zkc.multi(multiOps); // No need to create an entry for each requested bookie anymore as the // BookieServers will register themselves with ZooKeeper on startup. } catch (KeeperException e) { LOG.error("Exception while creating znodes", e); throw new IOException("Error creating znodes : ", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.error("Interrupted while creating znodes", e); throw new IOException("Error creating znodes : ", e); } } private static void cleanupDirectories(List<File> dirs) throws IOException { for (File dir : dirs) { FileUtils.deleteDirectory(dir); } } private List<File> runBookies(String dirSuffix) throws Exception { List<File> tempDirs = new ArrayList<>(); try { runBookies(tempDirs, dirSuffix); return tempDirs; } catch (Exception ioe) { cleanupDirectories(tempDirs); throw ioe; } } @SuppressWarnings("deprecation") private void runBookies(List<File> tempDirs, String dirSuffix) throws Exception { LOG.info("Starting Bookie(s)"); // Create Bookie Servers (B1, B2, B3) journalDirs = new File[numberOfBookies]; bs = new BookieServer[numberOfBookies]; bsConfs = new ServerConfiguration[numberOfBookies]; if (localBookiesConfigDir.exists() && localBookiesConfigDir.isFile()) { throw new IOException("Unable to create LocalBookiesConfigDir, since there is a file at " + localBookiesConfigDir.getAbsolutePath()); } if (!localBookiesConfigDir.exists() && !localBookiesConfigDir.mkdirs()) { throw new IOException( "Unable to create LocalBookiesConfigDir - " + localBookiesConfigDir.getAbsolutePath()); } for (int i = 0; i < numberOfBookies; i++) { if (null == baseConf.getJournalDirNameWithoutDefault()) { journalDirs[i] = IOUtils.createTempDir("localbookkeeper" + Integer.toString(i), dirSuffix); tempDirs.add(journalDirs[i]); } else { journalDirs[i] = new File(baseConf.getJournalDirName(), "bookie" + Integer.toString(i)); } if (journalDirs[i].exists()) { if (journalDirs[i].isDirectory()) { FileUtils.deleteDirectory(journalDirs[i]); } else if (!journalDirs[i].delete()) { throw new IOException("Couldn't cleanup bookie journal dir " + journalDirs[i]); } } if (!journalDirs[i].mkdirs()) { throw new IOException("Couldn't create bookie journal dir " + journalDirs[i]); } String [] ledgerDirs = baseConf.getLedgerDirWithoutDefault(); if ((null == ledgerDirs) || (0 == ledgerDirs.length)) { ledgerDirs = new String[] { journalDirs[i].getPath() }; } else { for (int l = 0; l < ledgerDirs.length; l++) { File dir = new File(ledgerDirs[l], "bookie" + Integer.toString(i)); if (dir.exists()) { if (dir.isDirectory()) { FileUtils.deleteDirectory(dir); } else if (!dir.delete()) { throw new IOException("Couldn't cleanup bookie ledger dir " + dir); } } if (!dir.mkdirs()) { throw new IOException("Couldn't create bookie ledger dir " + dir); } ledgerDirs[l] = dir.getPath(); } } bsConfs[i] = new ServerConfiguration((ServerConfiguration) baseConf.clone()); // If the caller specified ephemeral ports then use ephemeral ports for all // the bookies else use numBookie ports starting at initialPort PortManager.initPort(initialPort); if (0 == initialPort) { bsConfs[i].setBookiePort(0); } else { bsConfs[i].setBookiePort(PortManager.nextFreePort()); } if (null == baseConf.getMetadataServiceUriUnchecked()) { bsConfs[i].setMetadataServiceUri(baseConf.getMetadataServiceUri()); } bsConfs[i].setJournalDirName(journalDirs[i].getPath()); bsConfs[i].setLedgerDirNames(ledgerDirs); // write config into file before start so we can know what's wrong if start failed String fileName = Bookie.getBookieId(bsConfs[i]).toString() + ".conf"; serializeLocalBookieConfig(bsConfs[i], fileName); // Mimic BookKeeper Main final ComponentInfoPublisher componentInfoPublisher = new ComponentInfoPublisher(); final Supplier<BookieServiceInfo> bookieServiceInfoProvider = () -> buildBookieServiceInfo(componentInfoPublisher); BookieService bookieService = new BookieService(new BookieConfiguration(bsConfs[i]), NullStatsLogger.INSTANCE, bookieServiceInfoProvider ); bs[i] = bookieService.getServer(); bookieService.publishInfo(componentInfoPublisher); componentInfoPublisher.startupFinished(); bookieService.start(); } /* * baseconf.conf is needed because for executing any BookieShell command * of Metadata/Zookeeper Operation nature we need a valid conf file * having correct zk details and this could be used for running any such * bookieshell commands if bookieid is not provided as parameter to * bookkeeper shell operation. for eg: * "./bookkeeper shell localbookie listbookies -rw". But for execution * shell command of bookie Operation nature we need to provide bookieid, * for eg "./bookkeeper shell -localbookie 10.3.27.190:5000 lastmark", * so this shell command would use '10.3.27.190:5000.conf' file */ ServerConfiguration baseConfWithCorrectZKServers = new ServerConfiguration( (ServerConfiguration) baseConf.clone()); if (null == baseConf.getMetadataServiceUriUnchecked()) { baseConfWithCorrectZKServers.setMetadataServiceUri(baseConf.getMetadataServiceUri()); } serializeLocalBookieConfig(baseConfWithCorrectZKServers, "baseconf.conf"); } public static void startLocalBookies(String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort) throws Exception { ServerConfiguration conf = new ServerConfiguration(); startLocalBookiesInternal( conf, zkHost, zkPort, numBookies, shouldStartZK, initialBookiePort, true, "test", null, defaultLocalBookiesConfigDir); } public static void startLocalBookies(String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort, ServerConfiguration conf) throws Exception { startLocalBookiesInternal( conf, zkHost, zkPort, numBookies, shouldStartZK, initialBookiePort, true, "test", null, defaultLocalBookiesConfigDir); } public static void startLocalBookies(String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort, String dirSuffix) throws Exception { ServerConfiguration conf = new ServerConfiguration(); startLocalBookiesInternal( conf, zkHost, zkPort, numBookies, shouldStartZK, initialBookiePort, true, dirSuffix, null, defaultLocalBookiesConfigDir); } @SuppressWarnings("deprecation") static void startLocalBookiesInternal(ServerConfiguration conf, String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort, boolean stopOnExit, String dirSuffix, String zkDataDir, String localBookiesConfigDirName) throws Exception { conf.setMetadataServiceUri( newMetadataServiceUri( zkHost, zkPort, conf.getLedgerManagerLayoutStringFromFactoryClass(), conf.getZkLedgersRootPath())); LocalBookKeeper lb = new LocalBookKeeper(numBookies, initialBookiePort, conf, localBookiesConfigDirName); ZooKeeperServerShim zks = null; File zkTmpDir = null; List<File> bkTmpDirs = null; try { if (shouldStartZK) { File zkDataDirFile = null; if (zkDataDir != null) { zkDataDirFile = new File(zkDataDir); if (zkDataDirFile.exists() && zkDataDirFile.isFile()) { throw new IOException("Unable to create zkDataDir, since there is a file at " + zkDataDirFile.getAbsolutePath()); } if (!zkDataDirFile.exists() && !zkDataDirFile.mkdirs()) { throw new IOException("Unable to create zkDataDir - " + zkDataDirFile.getAbsolutePath()); } } zkTmpDir = IOUtils.createTempDir("zookeeper", dirSuffix, zkDataDirFile); zkTmpDir.deleteOnExit(); zks = LocalBookKeeper.runZookeeper(1000, zkPort, zkTmpDir); } lb.initializeZookeeper(zkHost, zkPort); bkTmpDirs = lb.runBookies(dirSuffix); try { while (true) { Thread.sleep(5000); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); if (stopOnExit) { lb.shutdownBookies(); if (null != zks) { zks.stop(); } } throw ie; } } catch (Exception e) { LOG.error("Failed to run {} bookies : zk ensemble = '{}:{}'", numBookies, zkHost, zkPort, e); throw e; } finally { if (stopOnExit) { if (null != bkTmpDirs) { cleanupDirectories(bkTmpDirs); } if (null != zkTmpDir) { FileUtils.deleteDirectory(zkTmpDir); } } } } /** * Serializes the config object to the specified file in localBookiesConfigDir. * * @param localBookieConfig * config object which has to be serialized * @param fileName * name of the file * @throws IOException */ private void serializeLocalBookieConfig(ServerConfiguration localBookieConfig, String fileName) throws IOException { File localBookieConfFile = new File(localBookiesConfigDir, fileName); if (localBookieConfFile.exists() && !localBookieConfFile.delete()) { throw new IOException( "Unable to delete the existing LocalBookieConfigFile - " + localBookieConfFile.getAbsolutePath()); } if (!localBookieConfFile.createNewFile()) { throw new IOException("Unable to create new File - " + localBookieConfFile.getAbsolutePath()); } Iterator<String> keys = localBookieConfig.getKeys(); try (PrintWriter writer = new PrintWriter(localBookieConfFile, "UTF-8")) { while (keys.hasNext()) { String key = keys.next(); String[] values = localBookieConfig.getStringArray(key); StringBuilder concatenatedValue = new StringBuilder(values[0]); for (int i = 1; i < values.length; i++) { concatenatedValue.append(",").append(values[i]); } writer.println(key + "=" + concatenatedValue.toString()); } } } public static void main(String[] args) { try { if (args.length < 1) { usage(); System.exit(-1); } int numBookies = 0; try { numBookies = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { LOG.error("Unrecognized number-of-bookies: {}", args[0]); usage(); System.exit(-1); } ServerConfiguration conf = new ServerConfiguration(); conf.setAllowLoopback(true); if (args.length >= 2) { String confFile = args[1]; try { conf.loadConf(new File(confFile).toURI().toURL()); LOG.info("Using configuration file {}", confFile); } catch (Exception e) { // load conf failed LOG.warn("Error loading configuration file {}", confFile, e); } } String zkDataDir = null; if (args.length >= 3) { zkDataDir = args[2]; } String localBookiesConfigDirName = defaultLocalBookiesConfigDir; if (args.length >= 4) { localBookiesConfigDirName = args[3]; } startLocalBookiesInternal(conf, zooKeeperDefaultHost, zooKeeperDefaultPort, numBookies, true, bookieDefaultInitialPort, false, "test", zkDataDir, localBookiesConfigDirName); } catch (Exception e) { LOG.error("Exiting LocalBookKeeper because of exception in main method", e); /* * This is needed because, some non-daemon thread (probably in ZK or * some other dependent service) is preventing the JVM from exiting, though * there is exception in main thread. */ System.exit(-1); } } private static void usage() { System.err.println( "Usage: LocalBookKeeper number-of-bookies [path to bookie config] " + "[path to create ZK data directory at] [path to LocalBookiesConfigDir]"); } public static boolean waitForServerUp(String hp, long timeout) { long start = System.currentTimeMillis(); String[] split = hp.split(":"); String host = split[0]; int port = Integer.parseInt(split[1]); while (true) { try { Socket sock = new Socket(host, port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes(UTF_8)); outstream.flush(); reader = new BufferedReader( new InputStreamReader(sock.getInputStream(), UTF_8)); String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { LOG.info("Server UP"); return true; } } finally { sock.close(); if (reader != null) { reader.close(); } } } catch (IOException e) { // ignore as this is expected LOG.info("server " + hp + " not up " + e); } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // ignore } } return false; } public void shutdownBookies() { for (BookieServer bookieServer: bs) { bookieServer.shutdown(); } } /** * Create the {@link BookieServiceInfo} starting from the published endpoints. * * @see ComponentInfoPublisher * @param componentInfoPublisher the endpoint publisher * @return the created bookie service info */ private static BookieServiceInfo buildBookieServiceInfo(ComponentInfoPublisher componentInfoPublisher) { List<Endpoint> endpoints = componentInfoPublisher.getEndpoints().values() .stream().map(e -> { return new Endpoint( e.getId(), e.getPort(), e.getHost(), e.getProtocol(), e.getAuth(), e.getExtensions() ); }).collect(Collectors.toList()); return new BookieServiceInfo(componentInfoPublisher.getProperties(), endpoints); } }
bookkeeper-server/src/main/java/org/apache/bookkeeper/util/LocalBookKeeper.java
/** * 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.bookkeeper.util; import static java.nio.charset.StandardCharsets.UTF_8; import static org.apache.bookkeeper.util.BookKeeperConstants.AVAILABLE_NODE; import static org.apache.bookkeeper.util.BookKeeperConstants.READONLY; import com.google.common.collect.Lists; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.bookkeeper.bookie.Bookie; import org.apache.bookkeeper.common.component.ComponentInfoPublisher; import org.apache.bookkeeper.conf.ServerConfiguration; import org.apache.bookkeeper.discover.BookieServiceInfo; import org.apache.bookkeeper.discover.BookieServiceInfo.Endpoint; import org.apache.bookkeeper.meta.zk.ZKMetadataDriverBase; import org.apache.bookkeeper.proto.BookieServer; import org.apache.bookkeeper.server.conf.BookieConfiguration; import org.apache.bookkeeper.server.service.BookieService; import org.apache.bookkeeper.shims.zk.ZooKeeperServerShim; import org.apache.bookkeeper.shims.zk.ZooKeeperServerShimFactory; import org.apache.bookkeeper.stats.NullStatsLogger; import org.apache.bookkeeper.zookeeper.ZooKeeperClient; import org.apache.commons.io.FileUtils; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.Op; import org.apache.zookeeper.ZooDefs.Ids; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Local Bookkeeper. */ public class LocalBookKeeper { protected static final Logger LOG = LoggerFactory.getLogger(LocalBookKeeper.class); public static final int CONNECTION_TIMEOUT = 30000; private static String newMetadataServiceUri(String zkServers, int port, String layout, String ledgerPath) { return "zk+" + layout + "://" + zkServers + ":" + port + ledgerPath; } int numberOfBookies; public LocalBookKeeper() { this(3); } public LocalBookKeeper(int numberOfBookies) { this(numberOfBookies, 5000, new ServerConfiguration(), defaultLocalBookiesConfigDir); } public LocalBookKeeper( int numberOfBookies, int initialPort, ServerConfiguration baseConf, String localBookiesConfigDirName) { this.numberOfBookies = numberOfBookies; this.initialPort = initialPort; this.localBookiesConfigDir = new File(localBookiesConfigDirName); this.baseConf = baseConf; LOG.info("Running {} bookie(s) on zk ensemble = '{}:{}'.", this.numberOfBookies, zooKeeperDefaultHost, zooKeeperDefaultPort); } private static String zooKeeperDefaultHost = "127.0.0.1"; private static int zooKeeperDefaultPort = 2181; private static int zkSessionTimeOut = 5000; private static Integer bookieDefaultInitialPort = 5000; private static String defaultLocalBookiesConfigDir = "/tmp/localbookies-config"; //BookKeeper variables File[] journalDirs; BookieServer[] bs; ServerConfiguration[] bsConfs; Integer initialPort = 5000; private ServerConfiguration baseConf; File localBookiesConfigDir; /** * @param maxCC * Max Concurrency of Client * @param zookeeperPort * ZooKeeper Server Port */ public static ZooKeeperServerShim runZookeeper(int maxCC, int zookeeperPort) throws IOException { File zkTmpDir = IOUtils.createTempDir("zookeeper", "localbookkeeper"); return runZookeeper(maxCC, zookeeperPort, zkTmpDir); } public static ZooKeeperServerShim runZookeeper(int maxCC, int zookeeperPort, File zkDir) throws IOException { LOG.info("Starting ZK server"); ZooKeeperServerShim server = ZooKeeperServerShimFactory.createServer(zkDir, zkDir, zookeeperPort, maxCC); server.start(); boolean b = waitForServerUp(InetAddress.getLoopbackAddress().getHostAddress() + ":" + zookeeperPort, CONNECTION_TIMEOUT); if (LOG.isDebugEnabled()) { LOG.debug("ZooKeeper server up: {}", b); } return server; } @SuppressWarnings("deprecation") private void initializeZookeeper(String zkHost, int zkPort) throws IOException { LOG.info("Instantiate ZK Client"); //initialize the zk client with values try (ZooKeeperClient zkc = ZooKeeperClient.newBuilder() .connectString(zkHost + ":" + zkPort) .sessionTimeoutMs(zkSessionTimeOut) .build()) { String zkLedgersRootPath = ZKMetadataDriverBase.resolveZkLedgersRootPath(baseConf); ZkUtils.createFullPathOptimistic(zkc, zkLedgersRootPath, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); List<Op> multiOps = Lists.newArrayListWithExpectedSize(2); multiOps.add( Op.create(zkLedgersRootPath + "/" + AVAILABLE_NODE, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)); multiOps.add( Op.create(zkLedgersRootPath + "/" + AVAILABLE_NODE + "/" + READONLY, new byte[0], Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT)); zkc.multi(multiOps); // No need to create an entry for each requested bookie anymore as the // BookieServers will register themselves with ZooKeeper on startup. } catch (KeeperException e) { LOG.error("Exception while creating znodes", e); throw new IOException("Error creating znodes : ", e); } catch (InterruptedException e) { Thread.currentThread().interrupt(); LOG.error("Interrupted while creating znodes", e); throw new IOException("Error creating znodes : ", e); } } private static void cleanupDirectories(List<File> dirs) throws IOException { for (File dir : dirs) { FileUtils.deleteDirectory(dir); } } private List<File> runBookies(String dirSuffix) throws Exception { List<File> tempDirs = new ArrayList<File>(); try { runBookies(tempDirs, dirSuffix); return tempDirs; } catch (Exception ioe) { cleanupDirectories(tempDirs); throw ioe; } } @SuppressWarnings("deprecation") private void runBookies(List<File> tempDirs, String dirSuffix) throws Exception { LOG.info("Starting Bookie(s)"); // Create Bookie Servers (B1, B2, B3) journalDirs = new File[numberOfBookies]; bs = new BookieServer[numberOfBookies]; bsConfs = new ServerConfiguration[numberOfBookies]; if (localBookiesConfigDir.exists() && localBookiesConfigDir.isFile()) { throw new IOException("Unable to create LocalBookiesConfigDir, since there is a file at " + localBookiesConfigDir.getAbsolutePath()); } if (!localBookiesConfigDir.exists() && !localBookiesConfigDir.mkdirs()) { throw new IOException( "Unable to create LocalBookiesConfigDir - " + localBookiesConfigDir.getAbsolutePath()); } for (int i = 0; i < numberOfBookies; i++) { if (null == baseConf.getJournalDirNameWithoutDefault()) { journalDirs[i] = IOUtils.createTempDir("localbookkeeper" + Integer.toString(i), dirSuffix); tempDirs.add(journalDirs[i]); } else { journalDirs[i] = new File(baseConf.getJournalDirName(), "bookie" + Integer.toString(i)); } if (journalDirs[i].exists()) { if (journalDirs[i].isDirectory()) { FileUtils.deleteDirectory(journalDirs[i]); } else if (!journalDirs[i].delete()) { throw new IOException("Couldn't cleanup bookie journal dir " + journalDirs[i]); } } if (!journalDirs[i].mkdirs()) { throw new IOException("Couldn't create bookie journal dir " + journalDirs[i]); } String [] ledgerDirs = baseConf.getLedgerDirWithoutDefault(); if ((null == ledgerDirs) || (0 == ledgerDirs.length)) { ledgerDirs = new String[] { journalDirs[i].getPath() }; } else { for (int l = 0; l < ledgerDirs.length; l++) { File dir = new File(ledgerDirs[l], "bookie" + Integer.toString(i)); if (dir.exists()) { if (dir.isDirectory()) { FileUtils.deleteDirectory(dir); } else if (!dir.delete()) { throw new IOException("Couldn't cleanup bookie ledger dir " + dir); } } if (!dir.mkdirs()) { throw new IOException("Couldn't create bookie ledger dir " + dir); } ledgerDirs[l] = dir.getPath(); } } bsConfs[i] = new ServerConfiguration((ServerConfiguration) baseConf.clone()); // If the caller specified ephemeral ports then use ephemeral ports for all // the bookies else use numBookie ports starting at initialPort PortManager.initPort(initialPort); if (0 == initialPort) { bsConfs[i].setBookiePort(0); } else { bsConfs[i].setBookiePort(PortManager.nextFreePort()); } if (null == baseConf.getMetadataServiceUriUnchecked()) { bsConfs[i].setMetadataServiceUri(baseConf.getMetadataServiceUri()); } bsConfs[i].setJournalDirName(journalDirs[i].getPath()); bsConfs[i].setLedgerDirNames(ledgerDirs); // write config into file before start so we can know what's wrong if start failed String fileName = Bookie.getBookieId(bsConfs[i]).toString() + ".conf"; serializeLocalBookieConfig(bsConfs[i], fileName); // Mimic BookKeeper Main final ComponentInfoPublisher componentInfoPublisher = new ComponentInfoPublisher(); final Supplier<BookieServiceInfo> bookieServiceInfoProvider = () -> buildBookieServiceInfo(componentInfoPublisher); BookieService bookieService = new BookieService(new BookieConfiguration(bsConfs[i]), NullStatsLogger.INSTANCE, bookieServiceInfoProvider ); bs[i] = bookieService.getServer(); bookieService.publishInfo(componentInfoPublisher); componentInfoPublisher.startupFinished(); bookieService.start(); } /* * baseconf.conf is needed because for executing any BookieShell command * of Metadata/Zookeeper Operation nature we need a valid conf file * having correct zk details and this could be used for running any such * bookieshell commands if bookieid is not provided as parameter to * bookkeeper shell operation. for eg: * "./bookkeeper shell localbookie listbookies -rw". But for execution * shell command of bookie Operation nature we need to provide bookieid, * for eg "./bookkeeper shell -localbookie 10.3.27.190:5000 lastmark", * so this shell command would use '10.3.27.190:5000.conf' file */ ServerConfiguration baseConfWithCorrectZKServers = new ServerConfiguration( (ServerConfiguration) baseConf.clone()); if (null == baseConf.getMetadataServiceUriUnchecked()) { baseConfWithCorrectZKServers.setMetadataServiceUri(baseConf.getMetadataServiceUri()); } serializeLocalBookieConfig(baseConfWithCorrectZKServers, "baseconf.conf"); } public static void startLocalBookies(String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort) throws Exception { ServerConfiguration conf = new ServerConfiguration(); startLocalBookiesInternal( conf, zkHost, zkPort, numBookies, shouldStartZK, initialBookiePort, true, "test", null, defaultLocalBookiesConfigDir); } public static void startLocalBookies(String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort, ServerConfiguration conf) throws Exception { startLocalBookiesInternal( conf, zkHost, zkPort, numBookies, shouldStartZK, initialBookiePort, true, "test", null, defaultLocalBookiesConfigDir); } public static void startLocalBookies(String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort, String dirSuffix) throws Exception { ServerConfiguration conf = new ServerConfiguration(); startLocalBookiesInternal( conf, zkHost, zkPort, numBookies, shouldStartZK, initialBookiePort, true, dirSuffix, null, defaultLocalBookiesConfigDir); } @SuppressWarnings("deprecation") static void startLocalBookiesInternal(ServerConfiguration conf, String zkHost, int zkPort, int numBookies, boolean shouldStartZK, int initialBookiePort, boolean stopOnExit, String dirSuffix, String zkDataDir, String localBookiesConfigDirName) throws Exception { conf.setMetadataServiceUri( newMetadataServiceUri( zkHost, zkPort, conf.getLedgerManagerLayoutStringFromFactoryClass(), conf.getZkLedgersRootPath())); LocalBookKeeper lb = new LocalBookKeeper(numBookies, initialBookiePort, conf, localBookiesConfigDirName); ZooKeeperServerShim zks = null; File zkTmpDir = null; List<File> bkTmpDirs = null; try { if (shouldStartZK) { File zkDataDirFile = null; if (zkDataDir != null) { zkDataDirFile = new File(zkDataDir); if (zkDataDirFile.exists() && zkDataDirFile.isFile()) { throw new IOException("Unable to create zkDataDir, since there is a file at " + zkDataDirFile.getAbsolutePath()); } if (!zkDataDirFile.exists() && !zkDataDirFile.mkdirs()) { throw new IOException("Unable to create zkDataDir - " + zkDataDirFile.getAbsolutePath()); } } zkTmpDir = IOUtils.createTempDir("zookeeper", dirSuffix, zkDataDirFile); zkTmpDir.deleteOnExit(); zks = LocalBookKeeper.runZookeeper(1000, zkPort, zkTmpDir); } lb.initializeZookeeper(zkHost, zkPort); bkTmpDirs = lb.runBookies(dirSuffix); try { while (true) { Thread.sleep(5000); } } catch (InterruptedException ie) { Thread.currentThread().interrupt(); if (stopOnExit) { lb.shutdownBookies(); if (null != zks) { zks.stop(); } } throw ie; } } catch (Exception e) { LOG.error("Failed to run {} bookies : zk ensemble = '{}:{}'", numBookies, zkHost, zkPort, e); throw e; } finally { if (stopOnExit) { cleanupDirectories(bkTmpDirs); if (null != zkTmpDir) { FileUtils.deleteDirectory(zkTmpDir); } } } } /** * Serializes the config object to the specified file in localBookiesConfigDir. * * @param localBookieConfig * config object which has to be serialized * @param fileName * name of the file * @throws IOException */ private void serializeLocalBookieConfig(ServerConfiguration localBookieConfig, String fileName) throws IOException { File localBookieConfFile = new File(localBookiesConfigDir, fileName); if (localBookieConfFile.exists() && !localBookieConfFile.delete()) { throw new IOException( "Unable to delete the existing LocalBookieConfigFile - " + localBookieConfFile.getAbsolutePath()); } if (!localBookieConfFile.createNewFile()) { throw new IOException("Unable to create new File - " + localBookieConfFile.getAbsolutePath()); } Iterator<String> keys = localBookieConfig.getKeys(); try (PrintWriter writer = new PrintWriter(localBookieConfFile, "UTF-8")) { while (keys.hasNext()) { String key = keys.next(); String[] values = localBookieConfig.getStringArray(key); StringBuilder concatenatedValue = new StringBuilder(values[0]); for (int i = 1; i < values.length; i++) { concatenatedValue.append(",").append(values[i]); } writer.println(key + "=" + concatenatedValue.toString()); } } } public static void main(String[] args) { try { if (args.length < 1) { usage(); System.exit(-1); } int numBookies = 0; try { numBookies = Integer.parseInt(args[0]); } catch (NumberFormatException nfe) { LOG.error("Unrecognized number-of-bookies: {}", args[0]); usage(); System.exit(-1); } ServerConfiguration conf = new ServerConfiguration(); conf.setAllowLoopback(true); if (args.length >= 2) { String confFile = args[1]; try { conf.loadConf(new File(confFile).toURI().toURL()); LOG.info("Using configuration file {}", confFile); } catch (Exception e) { // load conf failed LOG.warn("Error loading configuration file {}", confFile, e); } } String zkDataDir = null; if (args.length >= 3) { zkDataDir = args[2]; } String localBookiesConfigDirName = defaultLocalBookiesConfigDir; if (args.length >= 4) { localBookiesConfigDirName = args[3]; } startLocalBookiesInternal(conf, zooKeeperDefaultHost, zooKeeperDefaultPort, numBookies, true, bookieDefaultInitialPort, false, "test", zkDataDir, localBookiesConfigDirName); } catch (Exception e) { LOG.error("Exiting LocalBookKeeper because of exception in main method", e); /* * This is needed because, some non-daemon thread (probably in ZK or * some other dependent service) is preventing the JVM from exiting, though * there is exception in main thread. */ System.exit(-1); } } private static void usage() { System.err.println( "Usage: LocalBookKeeper number-of-bookies [path to bookie config] " + "[path to create ZK data directory at] [path to LocalBookiesConfigDir]"); } public static boolean waitForServerUp(String hp, long timeout) { long start = System.currentTimeMillis(); String[] split = hp.split(":"); String host = split[0]; int port = Integer.parseInt(split[1]); while (true) { try { Socket sock = new Socket(host, port); BufferedReader reader = null; try { OutputStream outstream = sock.getOutputStream(); outstream.write("stat".getBytes(UTF_8)); outstream.flush(); reader = new BufferedReader( new InputStreamReader(sock.getInputStream(), UTF_8)); String line = reader.readLine(); if (line != null && line.startsWith("Zookeeper version:")) { LOG.info("Server UP"); return true; } } finally { sock.close(); if (reader != null) { reader.close(); } } } catch (IOException e) { // ignore as this is expected LOG.info("server " + hp + " not up " + e); } if (System.currentTimeMillis() > start + timeout) { break; } try { Thread.sleep(250); } catch (InterruptedException e) { Thread.currentThread().interrupt(); // ignore } } return false; } public void shutdownBookies() { for (BookieServer bookieServer: bs) { bookieServer.shutdown(); } } /** * Create the {@link BookieServiceInfo} starting from the published endpoints. * * @see ComponentInfoPublisher * @param componentInfoPublisher the endpoint publisher * @return the created bookie service info */ private static BookieServiceInfo buildBookieServiceInfo(ComponentInfoPublisher componentInfoPublisher) { List<Endpoint> endpoints = componentInfoPublisher.getEndpoints().values() .stream().map(e -> { return new Endpoint( e.getId(), e.getPort(), e.getHost(), e.getProtocol(), e.getAuth(), e.getExtensions() ); }).collect(Collectors.toList()); return new BookieServiceInfo(componentInfoPublisher.getProperties(), endpoints); } }
Fix potential NullPointerException when local book keeper stop on exit Descriptions of the changes in this PR: - Fix potential NullPointerException when local book keeper stop on exit. Reviewers: Enrico Olivelli <[email protected]>, Sijie Guo <[email protected]> This closes #2414 from gaoxinge/fix
bookkeeper-server/src/main/java/org/apache/bookkeeper/util/LocalBookKeeper.java
Fix potential NullPointerException when local book keeper stop on exit
<ide><path>ookkeeper-server/src/main/java/org/apache/bookkeeper/util/LocalBookKeeper.java <ide> <ide> private List<File> runBookies(String dirSuffix) <ide> throws Exception { <del> List<File> tempDirs = new ArrayList<File>(); <add> List<File> tempDirs = new ArrayList<>(); <ide> try { <ide> runBookies(tempDirs, dirSuffix); <ide> return tempDirs; <ide> throw e; <ide> } finally { <ide> if (stopOnExit) { <del> cleanupDirectories(bkTmpDirs); <add> if (null != bkTmpDirs) { <add> cleanupDirectories(bkTmpDirs); <add> } <ide> if (null != zkTmpDir) { <ide> FileUtils.deleteDirectory(zkTmpDir); <ide> }
Java
apache-2.0
62fe8434a1b172e61a1cb63f31594b6d33067c4b
0
killbill/killbill-adyen-plugin
/* * Copyright 2014-2018 Groupon, Inc * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project 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.killbill.billing.plugin.adyen.api; import java.math.BigDecimal; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.joda.time.Period; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.killbill.adyen.recurring.RecurringDetail; import org.killbill.billing.account.api.Account; import org.killbill.billing.account.api.AccountApiException; import org.killbill.billing.payment.api.Payment; import org.killbill.billing.payment.api.PaymentApiException; import org.killbill.billing.payment.api.PaymentMethodPlugin; import org.killbill.billing.payment.api.PaymentTransaction; import org.killbill.billing.payment.api.PluginProperty; import org.killbill.billing.payment.api.TransactionType; import org.killbill.billing.payment.plugin.api.PaymentMethodInfoPlugin; import org.killbill.billing.payment.plugin.api.PaymentPluginApiException; import org.killbill.billing.payment.plugin.api.PaymentPluginStatus; import org.killbill.billing.payment.plugin.api.PaymentTransactionInfoPlugin; import org.killbill.billing.plugin.TestUtils; import org.killbill.billing.plugin.adyen.dao.AdyenDao; import org.killbill.billing.plugin.adyen.dao.gen.tables.records.AdyenPaymentMethodsRecord; import org.killbill.billing.plugin.api.PluginProperties; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ning.http.util.UTF8UrlEncoder; import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.jayway.restassured.http.ContentType; import static com.jayway.restassured.RestAssured.given; import static org.killbill.billing.plugin.adyen.api.AdyenPaymentPluginApi.PROPERTY_DD_ACCOUNT_NUMBER; import static org.killbill.billing.plugin.adyen.api.AdyenPaymentPluginApi.PROPERTY_DD_BANK_IDENTIFIER_CODE; import static org.killbill.billing.plugin.adyen.api.AdyenPaymentPluginApi.PROPERTY_DD_HOLDER_NAME; import static org.killbill.billing.plugin.adyen.api.AdyenPaymentPluginApi.PROPERTY_ELV_BLZ; import static org.killbill.billing.plugin.api.payment.PluginPaymentPluginApi.PROPERTY_COUNTRY; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestAdyenPaymentPluginApi extends TestAdyenPaymentPluginApiBase { private static final long SLEEP_IN_MILLIS_FOR_RECURRING_DETAIL = 3000L; // 3 Seconds private static final int HTTP_200_OK = 200; private static final int HTTP_PORT = 80; private static final int HTTPS_PORT = 443; private static final Map<TransactionType, String> TRANSACTION_TYPE_TO_EVENT_CODE = ImmutableMap.<TransactionType, String>builder().put(TransactionType.VOID, "CANCELLATION") .put(TransactionType.REFUND, "REFUND") .put(TransactionType.CAPTURE, "CAPTURE") .put(TransactionType.CREDIT, "REFUND_WITH_DATA") .put(TransactionType.CHARGEBACK, "CHARGEBACK") .put(TransactionType.AUTHORIZE, "AUTHORISATION") .put(TransactionType.PURCHASE, "AUTHORISATION") .build(); private final Iterable<PluginProperty> propertiesWithCCInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Dupont") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .build()); private final Iterable<PluginProperty> propertiesWith3DSInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Montblanc") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_3DS_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_3DS_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_USER_AGENT, "Java/1.8") .put(AdyenPaymentPluginApi.PROPERTY_ACCEPT_HEADER, "application/json") .put(AdyenPaymentPluginApi.PROPERTY_TERM_URL, "dummy://url") .put(AdyenPaymentPluginApi.PROPERTY_THREE_D_THRESHOLD, "25000") .build()); private final Iterable<PluginProperty> propertiesWithAVSInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Avschecker") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_AVS_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_CVV_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_ADDRESS1, "1600 Pennsylvania Ave NW") .put(AdyenPaymentPluginApi.PROPERTY_ADDRESS2, "") .put(AdyenPaymentPluginApi.PROPERTY_CITY, "Washington") .put(AdyenPaymentPluginApi.PROPERTY_STATE, "DC") .put(AdyenPaymentPluginApi.PROPERTY_ZIP, "20500") .put(AdyenPaymentPluginApi.PROPERTY_COUNTRY, DEFAULT_COUNTRY) .put(AdyenPaymentPluginApi.PROPERTY_USER_AGENT, "Java/1.8") .put(AdyenPaymentPluginApi.PROPERTY_ACCEPT_HEADER, "application/json") .put(AdyenPaymentPluginApi.PROPERTY_TERM_URL, "dummy://url") .build()); private final Iterable<PluginProperty> propertiesWithBadAVSInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Avschecker") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_AVS_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_CVV_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_ADDRESS1, "1600 Pennsylvania Ave NW") .put(AdyenPaymentPluginApi.PROPERTY_ADDRESS2, "") .put(AdyenPaymentPluginApi.PROPERTY_CITY, "Washington") .put(AdyenPaymentPluginApi.PROPERTY_STATE, "DC") .put(AdyenPaymentPluginApi.PROPERTY_ZIP, "20501") // zip is wrong .put(AdyenPaymentPluginApi.PROPERTY_COUNTRY, DEFAULT_COUNTRY) .put(AdyenPaymentPluginApi.PROPERTY_USER_AGENT, "Java/1.8") .put(AdyenPaymentPluginApi.PROPERTY_ACCEPT_HEADER, "application/json") .put(AdyenPaymentPluginApi.PROPERTY_TERM_URL, "dummy://url") .build()); private final Iterable<PluginProperty> propertiesWithZipCodeOnlyAVSInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Avschecker") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_AVS_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_CVV_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_ZIP, "20500") // only sending the zip code .put(AdyenPaymentPluginApi.PROPERTY_COUNTRY, DEFAULT_COUNTRY) .put(AdyenPaymentPluginApi.PROPERTY_USER_AGENT, "Java/1.8") .put(AdyenPaymentPluginApi.PROPERTY_ACCEPT_HEADER, "application/json") .put(AdyenPaymentPluginApi.PROPERTY_TERM_URL, "dummy://url") .build()); private Map<String, String> propertiesForRecurring; @Override @BeforeMethod(groups = "integration") public void setUpRemote() throws Exception { super.setUpRemote(); propertiesForRecurring = ImmutableMap.of(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID, UUID.randomUUID().toString(), AdyenPaymentPluginApi.PROPERTY_EMAIL, UUID.randomUUID().toString() + "@example.com"); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), false, ImmutableList.<PluginProperty>of(), context).size(), 0); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), true, ImmutableList.<PluginProperty>of(), context).size(), 0); } @Test(groups = "integration") public void testPaymentMethodManagement() throws Exception { final Iterable<PluginProperty> propertiesForAddPaymentMethod = PluginProperties.buildPluginProperties(propertiesForRecurring); adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesForAddPaymentMethod, context); // Verify the payment method is empty final List<PaymentMethodInfoPlugin> initialPaymentMethods = adyenPaymentPluginApi.getPaymentMethods(account.getId(), false, ImmutableList.<PluginProperty>of(), context); assertEquals(initialPaymentMethods.size(), 1); assertEquals(initialPaymentMethods.get(0).getAccountId(), account.getId()); assertEquals(initialPaymentMethods.get(0).getPaymentMethodId(), account.getPaymentMethodId()); assertNull(initialPaymentMethods.get(0).getExternalPaymentMethodId()); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), true, ImmutableList.<PluginProperty>of(), context), initialPaymentMethods); // Create the recurring contract final Iterable<PluginProperty> propertiesWithCCForRecurring = PluginProperties.merge(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "RECURRING") .build(), propertiesWithCCInfo); final Payment payment = doAuthorize(BigDecimal.TEN, propertiesWithCCForRecurring); doCapture(payment, BigDecimal.TEN); doRefund(payment, BigDecimal.TEN); // Sleep a few seconds to give Adyen's Test System time to process and create the RecurringDetails Thread.sleep(SLEEP_IN_MILLIS_FOR_RECURRING_DETAIL); // No change, unless refreshFromGateway is set assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), false, ImmutableList.<PluginProperty>of(), context), initialPaymentMethods); final List<PaymentMethodInfoPlugin> subsequentPaymentMethods = adyenPaymentPluginApi.getPaymentMethods(account.getId(), true, ImmutableList.<PluginProperty>of(), context); assertEquals(subsequentPaymentMethods.size(), 1); assertEquals(subsequentPaymentMethods.get(0).getAccountId(), account.getId()); assertEquals(subsequentPaymentMethods.get(0).getPaymentMethodId(), account.getPaymentMethodId()); // This points to the recurringDetailReference assertNotNull(subsequentPaymentMethods.get(0).getExternalPaymentMethodId()); // Verify the token can be used for recurring payments final Payment payment2 = doAuthorize(BigDecimal.TEN, ImmutableList.<PluginProperty>of()); doCapture(payment2, BigDecimal.TEN); doRefund(payment2, BigDecimal.TEN); // Verify the token can be used for an auto-capture recurring payment final Payment payment3 = doPurchase(BigDecimal.ONE, ImmutableList.<PluginProperty>of()); doRefund(payment3, BigDecimal.ONE); // Verify the token can be used for another recurring payment final Payment payment4 = doAuthorize(BigDecimal.ONE, ImmutableList.<PluginProperty>of()); doCapture(payment4, BigDecimal.ONE); doRefund(payment4, BigDecimal.ONE); adyenPaymentPluginApi.deletePaymentMethod(account.getId(), account.getPaymentMethodId(), ImmutableList.<PluginProperty>of(), context); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), false, ImmutableList.<PluginProperty>of(), context).size(), 0); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), true, ImmutableList.<PluginProperty>of(), context).size(), 0); } @Test(groups = "integration") public void testUnknownPayment() throws Exception { assertTrue(adyenPaymentPluginApi.getPaymentInfo(account.getId(), UUID.randomUUID(), ImmutableList.<PluginProperty>of(), context).isEmpty()); } @Test(groups = "integration") public void testAuthorizeAndCaptureSkipGw() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE, "skip_gw", "true", AdyenPaymentPluginApi.PROPERTY_PSP_REFERENCE, "test_psp_ref"))); PaymentTransactionInfoPlugin paymentTransactionInfoPlugin = adyenPaymentPluginApi.getPaymentInfo(account.getId(), payment.getId(), ImmutableList.of(), context).get(0); Assert.assertEquals("test_psp_ref", paymentTransactionInfoPlugin.getFirstPaymentReferenceId()); doCapture(payment, new BigDecimal("5"), ImmutableList.<PluginProperty>of(new PluginProperty("skip_gw", "true", false))); } @Test(groups = "integration") public void testAuthorizeAndMultipleCaptures() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE))); doCapture(payment, new BigDecimal("5")); doCapture(payment, new BigDecimal("5"), ImmutableList.<PluginProperty>of(new PluginProperty(PROPERTY_COUNTRY, "bogus", false))); } @Test(groups = "integration") public void testAuthorizeAndVoid() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE))); doVoid(payment); } @Test(groups = "integration") public void testAuthorizeOddCountryCodes() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); for (final String countryCode : ImmutableList.<String>of("GB", "UK", "QC", "CA")) { doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE, AdyenPaymentPluginApi.PROPERTY_COUNTRY, countryCode))); } } @Test(groups = "integration") public void testPurchaseAndRefund() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doPurchase(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE))); doRefund(payment, BigDecimal.TEN); } // Disabled by default since Card fund transfer (CFT) isn't enabled automatically on the sandbox @Test(groups = "integration", enabled = false) public void testCredit() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); doCredit(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE))); } @Test(groups = "integration") public void testAuthorizeAndMultipleCapturesSepaDirectDebit() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenPaymentMethodPluginSepaDirectDebit(), true, ImmutableList.<PluginProperty>of(), context); final Payment payment = doAuthorize(BigDecimal.TEN); doCapture(payment, new BigDecimal("5")); doCapture(payment, new BigDecimal("5")); } @Test(groups = "integration") public void testAuthorizeAndMultipleCapturesELV() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenPaymentMethodPluginELV(), true, ImmutableList.<PluginProperty>of(), context); final Payment payment = doAuthorize(BigDecimal.TEN); doCapture(payment, new BigDecimal("5")); doCapture(payment, new BigDecimal("5")); } @Test(groups = "integration") public void testAuthorizeFailingInvalidCVV() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, "1234")), context); assertEquals(authorizationInfoPlugin.getGatewayError(), "CVC Declined"); final List<PaymentTransactionInfoPlugin> fromDBList = adyenPaymentPluginApi.getPaymentInfo(account.getId(), payment.getId(), ImmutableList.<PluginProperty>of(), context); assertFalse(fromDBList.isEmpty()); assertEquals(fromDBList.get(0).getGatewayError(), "CVC Declined"); } @Test(groups = "integration") public void testAuthorizeRecurringDetailRecurring() throws Exception { final Iterable<PluginProperty> propertiesWithCCForRecurring = PluginProperties.buildPluginProperties(propertiesForRecurring); adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCForRecurring, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.merge(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE, AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "RECURRING"), propertiesWithCCInfo)); doCapture(payment, BigDecimal.TEN); doRefund(payment, BigDecimal.TEN); // Sleep a few seconds to give Adyen's Test System time to process and create the RecurringDetails Thread.sleep(SLEEP_IN_MILLIS_FOR_RECURRING_DETAIL); final List<RecurringDetail> recurringDetailList = adyenRecurringClient.getRecurringDetailList(propertiesForRecurring.get(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID), adyenConfigProperties.getMerchantAccount(DEFAULT_COUNTRY), "RECURRING"); if (recurringDetailList.isEmpty()) { fail("No recurring details for " + propertiesForRecurring.get(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID)); } final Iterable<PluginProperty> propertiesWithRecurringDetailInfo = PluginProperties.merge(ImmutableMap.<String, String>builder() .putAll(propertiesForRecurring) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_DETAIL_ID, recurringDetailList.get(0).getRecurringDetailReference()) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "RECURRING") .build()); final Payment payment2 = doAuthorize(BigDecimal.TEN, propertiesWithRecurringDetailInfo); doCapture(payment2, BigDecimal.TEN); doRefund(payment2, BigDecimal.TEN); } @Test(groups = "integration") public void testAuthorizeRecurringDetailOneClick() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, ImmutableList.<PluginProperty>of(), context); final Iterable<PluginProperty> propertiesWithCCForRecurring = PluginProperties.merge(ImmutableMap.<String, String>builder() .putAll(propertiesForRecurring) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "ONECLICK") .build(), propertiesWithCCInfo); final Payment payment = doAuthorize(BigDecimal.TEN, propertiesWithCCForRecurring); doCapture(payment, BigDecimal.TEN); doRefund(payment, BigDecimal.TEN); // Sleep a few seconds to give Adyen's Test System time to process and create the RecurringDetails Thread.sleep(SLEEP_IN_MILLIS_FOR_RECURRING_DETAIL); final List<RecurringDetail> recurringDetailList = adyenRecurringClient.getRecurringDetailList(propertiesForRecurring.get(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID), adyenConfigProperties.getMerchantAccount(DEFAULT_COUNTRY), "ONECLICK"); if (recurringDetailList.isEmpty()) { fail("No recurring details for " + propertiesForRecurring.get(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID)); } final Iterable<PluginProperty> propertiesWithRecurringDetailInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .putAll(propertiesForRecurring) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_DETAIL_ID, recurringDetailList.get(0).getRecurringDetailReference()) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "ONECLICK") .build()); final Payment payment2 = doAuthorize(BigDecimal.TEN, propertiesWithRecurringDetailInfo); doCapture(payment2, BigDecimal.TEN); doRefund(payment2, BigDecimal.TEN); } @Test(groups = "integration") public void testAuthorizeWithContinuousAuthentication() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CONTINUOUS_AUTHENTICATION, "true"))); doCapture(payment, BigDecimal.TEN); doRefund(payment, BigDecimal.TEN); } @Test(groups = "integration") public void testAuthorizeAndCheckAVSResult() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithAVSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin1 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWithAVSInfo, context); assertNull(authorizationInfoPlugin1.getGatewayErrorCode()); assertEquals(authorizationInfoPlugin1.getStatus(), PaymentPluginStatus.PROCESSED); final String avsResult = PluginProperties.findPluginPropertyValue("avsResult", authorizationInfoPlugin1.getProperties()); final String avsResultCode = PluginProperties.findPluginPropertyValue("avsResultCode", authorizationInfoPlugin1.getProperties()); assertEquals(avsResultCode, "Y"); assertEquals(avsResult, "7 Both postal code and address match"); } @Test(groups = "integration") public void testAuthorizeAndCheckBadAVSResult() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithAVSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin1 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWithBadAVSInfo, context); assertNull(authorizationInfoPlugin1.getGatewayErrorCode()); assertEquals(authorizationInfoPlugin1.getStatus(), PaymentPluginStatus.PROCESSED); final String avsResult = PluginProperties.findPluginPropertyValue("avsResult", authorizationInfoPlugin1.getProperties()); final String avsResultCode = PluginProperties.findPluginPropertyValue("avsResultCode", authorizationInfoPlugin1.getProperties()); assertEquals(avsResultCode, "A"); assertEquals(avsResult, "1 Address matches, postal code doesn't"); } @Test(groups = "integration") public void testAuthorizeWithZipCodeOnlyAVSCheck() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithZipCodeOnlyAVSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin1 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWithZipCodeOnlyAVSInfo, context); assertNull(authorizationInfoPlugin1.getGatewayErrorCode()); assertEquals(authorizationInfoPlugin1.getStatus(), PaymentPluginStatus.PROCESSED); final String avsResult = PluginProperties.findPluginPropertyValue("avsResult", authorizationInfoPlugin1.getProperties()); final String avsResultCode = PluginProperties.findPluginPropertyValue("avsResultCode", authorizationInfoPlugin1.getProperties()); assertEquals(avsResultCode, "Z"); assertEquals(avsResult, "6 Postal code matches, address doesn't match"); } @Test(groups = "integration") public void testAuthorizeAndComplete3DSecure() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWith3DSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransaction captureTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.CAPTURE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin1 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWith3DSInfo, context); assertNull(authorizationInfoPlugin1.getGatewayErrorCode()); assertEquals(authorizationInfoPlugin1.getStatus(), PaymentPluginStatus.PENDING); final String expectedMerchantAccount = getExpectedMerchantAccount(payment); final PaymentTransactionInfoPlugin paymentInfo = Iterables.getLast(adyenPaymentPluginApi.getPaymentInfo(payment.getAccountId(), payment.getId(), null, context)); assertEquals(PluginProperties.findPluginPropertyValue("merchantAccountCode", paymentInfo.getProperties()), expectedMerchantAccount); // Verify GET path final List<PaymentTransactionInfoPlugin> paymentTransactionInfoPluginsPreCompletion = adyenPaymentPluginApi.getPaymentInfo(account.getId(), authorizationInfoPlugin1.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); assertEquals(paymentTransactionInfoPluginsPreCompletion.size(), 1); assertEquals(paymentTransactionInfoPluginsPreCompletion.get(0).getTransactionType(), TransactionType.AUTHORIZE); assertEquals(paymentTransactionInfoPluginsPreCompletion.get(0).getStatus(), PaymentPluginStatus.PENDING); final URL issuerUrl = new URL(PluginProperties.findPluginPropertyValue("issuerUrl", authorizationInfoPlugin1.getProperties())); final String md = PluginProperties.findPluginPropertyValue("MD", authorizationInfoPlugin1.getProperties()); final String paReq = PluginProperties.findPluginPropertyValue("PaReq", authorizationInfoPlugin1.getProperties()); final String termUrl = PluginProperties.findPluginPropertyValue("TermUrl", authorizationInfoPlugin1.getProperties()); final String responseHTML = given().log().all() .contentType(ContentType.URLENC) .accept(ContentType.HTML) .formParam("MD", md) .formParam("PaReq", paReq) .formParam("TermUrl", termUrl) .post(issuerUrl) .then().log().all() .statusCode(HTTP_200_OK) .extract().asString(); final Map<String, String> formParams = extractForm(responseHTML); assertFalse(formParams.isEmpty(), "No FORM found in HTML response"); final String formAction = rewriteFormURL(issuerUrl, formParams.remove("formAction")); formParams.put("username", "user"); formParams.put("password", "password"); final String redirectHTML = given().log().all() .contentType(ContentType.URLENC) .accept(ContentType.HTML) .formParams(formParams) .post(formAction) .then().log().all() .statusCode(HTTP_200_OK) .extract().asString(); final Map<String, String> redirectFormParams = extractForm(redirectHTML); assertFalse(redirectFormParams.isEmpty(), "No FORM found in redirect HTML response"); assertEquals(termUrl, redirectFormParams.remove("formAction")); // simulate url encoding that happens in the KillBill Client redirectFormParams.put("MD", UTF8UrlEncoder.encodeQueryElement(redirectFormParams.get("MD"))); redirectFormParams.put("PaRes", UTF8UrlEncoder.encodeQueryElement(redirectFormParams.get("PaRes"))); final List<PluginProperty> propertiesWithCompleteParams = PluginProperties.buildPluginProperties(redirectFormParams); final PaymentTransactionInfoPlugin authorizationInfoPlugin2 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWithCompleteParams, context); verifyPaymentTransactionInfoPlugin(payment, authorizationTransaction, authorizationInfoPlugin2); assertEquals(authorizationInfoPlugin2.getFirstPaymentReferenceId(), authorizationInfoPlugin1.getFirstPaymentReferenceId()); // Verify GET path final List<PaymentTransactionInfoPlugin> paymentTransactionInfoPluginsPostCompletion = adyenPaymentPluginApi.getPaymentInfo(account.getId(), authorizationInfoPlugin1.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); assertEquals(paymentTransactionInfoPluginsPostCompletion.size(), 1); assertEquals(paymentTransactionInfoPluginsPostCompletion.get(0).getTransactionType(), TransactionType.AUTHORIZE); assertEquals(paymentTransactionInfoPluginsPostCompletion.get(0).getStatus(), PaymentPluginStatus.PROCESSED); final PaymentTransactionInfoPlugin captureInfoPlugin = adyenPaymentPluginApi.capturePayment(account.getId(), payment.getId(), captureTransaction.getId(), account.getPaymentMethodId(), captureTransaction.getAmount(), captureTransaction.getCurrency(), authorizationInfoPlugin2.getProperties(), context); verifyPaymentTransactionInfoPlugin(payment, captureTransaction, captureInfoPlugin); // Verify GET path final List<PaymentTransactionInfoPlugin> paymentTransactionInfoPluginsPostCapture = adyenPaymentPluginApi.getPaymentInfo(account.getId(), authorizationInfoPlugin1.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); assertEquals(paymentTransactionInfoPluginsPostCapture.size(), 2); assertEquals(paymentTransactionInfoPluginsPostCapture.get(0).getTransactionType(), TransactionType.AUTHORIZE); assertEquals(paymentTransactionInfoPluginsPostCapture.get(0).getStatus(), PaymentPluginStatus.PROCESSED); assertEquals(paymentTransactionInfoPluginsPostCapture.get(1).getTransactionType(), TransactionType.CAPTURE); assertEquals(paymentTransactionInfoPluginsPostCapture.get(1).getStatus(), PaymentPluginStatus.PENDING); } @Test(groups = "integration") public void testAuthorizeAndExpire3DSecure() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWith3DSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWith3DSInfo, context); assertEquals(authorizationInfoPlugin.getStatus(), PaymentPluginStatus.PENDING); final Period expirationPeriod = adyenConfigProperties.getPending3DsPaymentExpirationPeriod().plusMinutes(1); clock.setDeltaFromReality(expirationPeriod.toStandardDuration().getMillis()); final List<PaymentTransactionInfoPlugin> expiredPaymentTransactions = adyenPaymentPluginApi.getPaymentInfo(account.getId(), authorizationInfoPlugin.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); assertEquals(expiredPaymentTransactions.size(), 1); final PaymentTransactionInfoPlugin canceledTransaction = expiredPaymentTransactions.get(0); assertEquals(canceledTransaction.getTransactionType(), TransactionType.AUTHORIZE); assertEquals(canceledTransaction.getStatus(), PaymentPluginStatus.CANCELED); } @Test(groups = "integration") public void testAuthorizeAndCaptureWithSplitSettlements() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>(); builder.put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE); builder.put(String.format("%s.1.amount", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "3.51"); builder.put(String.format("%s.1.group", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "MENSWEAR"); builder.put(String.format("%s.1.reference", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), UUID.randomUUID().toString()); builder.put(String.format("%s.1.type", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "FOOTWEAR"); builder.put(String.format("%s.2.amount", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "6.49"); builder.put(String.format("%s.2.group", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "STREETWEAR"); builder.put(String.format("%s.2.reference", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), UUID.randomUUID().toString()); builder.put(String.format("%s.2.type", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "HEADWEAR"); final Map<String, String> pluginPropertiesMap = builder.build(); final List<PluginProperty> pluginProperties = PluginProperties.buildPluginProperties(pluginPropertiesMap); final Payment payment = doAuthorize(BigDecimal.TEN, pluginProperties); doCapture(payment, BigDecimal.TEN); } private Map<String, String> extractForm(final String html) { final Map<String, String> fields = new HashMap<String, String>(); final Document doc = Jsoup.parse(html); final Elements forms = doc.getElementsByTag("form"); for (final Element form : forms) { if ("post".equalsIgnoreCase(form.attr("method"))) { fields.put("formAction", form.attr("action")); final Elements inputs = form.getElementsByTag("input"); for (final Element input : inputs) { final String value = input.val(); if (value != null && !value.isEmpty() && !"Submit".equalsIgnoreCase(value)) { fields.put(input.attr("name"), value); } } return fields; } } return Collections.emptyMap(); } private String rewriteFormURL(final URL issuerUrl, final String formAction) { if (formAction.startsWith("http")) { return formAction; } else { return issuerUrl.getProtocol() + "://" + issuerUrl.getHost() + (issuerUrl.getPort() != HTTP_PORT && issuerUrl.getPort() != HTTPS_PORT ? ":" + issuerUrl.getPort() : "") + formAction; } } private Payment doAuthorize(final BigDecimal amount) throws PaymentPluginApiException, PaymentApiException { return doAuthorize(amount, ImmutableList.<PluginProperty>of()); } private Payment doAuthorize(final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException, PaymentApiException { return doPluginCall(amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doPurchase(final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException, PaymentApiException { return doPluginCall(amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.purchasePayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doCredit(final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException, PaymentApiException { return doPluginCall(amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.creditPayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doCapture(final Payment payment, final BigDecimal amount) throws PaymentPluginApiException { return doCapture(payment, amount, ImmutableList.<PluginProperty>of()); } private Payment doCapture(final Payment payment, final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return doPluginCall(payment, amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.capturePayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doRefund(final Payment payment, final BigDecimal amount) throws PaymentPluginApiException { return doRefund(payment, amount, ImmutableList.<PluginProperty>of()); } private Payment doRefund(final Payment payment, final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return doPluginCall(payment, amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.refundPayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doVoid(final Payment payment) throws PaymentPluginApiException { return doVoid(payment, ImmutableList.<PluginProperty>of()); } private Payment doVoid(final Payment payment, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return doPluginCall(payment, null, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.voidPayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), pluginProperties, context); } }); } private Payment doPluginCall(final BigDecimal amount, final Iterable<PluginProperty> pluginProperties, final PluginCall pluginCall) throws PaymentPluginApiException, PaymentApiException { final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); return doPluginCall(payment, amount, pluginProperties, pluginCall); } private Payment doPluginCall(final Payment payment, final BigDecimal amount, final Iterable<PluginProperty> pluginProperties, final PluginCall pluginCall) throws PaymentPluginApiException { final PaymentTransaction paymentTransaction = TestUtils.buildPaymentTransaction(payment, null, amount, payment.getCurrency()); final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin = pluginCall.execute(payment, paymentTransaction, pluginProperties); TestUtils.updatePaymentTransaction(paymentTransaction, paymentTransactionInfoPlugin); verifyPaymentTransactionInfoPlugin(payment, paymentTransaction, paymentTransactionInfoPlugin); if ("true".equals(PluginProperties.findPluginPropertyValue("skip_gw", pluginProperties))) { return payment; } if (paymentTransactionInfoPlugin.getTransactionType() == TransactionType.AUTHORIZE || paymentTransactionInfoPlugin.getTransactionType() == TransactionType.PURCHASE) { // Authorization are synchronous assertEquals(paymentTransactionInfoPlugin.getStatus(), PaymentPluginStatus.PROCESSED); } else { assertEquals(paymentTransactionInfoPlugin.getStatus(), PaymentPluginStatus.PENDING); } processNotification(TRANSACTION_TYPE_TO_EVENT_CODE.get(paymentTransaction.getTransactionType()), true, paymentTransaction.getExternalKey(), paymentTransactionInfoPlugin.getFirstPaymentReferenceId()); assertEquals(paymentTransaction.getPaymentInfoPlugin().getStatus(), PaymentPluginStatus.PROCESSED); final String expectedMerchantAccount = getExpectedMerchantAccount(payment); final PaymentTransactionInfoPlugin refreshedTransactionInfo = Iterables.getLast(adyenPaymentPluginApi.getPaymentInfo(payment.getAccountId(), payment.getId(), null, context)); assertEquals(PluginProperties.findPluginPropertyValue("merchantAccountCode", refreshedTransactionInfo.getProperties()), expectedMerchantAccount); return payment; } private String getExpectedMerchantAccount(final Payment payment) { final Account paymentAccount; try { paymentAccount = this.killbillApi.getAccountUserApi().getAccountById(payment.getAccountId(), context); } catch (AccountApiException e) { throw new RuntimeException(e); } return adyenConfigProperties.getMerchantAccount(paymentAccount.getCountry()); } private void verifyPaymentTransactionInfoPlugin(final Payment payment, final PaymentTransaction paymentTransaction, final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin) throws PaymentPluginApiException { verifyPaymentTransactionInfoPlugin(payment, paymentTransaction, paymentTransactionInfoPlugin, true); // Verify we can fetch the details final List<PaymentTransactionInfoPlugin> paymentTransactionInfoPlugins = adyenPaymentPluginApi.getPaymentInfo(account.getId(), paymentTransactionInfoPlugin.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); final PaymentTransactionInfoPlugin paymentTransactionInfoPluginFetched = Iterables.<PaymentTransactionInfoPlugin>find(Lists.<PaymentTransactionInfoPlugin>reverse(paymentTransactionInfoPlugins), new Predicate<PaymentTransactionInfoPlugin>() { @Override public boolean apply(final PaymentTransactionInfoPlugin input) { return input.getKbTransactionPaymentId().equals(paymentTransaction.getId()); } }); verifyPaymentTransactionInfoPlugin(payment, paymentTransaction, paymentTransactionInfoPluginFetched, true); } private void verifyPaymentTransactionInfoPlugin(final Payment payment, final PaymentTransaction paymentTransaction, final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin, final boolean authorizedProcessed) { assertEquals(paymentTransactionInfoPlugin.getKbPaymentId(), payment.getId()); assertEquals(paymentTransactionInfoPlugin.getKbTransactionPaymentId(), paymentTransaction.getId()); assertEquals(paymentTransactionInfoPlugin.getTransactionType(), paymentTransaction.getTransactionType()); if (TransactionType.VOID.equals(paymentTransaction.getTransactionType())) { assertNull(paymentTransactionInfoPlugin.getAmount()); assertNull(paymentTransactionInfoPlugin.getCurrency()); } else { assertEquals(paymentTransactionInfoPlugin.getAmount().compareTo(paymentTransaction.getAmount()), 0); assertEquals(paymentTransactionInfoPlugin.getCurrency(), paymentTransaction.getCurrency()); } assertNotNull(paymentTransactionInfoPlugin.getCreatedDate()); assertNotNull(paymentTransactionInfoPlugin.getEffectiveDate()); final List<PaymentPluginStatus> expectedPaymentPluginStatus; switch (paymentTransaction.getTransactionType()) { case PURCHASE: case AUTHORIZE: expectedPaymentPluginStatus = authorizedProcessed ? ImmutableList.of(PaymentPluginStatus.PROCESSED) : ImmutableList.of(PaymentPluginStatus.PROCESSED, PaymentPluginStatus.PENDING); break; case CAPTURE: expectedPaymentPluginStatus = ImmutableList.of(PaymentPluginStatus.PENDING); break; case REFUND: expectedPaymentPluginStatus = ImmutableList.of(PaymentPluginStatus.PENDING); break; case VOID: expectedPaymentPluginStatus = ImmutableList.of(PaymentPluginStatus.PENDING); break; default: expectedPaymentPluginStatus = ImmutableList.of(PaymentPluginStatus.PENDING); break; } if ("skip_gw".equals(paymentTransactionInfoPlugin.getGatewayError()) || "true".equals(PluginProperties.findPluginPropertyValue("skipGw", paymentTransactionInfoPlugin.getProperties()))) { assertNull(paymentTransactionInfoPlugin.getGatewayErrorCode()); assertEquals(paymentTransactionInfoPlugin.getStatus(), PaymentPluginStatus.PROCESSED); } else { assertNull(paymentTransactionInfoPlugin.getGatewayErrorCode()); assertTrue(expectedPaymentPluginStatus.contains(paymentTransactionInfoPlugin.getStatus()), "was: " + paymentTransactionInfoPlugin.getStatus()); assertNull(paymentTransactionInfoPlugin.getGatewayError()); assertNotNull(paymentTransactionInfoPlugin.getFirstPaymentReferenceId()); // NULL for subsequent transactions (modifications) //Assert.assertNotNull(paymentTransactionInfoPlugin.getSecondPaymentReferenceId()); } } private PaymentMethodPlugin adyenEmptyPaymentMethodPlugin() { return adyenPaymentMethodPlugin(account.getPaymentMethodId().toString(), null); } private PaymentMethodPlugin adyenPaymentMethodPluginSepaDirectDebit() { return adyenPaymentMethodPlugin(account.getPaymentMethodId().toString(), "{" + '"' + PROPERTY_DD_HOLDER_NAME + "\":\"" + DD_HOLDER_NAME + "\"," + '"' + PROPERTY_DD_ACCOUNT_NUMBER + "\":\"" + DD_IBAN + "\"," + '"' + PROPERTY_DD_BANK_IDENTIFIER_CODE + "\":\"" + DD_BIC + '"' + '}'); } private PaymentMethodPlugin adyenPaymentMethodPluginELV() { return adyenPaymentMethodPlugin(account.getPaymentMethodId().toString(), "{" + '"' + PROPERTY_DD_HOLDER_NAME + "\":\"" + DD_HOLDER_NAME + "\"," + '"' + PROPERTY_DD_ACCOUNT_NUMBER + "\":\"" + ELV_KONTONUMMER + "\"," + '"' + PROPERTY_ELV_BLZ + "\":\"" + ELV_BANKLEITZAHL + '"' + '}'); } private static PaymentMethodPlugin adyenPaymentMethodPlugin(final String paymentMethodId, final String additionalData) { final AdyenPaymentMethodsRecord record = new AdyenPaymentMethodsRecord(); record.setKbPaymentMethodId(paymentMethodId); record.setIsDefault(AdyenDao.TRUE); if (!Strings.isNullOrEmpty(additionalData)) { record.setAdditionalData(additionalData); } return new AdyenPaymentMethodPlugin(record); } private interface PluginCall { PaymentTransactionInfoPlugin execute(Payment payment, PaymentTransaction paymentTransaction, Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException; } }
src/test/java/org/killbill/billing/plugin/adyen/api/TestAdyenPaymentPluginApi.java
/* * Copyright 2014-2018 Groupon, Inc * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project 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.killbill.billing.plugin.adyen.api; import java.math.BigDecimal; import java.net.URL; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.joda.time.Period; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import org.killbill.adyen.recurring.RecurringDetail; import org.killbill.billing.account.api.Account; import org.killbill.billing.account.api.AccountApiException; import org.killbill.billing.payment.api.Payment; import org.killbill.billing.payment.api.PaymentApiException; import org.killbill.billing.payment.api.PaymentMethodPlugin; import org.killbill.billing.payment.api.PaymentTransaction; import org.killbill.billing.payment.api.PluginProperty; import org.killbill.billing.payment.api.TransactionType; import org.killbill.billing.payment.plugin.api.PaymentMethodInfoPlugin; import org.killbill.billing.payment.plugin.api.PaymentPluginApiException; import org.killbill.billing.payment.plugin.api.PaymentPluginStatus; import org.killbill.billing.payment.plugin.api.PaymentTransactionInfoPlugin; import org.killbill.billing.plugin.TestUtils; import org.killbill.billing.plugin.adyen.dao.AdyenDao; import org.killbill.billing.plugin.adyen.dao.gen.tables.records.AdyenPaymentMethodsRecord; import org.killbill.billing.plugin.api.PluginProperties; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.ning.http.util.UTF8UrlEncoder; import com.google.common.base.Predicate; import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Iterables; import com.google.common.collect.Lists; import com.jayway.restassured.http.ContentType; import static com.jayway.restassured.RestAssured.given; import static org.killbill.billing.plugin.adyen.api.AdyenPaymentPluginApi.PROPERTY_DD_ACCOUNT_NUMBER; import static org.killbill.billing.plugin.adyen.api.AdyenPaymentPluginApi.PROPERTY_DD_BANK_IDENTIFIER_CODE; import static org.killbill.billing.plugin.adyen.api.AdyenPaymentPluginApi.PROPERTY_DD_HOLDER_NAME; import static org.killbill.billing.plugin.adyen.api.AdyenPaymentPluginApi.PROPERTY_ELV_BLZ; import static org.killbill.billing.plugin.api.payment.PluginPaymentPluginApi.PROPERTY_COUNTRY; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertNotNull; import static org.testng.Assert.assertNull; import static org.testng.Assert.assertTrue; import static org.testng.Assert.fail; public class TestAdyenPaymentPluginApi extends TestAdyenPaymentPluginApiBase { private static final long SLEEP_IN_MILLIS_FOR_RECURRING_DETAIL = 3000L; // 3 Seconds private static final int HTTP_200_OK = 200; private static final int HTTP_PORT = 80; private static final int HTTPS_PORT = 443; private static final Map<TransactionType, String> TRANSACTION_TYPE_TO_EVENT_CODE = ImmutableMap.<TransactionType, String>builder().put(TransactionType.VOID, "CANCELLATION") .put(TransactionType.REFUND, "REFUND") .put(TransactionType.CAPTURE, "CAPTURE") .put(TransactionType.CREDIT, "REFUND_WITH_DATA") .put(TransactionType.CHARGEBACK, "CHARGEBACK") .put(TransactionType.AUTHORIZE, "AUTHORISATION") .put(TransactionType.PURCHASE, "AUTHORISATION") .build(); private final Iterable<PluginProperty> propertiesWithCCInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Dupont") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .build()); private final Iterable<PluginProperty> propertiesWith3DSInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Montblanc") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_3DS_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_3DS_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_USER_AGENT, "Java/1.8") .put(AdyenPaymentPluginApi.PROPERTY_ACCEPT_HEADER, "application/json") .put(AdyenPaymentPluginApi.PROPERTY_TERM_URL, "dummy://url") .put(AdyenPaymentPluginApi.PROPERTY_THREE_D_THRESHOLD, "25000") .build()); private final Iterable<PluginProperty> propertiesWithAVSInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Avschecker") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_AVS_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_CVV_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_ADDRESS1, "1600 Pennsylvania Ave NW") .put(AdyenPaymentPluginApi.PROPERTY_ADDRESS2, "") .put(AdyenPaymentPluginApi.PROPERTY_CITY, "Washington") .put(AdyenPaymentPluginApi.PROPERTY_STATE, "DC") .put(AdyenPaymentPluginApi.PROPERTY_ZIP, "20500") .put(AdyenPaymentPluginApi.PROPERTY_COUNTRY, DEFAULT_COUNTRY) .put(AdyenPaymentPluginApi.PROPERTY_USER_AGENT, "Java/1.8") .put(AdyenPaymentPluginApi.PROPERTY_ACCEPT_HEADER, "application/json") .put(AdyenPaymentPluginApi.PROPERTY_TERM_URL, "dummy://url") .build()); private final Iterable<PluginProperty> propertiesWithBadAVSInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Avschecker") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_AVS_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_CVV_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_ADDRESS1, "1600 Pennsylvania Ave NW") .put(AdyenPaymentPluginApi.PROPERTY_ADDRESS2, "") .put(AdyenPaymentPluginApi.PROPERTY_CITY, "Washington") .put(AdyenPaymentPluginApi.PROPERTY_STATE, "DC") .put(AdyenPaymentPluginApi.PROPERTY_ZIP, "20501") // zip is wrong .put(AdyenPaymentPluginApi.PROPERTY_COUNTRY, DEFAULT_COUNTRY) .put(AdyenPaymentPluginApi.PROPERTY_USER_AGENT, "Java/1.8") .put(AdyenPaymentPluginApi.PROPERTY_ACCEPT_HEADER, "application/json") .put(AdyenPaymentPluginApi.PROPERTY_TERM_URL, "dummy://url") .build()); private final Iterable<PluginProperty> propertiesWithZipCodeOnlyAVSInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_TYPE, CC_TYPE) .put(AdyenPaymentPluginApi.PROPERTY_CC_LAST_NAME, "Avschecker") .put(AdyenPaymentPluginApi.PROPERTY_CC_NUMBER, CC_AVS_NUMBER) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_MONTH, String.valueOf(CC_EXPIRATION_MONTH)) .put(AdyenPaymentPluginApi.PROPERTY_CC_EXPIRATION_YEAR, String.valueOf(CC_EXPIRATION_YEAR)) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_CVV_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_ZIP, "20500") // only sending the zip code .put(AdyenPaymentPluginApi.PROPERTY_COUNTRY, DEFAULT_COUNTRY) .put(AdyenPaymentPluginApi.PROPERTY_USER_AGENT, "Java/1.8") .put(AdyenPaymentPluginApi.PROPERTY_ACCEPT_HEADER, "application/json") .put(AdyenPaymentPluginApi.PROPERTY_TERM_URL, "dummy://url") .build()); private Map<String, String> propertiesForRecurring; @Override @BeforeMethod(groups = "integration") public void setUpRemote() throws Exception { super.setUpRemote(); propertiesForRecurring = ImmutableMap.of(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID, UUID.randomUUID().toString(), AdyenPaymentPluginApi.PROPERTY_EMAIL, UUID.randomUUID().toString() + "@example.com"); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), false, ImmutableList.<PluginProperty>of(), context).size(), 0); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), true, ImmutableList.<PluginProperty>of(), context).size(), 0); } @Test(groups = "integration") public void testPaymentMethodManagement() throws Exception { final Iterable<PluginProperty> propertiesForAddPaymentMethod = PluginProperties.buildPluginProperties(propertiesForRecurring); adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesForAddPaymentMethod, context); // Verify the payment method is empty final List<PaymentMethodInfoPlugin> initialPaymentMethods = adyenPaymentPluginApi.getPaymentMethods(account.getId(), false, ImmutableList.<PluginProperty>of(), context); assertEquals(initialPaymentMethods.size(), 1); assertEquals(initialPaymentMethods.get(0).getAccountId(), account.getId()); assertEquals(initialPaymentMethods.get(0).getPaymentMethodId(), account.getPaymentMethodId()); assertNull(initialPaymentMethods.get(0).getExternalPaymentMethodId()); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), true, ImmutableList.<PluginProperty>of(), context), initialPaymentMethods); // Create the recurring contract final Iterable<PluginProperty> propertiesWithCCForRecurring = PluginProperties.merge(ImmutableMap.<String, String>builder() .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "RECURRING") .build(), propertiesWithCCInfo); final Payment payment = doAuthorize(BigDecimal.TEN, propertiesWithCCForRecurring); doCapture(payment, BigDecimal.TEN); doRefund(payment, BigDecimal.TEN); // Sleep a few seconds to give Adyen's Test System time to process and create the RecurringDetails Thread.sleep(SLEEP_IN_MILLIS_FOR_RECURRING_DETAIL); // No change, unless refreshFromGateway is set assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), false, ImmutableList.<PluginProperty>of(), context), initialPaymentMethods); final List<PaymentMethodInfoPlugin> subsequentPaymentMethods = adyenPaymentPluginApi.getPaymentMethods(account.getId(), true, ImmutableList.<PluginProperty>of(), context); assertEquals(subsequentPaymentMethods.size(), 1); assertEquals(subsequentPaymentMethods.get(0).getAccountId(), account.getId()); assertEquals(subsequentPaymentMethods.get(0).getPaymentMethodId(), account.getPaymentMethodId()); // This points to the recurringDetailReference assertNotNull(subsequentPaymentMethods.get(0).getExternalPaymentMethodId()); // Verify the token can be used for recurring payments final Payment payment2 = doAuthorize(BigDecimal.TEN, ImmutableList.<PluginProperty>of()); doCapture(payment2, BigDecimal.TEN); doRefund(payment2, BigDecimal.TEN); // Verify the token can be used for an auto-capture recurring payment final Payment payment3 = doPurchase(BigDecimal.ONE, ImmutableList.<PluginProperty>of()); doRefund(payment3, BigDecimal.ONE); // Verify the token can be used for another recurring payment final Payment payment4 = doAuthorize(BigDecimal.ONE, ImmutableList.<PluginProperty>of()); doCapture(payment4, BigDecimal.ONE); doRefund(payment4, BigDecimal.ONE); adyenPaymentPluginApi.deletePaymentMethod(account.getId(), account.getPaymentMethodId(), ImmutableList.<PluginProperty>of(), context); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), false, ImmutableList.<PluginProperty>of(), context).size(), 0); assertEquals(adyenPaymentPluginApi.getPaymentMethods(account.getId(), true, ImmutableList.<PluginProperty>of(), context).size(), 0); } @Test(groups = "integration") public void testUnknownPayment() throws Exception { assertTrue(adyenPaymentPluginApi.getPaymentInfo(account.getId(), UUID.randomUUID(), ImmutableList.<PluginProperty>of(), context).isEmpty()); } @Test(groups = "integration") public void testAuthorizeAndCaptureSkipGw() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE, "skip_gw", "true"))); doCapture(payment, new BigDecimal("5"), ImmutableList.<PluginProperty>of(new PluginProperty("skip_gw", "true", false))); } @Test(groups = "integration") public void testAuthorizeAndMultipleCaptures() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE))); doCapture(payment, new BigDecimal("5")); doCapture(payment, new BigDecimal("5"), ImmutableList.<PluginProperty>of(new PluginProperty(PROPERTY_COUNTRY, "bogus", false))); } @Test(groups = "integration") public void testAuthorizeAndVoid() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE))); doVoid(payment); } @Test(groups = "integration") public void testAuthorizeOddCountryCodes() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); for (final String countryCode : ImmutableList.<String>of("GB", "UK", "QC", "CA")) { doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE, AdyenPaymentPluginApi.PROPERTY_COUNTRY, countryCode))); } } @Test(groups = "integration") public void testPurchaseAndRefund() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doPurchase(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE))); doRefund(payment, BigDecimal.TEN); } // Disabled by default since Card fund transfer (CFT) isn't enabled automatically on the sandbox @Test(groups = "integration", enabled = false) public void testCredit() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); doCredit(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE))); } @Test(groups = "integration") public void testAuthorizeAndMultipleCapturesSepaDirectDebit() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenPaymentMethodPluginSepaDirectDebit(), true, ImmutableList.<PluginProperty>of(), context); final Payment payment = doAuthorize(BigDecimal.TEN); doCapture(payment, new BigDecimal("5")); doCapture(payment, new BigDecimal("5")); } @Test(groups = "integration") public void testAuthorizeAndMultipleCapturesELV() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenPaymentMethodPluginELV(), true, ImmutableList.<PluginProperty>of(), context); final Payment payment = doAuthorize(BigDecimal.TEN); doCapture(payment, new BigDecimal("5")); doCapture(payment, new BigDecimal("5")); } @Test(groups = "integration") public void testAuthorizeFailingInvalidCVV() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, "1234")), context); assertEquals(authorizationInfoPlugin.getGatewayError(), "CVC Declined"); final List<PaymentTransactionInfoPlugin> fromDBList = adyenPaymentPluginApi.getPaymentInfo(account.getId(), payment.getId(), ImmutableList.<PluginProperty>of(), context); assertFalse(fromDBList.isEmpty()); assertEquals(fromDBList.get(0).getGatewayError(), "CVC Declined"); } @Test(groups = "integration") public void testAuthorizeRecurringDetailRecurring() throws Exception { final Iterable<PluginProperty> propertiesWithCCForRecurring = PluginProperties.buildPluginProperties(propertiesForRecurring); adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCForRecurring, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.merge(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE, AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "RECURRING"), propertiesWithCCInfo)); doCapture(payment, BigDecimal.TEN); doRefund(payment, BigDecimal.TEN); // Sleep a few seconds to give Adyen's Test System time to process and create the RecurringDetails Thread.sleep(SLEEP_IN_MILLIS_FOR_RECURRING_DETAIL); final List<RecurringDetail> recurringDetailList = adyenRecurringClient.getRecurringDetailList(propertiesForRecurring.get(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID), adyenConfigProperties.getMerchantAccount(DEFAULT_COUNTRY), "RECURRING"); if (recurringDetailList.isEmpty()) { fail("No recurring details for " + propertiesForRecurring.get(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID)); } final Iterable<PluginProperty> propertiesWithRecurringDetailInfo = PluginProperties.merge(ImmutableMap.<String, String>builder() .putAll(propertiesForRecurring) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_DETAIL_ID, recurringDetailList.get(0).getRecurringDetailReference()) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "RECURRING") .build()); final Payment payment2 = doAuthorize(BigDecimal.TEN, propertiesWithRecurringDetailInfo); doCapture(payment2, BigDecimal.TEN); doRefund(payment2, BigDecimal.TEN); } @Test(groups = "integration") public void testAuthorizeRecurringDetailOneClick() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, ImmutableList.<PluginProperty>of(), context); final Iterable<PluginProperty> propertiesWithCCForRecurring = PluginProperties.merge(ImmutableMap.<String, String>builder() .putAll(propertiesForRecurring) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "ONECLICK") .build(), propertiesWithCCInfo); final Payment payment = doAuthorize(BigDecimal.TEN, propertiesWithCCForRecurring); doCapture(payment, BigDecimal.TEN); doRefund(payment, BigDecimal.TEN); // Sleep a few seconds to give Adyen's Test System time to process and create the RecurringDetails Thread.sleep(SLEEP_IN_MILLIS_FOR_RECURRING_DETAIL); final List<RecurringDetail> recurringDetailList = adyenRecurringClient.getRecurringDetailList(propertiesForRecurring.get(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID), adyenConfigProperties.getMerchantAccount(DEFAULT_COUNTRY), "ONECLICK"); if (recurringDetailList.isEmpty()) { fail("No recurring details for " + propertiesForRecurring.get(AdyenPaymentPluginApi.PROPERTY_CUSTOMER_ID)); } final Iterable<PluginProperty> propertiesWithRecurringDetailInfo = PluginProperties.buildPluginProperties(ImmutableMap.<String, String>builder() .putAll(propertiesForRecurring) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_DETAIL_ID, recurringDetailList.get(0).getRecurringDetailReference()) .put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE) .put(AdyenPaymentPluginApi.PROPERTY_RECURRING_TYPE, "ONECLICK") .build()); final Payment payment2 = doAuthorize(BigDecimal.TEN, propertiesWithRecurringDetailInfo); doCapture(payment2, BigDecimal.TEN); doRefund(payment2, BigDecimal.TEN); } @Test(groups = "integration") public void testAuthorizeWithContinuousAuthentication() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CONTINUOUS_AUTHENTICATION, "true"))); doCapture(payment, BigDecimal.TEN); doRefund(payment, BigDecimal.TEN); } @Test(groups = "integration") public void testAuthorizeAndCheckAVSResult() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithAVSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin1 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWithAVSInfo, context); assertNull(authorizationInfoPlugin1.getGatewayErrorCode()); assertEquals(authorizationInfoPlugin1.getStatus(), PaymentPluginStatus.PROCESSED); final String avsResult = PluginProperties.findPluginPropertyValue("avsResult", authorizationInfoPlugin1.getProperties()); final String avsResultCode = PluginProperties.findPluginPropertyValue("avsResultCode", authorizationInfoPlugin1.getProperties()); assertEquals(avsResultCode, "Y"); assertEquals(avsResult, "7 Both postal code and address match"); } @Test(groups = "integration") public void testAuthorizeAndCheckBadAVSResult() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithAVSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin1 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWithBadAVSInfo, context); assertNull(authorizationInfoPlugin1.getGatewayErrorCode()); assertEquals(authorizationInfoPlugin1.getStatus(), PaymentPluginStatus.PROCESSED); final String avsResult = PluginProperties.findPluginPropertyValue("avsResult", authorizationInfoPlugin1.getProperties()); final String avsResultCode = PluginProperties.findPluginPropertyValue("avsResultCode", authorizationInfoPlugin1.getProperties()); assertEquals(avsResultCode, "A"); assertEquals(avsResult, "1 Address matches, postal code doesn't"); } @Test(groups = "integration") public void testAuthorizeWithZipCodeOnlyAVSCheck() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithZipCodeOnlyAVSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin1 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWithZipCodeOnlyAVSInfo, context); assertNull(authorizationInfoPlugin1.getGatewayErrorCode()); assertEquals(authorizationInfoPlugin1.getStatus(), PaymentPluginStatus.PROCESSED); final String avsResult = PluginProperties.findPluginPropertyValue("avsResult", authorizationInfoPlugin1.getProperties()); final String avsResultCode = PluginProperties.findPluginPropertyValue("avsResultCode", authorizationInfoPlugin1.getProperties()); assertEquals(avsResultCode, "Z"); assertEquals(avsResult, "6 Postal code matches, address doesn't match"); } @Test(groups = "integration") public void testAuthorizeAndComplete3DSecure() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWith3DSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransaction captureTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.CAPTURE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin1 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWith3DSInfo, context); assertNull(authorizationInfoPlugin1.getGatewayErrorCode()); assertEquals(authorizationInfoPlugin1.getStatus(), PaymentPluginStatus.PENDING); final String expectedMerchantAccount = getExpectedMerchantAccount(payment); final PaymentTransactionInfoPlugin paymentInfo = Iterables.getLast(adyenPaymentPluginApi.getPaymentInfo(payment.getAccountId(), payment.getId(), null, context)); assertEquals(PluginProperties.findPluginPropertyValue("merchantAccountCode", paymentInfo.getProperties()), expectedMerchantAccount); // Verify GET path final List<PaymentTransactionInfoPlugin> paymentTransactionInfoPluginsPreCompletion = adyenPaymentPluginApi.getPaymentInfo(account.getId(), authorizationInfoPlugin1.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); assertEquals(paymentTransactionInfoPluginsPreCompletion.size(), 1); assertEquals(paymentTransactionInfoPluginsPreCompletion.get(0).getTransactionType(), TransactionType.AUTHORIZE); assertEquals(paymentTransactionInfoPluginsPreCompletion.get(0).getStatus(), PaymentPluginStatus.PENDING); final URL issuerUrl = new URL(PluginProperties.findPluginPropertyValue("issuerUrl", authorizationInfoPlugin1.getProperties())); final String md = PluginProperties.findPluginPropertyValue("MD", authorizationInfoPlugin1.getProperties()); final String paReq = PluginProperties.findPluginPropertyValue("PaReq", authorizationInfoPlugin1.getProperties()); final String termUrl = PluginProperties.findPluginPropertyValue("TermUrl", authorizationInfoPlugin1.getProperties()); final String responseHTML = given().log().all() .contentType(ContentType.URLENC) .accept(ContentType.HTML) .formParam("MD", md) .formParam("PaReq", paReq) .formParam("TermUrl", termUrl) .post(issuerUrl) .then().log().all() .statusCode(HTTP_200_OK) .extract().asString(); final Map<String, String> formParams = extractForm(responseHTML); assertFalse(formParams.isEmpty(), "No FORM found in HTML response"); final String formAction = rewriteFormURL(issuerUrl, formParams.remove("formAction")); formParams.put("username", "user"); formParams.put("password", "password"); final String redirectHTML = given().log().all() .contentType(ContentType.URLENC) .accept(ContentType.HTML) .formParams(formParams) .post(formAction) .then().log().all() .statusCode(HTTP_200_OK) .extract().asString(); final Map<String, String> redirectFormParams = extractForm(redirectHTML); assertFalse(redirectFormParams.isEmpty(), "No FORM found in redirect HTML response"); assertEquals(termUrl, redirectFormParams.remove("formAction")); // simulate url encoding that happens in the KillBill Client redirectFormParams.put("MD", UTF8UrlEncoder.encodeQueryElement(redirectFormParams.get("MD"))); redirectFormParams.put("PaRes", UTF8UrlEncoder.encodeQueryElement(redirectFormParams.get("PaRes"))); final List<PluginProperty> propertiesWithCompleteParams = PluginProperties.buildPluginProperties(redirectFormParams); final PaymentTransactionInfoPlugin authorizationInfoPlugin2 = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWithCompleteParams, context); verifyPaymentTransactionInfoPlugin(payment, authorizationTransaction, authorizationInfoPlugin2); assertEquals(authorizationInfoPlugin2.getFirstPaymentReferenceId(), authorizationInfoPlugin1.getFirstPaymentReferenceId()); // Verify GET path final List<PaymentTransactionInfoPlugin> paymentTransactionInfoPluginsPostCompletion = adyenPaymentPluginApi.getPaymentInfo(account.getId(), authorizationInfoPlugin1.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); assertEquals(paymentTransactionInfoPluginsPostCompletion.size(), 1); assertEquals(paymentTransactionInfoPluginsPostCompletion.get(0).getTransactionType(), TransactionType.AUTHORIZE); assertEquals(paymentTransactionInfoPluginsPostCompletion.get(0).getStatus(), PaymentPluginStatus.PROCESSED); final PaymentTransactionInfoPlugin captureInfoPlugin = adyenPaymentPluginApi.capturePayment(account.getId(), payment.getId(), captureTransaction.getId(), account.getPaymentMethodId(), captureTransaction.getAmount(), captureTransaction.getCurrency(), authorizationInfoPlugin2.getProperties(), context); verifyPaymentTransactionInfoPlugin(payment, captureTransaction, captureInfoPlugin); // Verify GET path final List<PaymentTransactionInfoPlugin> paymentTransactionInfoPluginsPostCapture = adyenPaymentPluginApi.getPaymentInfo(account.getId(), authorizationInfoPlugin1.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); assertEquals(paymentTransactionInfoPluginsPostCapture.size(), 2); assertEquals(paymentTransactionInfoPluginsPostCapture.get(0).getTransactionType(), TransactionType.AUTHORIZE); assertEquals(paymentTransactionInfoPluginsPostCapture.get(0).getStatus(), PaymentPluginStatus.PROCESSED); assertEquals(paymentTransactionInfoPluginsPostCapture.get(1).getTransactionType(), TransactionType.CAPTURE); assertEquals(paymentTransactionInfoPluginsPostCapture.get(1).getStatus(), PaymentPluginStatus.PENDING); } @Test(groups = "integration") public void testAuthorizeAndExpire3DSecure() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWith3DSInfo, context); final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); final PaymentTransaction authorizationTransaction = TestUtils.buildPaymentTransaction(payment, TransactionType.AUTHORIZE, new BigDecimal("1000"), account.getCurrency()); final PaymentTransactionInfoPlugin authorizationInfoPlugin = adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), authorizationTransaction.getId(), account.getPaymentMethodId(), authorizationTransaction.getAmount(), authorizationTransaction.getCurrency(), propertiesWith3DSInfo, context); assertEquals(authorizationInfoPlugin.getStatus(), PaymentPluginStatus.PENDING); final Period expirationPeriod = adyenConfigProperties.getPending3DsPaymentExpirationPeriod().plusMinutes(1); clock.setDeltaFromReality(expirationPeriod.toStandardDuration().getMillis()); final List<PaymentTransactionInfoPlugin> expiredPaymentTransactions = adyenPaymentPluginApi.getPaymentInfo(account.getId(), authorizationInfoPlugin.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); assertEquals(expiredPaymentTransactions.size(), 1); final PaymentTransactionInfoPlugin canceledTransaction = expiredPaymentTransactions.get(0); assertEquals(canceledTransaction.getTransactionType(), TransactionType.AUTHORIZE); assertEquals(canceledTransaction.getStatus(), PaymentPluginStatus.CANCELED); } @Test(groups = "integration") public void testAuthorizeAndCaptureWithSplitSettlements() throws Exception { adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); final ImmutableMap.Builder<String, String> builder = new ImmutableMap.Builder<String, String>(); builder.put(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE); builder.put(String.format("%s.1.amount", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "3.51"); builder.put(String.format("%s.1.group", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "MENSWEAR"); builder.put(String.format("%s.1.reference", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), UUID.randomUUID().toString()); builder.put(String.format("%s.1.type", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "FOOTWEAR"); builder.put(String.format("%s.2.amount", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "6.49"); builder.put(String.format("%s.2.group", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "STREETWEAR"); builder.put(String.format("%s.2.reference", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), UUID.randomUUID().toString()); builder.put(String.format("%s.2.type", AdyenPaymentPluginApi.SPLIT_SETTLEMENT_DATA_ITEM), "HEADWEAR"); final Map<String, String> pluginPropertiesMap = builder.build(); final List<PluginProperty> pluginProperties = PluginProperties.buildPluginProperties(pluginPropertiesMap); final Payment payment = doAuthorize(BigDecimal.TEN, pluginProperties); doCapture(payment, BigDecimal.TEN); } private Map<String, String> extractForm(final String html) { final Map<String, String> fields = new HashMap<String, String>(); final Document doc = Jsoup.parse(html); final Elements forms = doc.getElementsByTag("form"); for (final Element form : forms) { if ("post".equalsIgnoreCase(form.attr("method"))) { fields.put("formAction", form.attr("action")); final Elements inputs = form.getElementsByTag("input"); for (final Element input : inputs) { final String value = input.val(); if (value != null && !value.isEmpty() && !"Submit".equalsIgnoreCase(value)) { fields.put(input.attr("name"), value); } } return fields; } } return Collections.emptyMap(); } private String rewriteFormURL(final URL issuerUrl, final String formAction) { if (formAction.startsWith("http")) { return formAction; } else { return issuerUrl.getProtocol() + "://" + issuerUrl.getHost() + (issuerUrl.getPort() != HTTP_PORT && issuerUrl.getPort() != HTTPS_PORT ? ":" + issuerUrl.getPort() : "") + formAction; } } private Payment doAuthorize(final BigDecimal amount) throws PaymentPluginApiException, PaymentApiException { return doAuthorize(amount, ImmutableList.<PluginProperty>of()); } private Payment doAuthorize(final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException, PaymentApiException { return doPluginCall(amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.authorizePayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doPurchase(final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException, PaymentApiException { return doPluginCall(amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.purchasePayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doCredit(final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException, PaymentApiException { return doPluginCall(amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.creditPayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doCapture(final Payment payment, final BigDecimal amount) throws PaymentPluginApiException { return doCapture(payment, amount, ImmutableList.<PluginProperty>of()); } private Payment doCapture(final Payment payment, final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return doPluginCall(payment, amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.capturePayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doRefund(final Payment payment, final BigDecimal amount) throws PaymentPluginApiException { return doRefund(payment, amount, ImmutableList.<PluginProperty>of()); } private Payment doRefund(final Payment payment, final BigDecimal amount, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return doPluginCall(payment, amount, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.refundPayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), paymentTransaction.getAmount(), paymentTransaction.getCurrency(), pluginProperties, context); } }); } private Payment doVoid(final Payment payment) throws PaymentPluginApiException { return doVoid(payment, ImmutableList.<PluginProperty>of()); } private Payment doVoid(final Payment payment, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return doPluginCall(payment, null, pluginProperties, new PluginCall() { @Override public PaymentTransactionInfoPlugin execute(final Payment payment, final PaymentTransaction paymentTransaction, final Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException { return adyenPaymentPluginApi.voidPayment(account.getId(), payment.getId(), paymentTransaction.getId(), payment.getPaymentMethodId(), pluginProperties, context); } }); } private Payment doPluginCall(final BigDecimal amount, final Iterable<PluginProperty> pluginProperties, final PluginCall pluginCall) throws PaymentPluginApiException, PaymentApiException { final Payment payment = TestUtils.buildPayment(account.getId(), account.getPaymentMethodId(), account.getCurrency(), killbillApi); return doPluginCall(payment, amount, pluginProperties, pluginCall); } private Payment doPluginCall(final Payment payment, final BigDecimal amount, final Iterable<PluginProperty> pluginProperties, final PluginCall pluginCall) throws PaymentPluginApiException { final PaymentTransaction paymentTransaction = TestUtils.buildPaymentTransaction(payment, null, amount, payment.getCurrency()); final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin = pluginCall.execute(payment, paymentTransaction, pluginProperties); TestUtils.updatePaymentTransaction(paymentTransaction, paymentTransactionInfoPlugin); verifyPaymentTransactionInfoPlugin(payment, paymentTransaction, paymentTransactionInfoPlugin); if ("true".equals(PluginProperties.findPluginPropertyValue("skip_gw", pluginProperties))) { return payment; } if (paymentTransactionInfoPlugin.getTransactionType() == TransactionType.AUTHORIZE || paymentTransactionInfoPlugin.getTransactionType() == TransactionType.PURCHASE) { // Authorization are synchronous assertEquals(paymentTransactionInfoPlugin.getStatus(), PaymentPluginStatus.PROCESSED); } else { assertEquals(paymentTransactionInfoPlugin.getStatus(), PaymentPluginStatus.PENDING); } processNotification(TRANSACTION_TYPE_TO_EVENT_CODE.get(paymentTransaction.getTransactionType()), true, paymentTransaction.getExternalKey(), paymentTransactionInfoPlugin.getFirstPaymentReferenceId()); assertEquals(paymentTransaction.getPaymentInfoPlugin().getStatus(), PaymentPluginStatus.PROCESSED); final String expectedMerchantAccount = getExpectedMerchantAccount(payment); final PaymentTransactionInfoPlugin refreshedTransactionInfo = Iterables.getLast(adyenPaymentPluginApi.getPaymentInfo(payment.getAccountId(), payment.getId(), null, context)); assertEquals(PluginProperties.findPluginPropertyValue("merchantAccountCode", refreshedTransactionInfo.getProperties()), expectedMerchantAccount); return payment; } private String getExpectedMerchantAccount(final Payment payment) { final Account paymentAccount; try { paymentAccount = this.killbillApi.getAccountUserApi().getAccountById(payment.getAccountId(), context); } catch (AccountApiException e) { throw new RuntimeException(e); } return adyenConfigProperties.getMerchantAccount(paymentAccount.getCountry()); } private void verifyPaymentTransactionInfoPlugin(final Payment payment, final PaymentTransaction paymentTransaction, final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin) throws PaymentPluginApiException { verifyPaymentTransactionInfoPlugin(payment, paymentTransaction, paymentTransactionInfoPlugin, true); // Verify we can fetch the details final List<PaymentTransactionInfoPlugin> paymentTransactionInfoPlugins = adyenPaymentPluginApi.getPaymentInfo(account.getId(), paymentTransactionInfoPlugin.getKbPaymentId(), ImmutableList.<PluginProperty>of(), context); final PaymentTransactionInfoPlugin paymentTransactionInfoPluginFetched = Iterables.<PaymentTransactionInfoPlugin>find(Lists.<PaymentTransactionInfoPlugin>reverse(paymentTransactionInfoPlugins), new Predicate<PaymentTransactionInfoPlugin>() { @Override public boolean apply(final PaymentTransactionInfoPlugin input) { return input.getKbTransactionPaymentId().equals(paymentTransaction.getId()); } }); verifyPaymentTransactionInfoPlugin(payment, paymentTransaction, paymentTransactionInfoPluginFetched, true); } private void verifyPaymentTransactionInfoPlugin(final Payment payment, final PaymentTransaction paymentTransaction, final PaymentTransactionInfoPlugin paymentTransactionInfoPlugin, final boolean authorizedProcessed) { assertEquals(paymentTransactionInfoPlugin.getKbPaymentId(), payment.getId()); assertEquals(paymentTransactionInfoPlugin.getKbTransactionPaymentId(), paymentTransaction.getId()); assertEquals(paymentTransactionInfoPlugin.getTransactionType(), paymentTransaction.getTransactionType()); if (TransactionType.VOID.equals(paymentTransaction.getTransactionType())) { assertNull(paymentTransactionInfoPlugin.getAmount()); assertNull(paymentTransactionInfoPlugin.getCurrency()); } else { assertEquals(paymentTransactionInfoPlugin.getAmount().compareTo(paymentTransaction.getAmount()), 0); assertEquals(paymentTransactionInfoPlugin.getCurrency(), paymentTransaction.getCurrency()); } assertNotNull(paymentTransactionInfoPlugin.getCreatedDate()); assertNotNull(paymentTransactionInfoPlugin.getEffectiveDate()); final List<PaymentPluginStatus> expectedPaymentPluginStatus; switch (paymentTransaction.getTransactionType()) { case PURCHASE: case AUTHORIZE: expectedPaymentPluginStatus = authorizedProcessed ? ImmutableList.of(PaymentPluginStatus.PROCESSED) : ImmutableList.of(PaymentPluginStatus.PROCESSED, PaymentPluginStatus.PENDING); break; case CAPTURE: expectedPaymentPluginStatus = ImmutableList.of(PaymentPluginStatus.PENDING); break; case REFUND: expectedPaymentPluginStatus = ImmutableList.of(PaymentPluginStatus.PENDING); break; case VOID: expectedPaymentPluginStatus = ImmutableList.of(PaymentPluginStatus.PENDING); break; default: expectedPaymentPluginStatus = ImmutableList.of(PaymentPluginStatus.PENDING); break; } if ("skip_gw".equals(paymentTransactionInfoPlugin.getGatewayError()) || "true".equals(PluginProperties.findPluginPropertyValue("skipGw", paymentTransactionInfoPlugin.getProperties()))) { assertNull(paymentTransactionInfoPlugin.getGatewayErrorCode()); assertEquals(paymentTransactionInfoPlugin.getStatus(), PaymentPluginStatus.PROCESSED); assertNull(paymentTransactionInfoPlugin.getFirstPaymentReferenceId()); } else { assertNull(paymentTransactionInfoPlugin.getGatewayErrorCode()); assertTrue(expectedPaymentPluginStatus.contains(paymentTransactionInfoPlugin.getStatus()), "was: " + paymentTransactionInfoPlugin.getStatus()); assertNull(paymentTransactionInfoPlugin.getGatewayError()); assertNotNull(paymentTransactionInfoPlugin.getFirstPaymentReferenceId()); // NULL for subsequent transactions (modifications) //Assert.assertNotNull(paymentTransactionInfoPlugin.getSecondPaymentReferenceId()); } } private PaymentMethodPlugin adyenEmptyPaymentMethodPlugin() { return adyenPaymentMethodPlugin(account.getPaymentMethodId().toString(), null); } private PaymentMethodPlugin adyenPaymentMethodPluginSepaDirectDebit() { return adyenPaymentMethodPlugin(account.getPaymentMethodId().toString(), "{" + '"' + PROPERTY_DD_HOLDER_NAME + "\":\"" + DD_HOLDER_NAME + "\"," + '"' + PROPERTY_DD_ACCOUNT_NUMBER + "\":\"" + DD_IBAN + "\"," + '"' + PROPERTY_DD_BANK_IDENTIFIER_CODE + "\":\"" + DD_BIC + '"' + '}'); } private PaymentMethodPlugin adyenPaymentMethodPluginELV() { return adyenPaymentMethodPlugin(account.getPaymentMethodId().toString(), "{" + '"' + PROPERTY_DD_HOLDER_NAME + "\":\"" + DD_HOLDER_NAME + "\"," + '"' + PROPERTY_DD_ACCOUNT_NUMBER + "\":\"" + ELV_KONTONUMMER + "\"," + '"' + PROPERTY_ELV_BLZ + "\":\"" + ELV_BANKLEITZAHL + '"' + '}'); } private static PaymentMethodPlugin adyenPaymentMethodPlugin(final String paymentMethodId, final String additionalData) { final AdyenPaymentMethodsRecord record = new AdyenPaymentMethodsRecord(); record.setKbPaymentMethodId(paymentMethodId); record.setIsDefault(AdyenDao.TRUE); if (!Strings.isNullOrEmpty(additionalData)) { record.setAdditionalData(additionalData); } return new AdyenPaymentMethodPlugin(record); } private interface PluginCall { PaymentTransactionInfoPlugin execute(Payment payment, PaymentTransaction paymentTransaction, Iterable<PluginProperty> pluginProperties) throws PaymentPluginApiException; } }
Modify test for skipGw
src/test/java/org/killbill/billing/plugin/adyen/api/TestAdyenPaymentPluginApi.java
Modify test for skipGw
<ide><path>rc/test/java/org/killbill/billing/plugin/adyen/api/TestAdyenPaymentPluginApi.java <ide> import org.killbill.billing.plugin.adyen.dao.AdyenDao; <ide> import org.killbill.billing.plugin.adyen.dao.gen.tables.records.AdyenPaymentMethodsRecord; <ide> import org.killbill.billing.plugin.api.PluginProperties; <add>import org.testng.Assert; <ide> import org.testng.annotations.BeforeMethod; <ide> import org.testng.annotations.Test; <ide> <ide> public void testAuthorizeAndCaptureSkipGw() throws Exception { <ide> adyenPaymentPluginApi.addPaymentMethod(account.getId(), account.getPaymentMethodId(), adyenEmptyPaymentMethodPlugin(), true, propertiesWithCCInfo, context); <ide> <del> final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE, "skip_gw", "true"))); <add> final Payment payment = doAuthorize(BigDecimal.TEN, PluginProperties.buildPluginProperties(ImmutableMap.<String, String>of(AdyenPaymentPluginApi.PROPERTY_CC_VERIFICATION_VALUE, CC_VERIFICATION_VALUE, "skip_gw", "true", AdyenPaymentPluginApi.PROPERTY_PSP_REFERENCE, "test_psp_ref"))); <add> PaymentTransactionInfoPlugin paymentTransactionInfoPlugin = adyenPaymentPluginApi.getPaymentInfo(account.getId(), payment.getId(), ImmutableList.of(), context).get(0); <add> Assert.assertEquals("test_psp_ref", paymentTransactionInfoPlugin.getFirstPaymentReferenceId()); <add> <ide> doCapture(payment, new BigDecimal("5"), ImmutableList.<PluginProperty>of(new PluginProperty("skip_gw", "true", false))); <ide> } <ide> <ide> "true".equals(PluginProperties.findPluginPropertyValue("skipGw", paymentTransactionInfoPlugin.getProperties()))) { <ide> assertNull(paymentTransactionInfoPlugin.getGatewayErrorCode()); <ide> assertEquals(paymentTransactionInfoPlugin.getStatus(), PaymentPluginStatus.PROCESSED); <del> assertNull(paymentTransactionInfoPlugin.getFirstPaymentReferenceId()); <ide> } else { <ide> assertNull(paymentTransactionInfoPlugin.getGatewayErrorCode()); <ide> assertTrue(expectedPaymentPluginStatus.contains(paymentTransactionInfoPlugin.getStatus()), "was: " + paymentTransactionInfoPlugin.getStatus());
Java
mit
c3a093e4dbc85ff4dac93182a37c67e572903da5
0
Innovimax-SARL/mix-them
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import innovimax.mixthem.arguments.ParamValue; import innovimax.mixthem.arguments.RuleParam; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * <p>Joins two or more lines on a common field.</p> * <p>Joining doesn't operate when no common field is found for all lines.</p> * <p>In this case, we prevent bigger join field file(s) from beeing read, keeping current line(s).</p> * @see ILineOperation * @author Innovimax * @version 1.0 */ public class DefaultLineJoining extends AbstractLineOperation { private final int[] joinCols; /** * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.operation.RuleParam * @see innovimax.mixthem.operation.ParamValue */ public DefaultLineJoining(final Map<RuleParam, ParamValue> params) { super(params); if (this.params.containsKey(RuleParam.JOIN_COLS)) { this.joinCols = this.params.get(RuleParam.JOIN_COLS).asIntArray(); } else { this.joinCols = new int[1]; this.joinCols[0] = JoinOperation.DEFAULT_JOIN_COLUMN.getValue().asInt(); } //System.out.println("COLS="+Arrays.toString(this.joinCols)); } @Override public void process(final List<String> lineRange, final LineResult result) throws MixException { //System.out.println("LINES="+lineRange.toString()); final List<Boolean> lineReadingRange = new ArrayList<Boolean>(result.getLineReadingRange()); //System.out.println("READ="+lineReadingRange.toString()); result.reset(); final List<List<String>> lineCellsRange = getLineCellsRange(lineRange); if (linesComparable(lineCellsRange)) { if (linesJoined(lineCellsRange)) { joinLines(lineCellsRange, result); //System.out.println("JOINED="+result.getResult()); } else { setLineReadingPreservation(lineCellsRange, result); } for (int i=0; i < lineRange.size(); i++) { result.setRangeLine(i, lineRange.get(i)); } } } private List<List<String>> getLineCellsRange(final List<String> lineRange) { final List<List<String>> lineCellsRange = new ArrayList<List<String>>(); for (String line : lineRange) { lineCellsRange.add(Arrays.asList(line.split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.getValue().asString()))); } return lineCellsRange; } private int getJoinedColumn(int index) { if (this.joinCols.length == 1) { return this.joinCols[0]; } else if (index < this.joinCols.length && this.joinCols[index] > 0) { return this.joinCols[index]; } else { return JoinOperation.DEFAULT_JOIN_COLUMN.getValue().asInt(); } } private boolean linesComparable(final List<List<String>> lineCellsRange) { for (int i=0; i < lineCellsRange.size(); i++) { final List<String> lineCells = lineCellsRange.get(i); if (lineCells.size() < getJoinedColumn(i)) { return false; } } return true; } private boolean linesJoined(final List<List<String>> lineCellsRange) { String joinCell = null; for (int i=0; i < lineCellsRange.size(); i++) { final List<String> lineCells = lineCellsRange.get(i); final String cell = lineCells.get(getJoinedColumn(i) - 1); if (joinCell == null) { joinCell = cell; } if (!cell.equals(joinCell)) { return false; } } return true; } private void setLineReadingPreservation(final List<List<String>> lineCellsRange, final LineResult result) { List<String> cellRange = new ArrayList<String>(); String greaterCell = null; for (int i=0; i < lineCellsRange.size(); i++) { final List<String> lineCells = lineCellsRange.get(i); final String cell = lineCells.get(getJoinedColumn(i) - 1); if (greaterCell == null) { greaterCell = cell; } if (cell.compareTo(greaterCell) > 0) { greaterCell = cell; } cellRange.add(cell); } for (int i=0; i < cellRange.size(); i++) { final String cell = cellRange.get(i); if (cell.equals(greaterCell)) { result.setRangeLineReadingStatus(i, false); } } } private void joinLines(final List<List<String>> lineCellsRange, final LineResult result) { final StringBuilder joinedCells = new StringBuilder(); String join = lineCellsRange.get(0).get(getJoinedColumn(0) - 1); joinedCells.append(join); for (List<String> lineCells : lineCellsRange) { joinedCells.append(CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString()); joinedCells.append( lineCells.stream() .filter(s -> !s.equals(join)) .collect(Collectors.joining(CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString()))); } result.setResult(joinedCells.toString()); } }
src/main/java/innovimax/mixthem/operation/DefaultLineJoining.java
package innovimax.mixthem.operation; import innovimax.mixthem.MixException; import innovimax.mixthem.arguments.ParamValue; import innovimax.mixthem.arguments.RuleParam; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** * <p>Joins two or more lines on a common field.</p> * <p>Joining doesn't operate when no common field is found for all lines.</p> * <p>In this case, we prevent bigger join field file(s) from beeing read, keeping current line(s).</p> * @see ILineOperation * @author Innovimax * @version 1.0 */ public class DefaultLineJoining extends AbstractLineOperation { private final int[] joinCols; /** * @param params The list of parameters (maybe empty) * @see innovimax.mixthem.operation.RuleParam * @see innovimax.mixthem.operation.ParamValue */ public DefaultLineJoining(final Map<RuleParam, ParamValue> params) { super(params); if (this.params.containsKey(RuleParam.JOIN_COLS)) { this.joinCols = this.params.get(RuleParam.JOIN_COLS).asIntArray(); } else { this.joinCols = new int[1]; this.joinCols[0] = JoinOperation.DEFAULT_JOIN_COLUMN.getValue().asInt(); } System.out.println("COLS="+Arrays.toString(this.joinCols)); } @Override public void process(final List<String> lineRange, final LineResult result) throws MixException { System.out.println("LINES="+lineRange.toString()); final List<Boolean> lineReadingRange = new ArrayList<Boolean>(result.getLineReadingRange()); System.out.println("READ="+lineReadingRange.toString()); result.reset(); final List<List<String>> lineCellsRange = getLineCellsRange(lineRange); if (linesComparable(lineCellsRange)) { if (linesJoined(lineCellsRange)) { joinLines(lineCellsRange, result); System.out.println("JOINED="+result.getResult()); } else { setLineReadingPreservation(lineCellsRange, result); } for (int i=0; i < lineRange.size(); i++) { result.setRangeLine(i, lineRange.get(i)); } } } private List<List<String>> getLineCellsRange(final List<String> lineRange) { final List<List<String>> lineCellsRange = new ArrayList<List<String>>(); for (String line : lineRange) { lineCellsRange.add(Arrays.asList(line.split(CellOperation.DEFAULT_SPLIT_CELL_REGEX.getValue().asString()))); } return lineCellsRange; } private int getJoinedColumn(int index) { if (this.joinCols.length == 1) { return this.joinCols[0]; } else if (index < this.joinCols.length && this.joinCols[index] > 0) { return this.joinCols[index]; } else { return JoinOperation.DEFAULT_JOIN_COLUMN.getValue().asInt(); } } private boolean linesComparable(final List<List<String>> lineCellsRange) { for (int i=0; i < lineCellsRange.size(); i++) { final List<String> lineCells = lineCellsRange.get(i); if (lineCells.size() < getJoinedColumn(i)) { return false; } } return true; } private boolean linesJoined(final List<List<String>> lineCellsRange) { String joinCell = null; for (int i=0; i < lineCellsRange.size(); i++) { final List<String> lineCells = lineCellsRange.get(i); final String cell = lineCells.get(getJoinedColumn(i) - 1); if (joinCell == null) { joinCell = cell; } if (!cell.equals(joinCell)) { return false; } } return true; } private void setLineReadingPreservation(final List<List<String>> lineCellsRange, final LineResult result) { List<String> cellRange = new ArrayList<String>(); String greaterCell = null; for (int i=0; i < lineCellsRange.size(); i++) { final List<String> lineCells = lineCellsRange.get(i); final String cell = lineCells.get(getJoinedColumn(i) - 1); if (greaterCell == null) { greaterCell = cell; } if (cell.compareTo(greaterCell) > 0) { greaterCell = cell; } cellRange.add(cell); } for (int i=0; i < cellRange.size(); i++) { final String cell = cellRange.get(i); if (cell.equals(greaterCell)) { result.setRangeLineReadingStatus(i, false); } } } private void joinLines(final List<List<String>> lineCellsRange, final LineResult result) { final StringBuilder joinedCells = new StringBuilder(); String join = lineCellsRange.get(0).get(getJoinedColumn(0) - 1); joinedCells.append(join); for (List<String> lineCells : lineCellsRange) { joinedCells.append(CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString()); joinedCells.append( lineCells.stream() .filter(s -> !s.equals(join)) .collect(Collectors.joining(CellOperation.DEFAULT_CELL_SEPARATOR.getValue().asString()))); } result.setResult(joinedCells.toString()); } }
Update DefaultLineJoining.java
src/main/java/innovimax/mixthem/operation/DefaultLineJoining.java
Update DefaultLineJoining.java
<ide><path>rc/main/java/innovimax/mixthem/operation/DefaultLineJoining.java <ide> this.joinCols = new int[1]; <ide> this.joinCols[0] = JoinOperation.DEFAULT_JOIN_COLUMN.getValue().asInt(); <ide> } <del> System.out.println("COLS="+Arrays.toString(this.joinCols)); <add> //System.out.println("COLS="+Arrays.toString(this.joinCols)); <ide> } <ide> <ide> @Override <ide> public void process(final List<String> lineRange, final LineResult result) throws MixException { <del> System.out.println("LINES="+lineRange.toString()); <add> //System.out.println("LINES="+lineRange.toString()); <ide> final List<Boolean> lineReadingRange = new ArrayList<Boolean>(result.getLineReadingRange()); <del> System.out.println("READ="+lineReadingRange.toString()); <add> //System.out.println("READ="+lineReadingRange.toString()); <ide> result.reset(); <ide> final List<List<String>> lineCellsRange = getLineCellsRange(lineRange); <ide> if (linesComparable(lineCellsRange)) { <ide> if (linesJoined(lineCellsRange)) { <ide> joinLines(lineCellsRange, result); <del> System.out.println("JOINED="+result.getResult()); <add> //System.out.println("JOINED="+result.getResult()); <ide> } else { <ide> setLineReadingPreservation(lineCellsRange, result); <ide> }
Java
apache-2.0
6a375b8623e10333e656d9b616b33ec845146da0
0
welleby/aftonbladet-analyzer
package org.welleby.web.scrape.aftonbladet; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.ReversedLinesFileReader; import org.apache.logging.log4j.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by kerling on 01/11/15. */ public class Application { private static String baseUrl = "http://www.aftonbladet.se/article"; private static final String URL_FILE = "workingUrls.txt"; private static Logger logger = LogManager.getLogger(Application.class); private static File workingUrlsFile; private static List<URL> workingUrls = new ArrayList<URL>(); private static final int WRITE_BUFFER = 1000; public static void main(String[] args) throws IOException { workingUrlsFile = new File(URL_FILE); int currentId; try (ReversedLinesFileReader fileReader = new ReversedLinesFileReader(workingUrlsFile)){ logger.debug("Reading file " + URL_FILE + " to pick up where we left of."); String lastUrl = fileReader.readLine(); currentId = Integer.parseInt(lastUrl.replaceAll("[^-?0-9]+", "")); logger.debug("Starting at " + currentId); } catch (FileNotFoundException exception) { currentId = 446; } for (int i = currentId + 1; i < 21684046; i++) { URL url = new URL(baseUrl + i + ".ab"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); connection.setInstanceFollowRedirects(false); int responseCode = connection.getResponseCode(); if (responseCode == 301 || responseCode == 200) { logger.info("Found url: " + url); workingUrls.add(url); } else { logger.info(responseCode + " on url: " + url); } if (workingUrls.size() >= WRITE_BUFFER) { writeUrls(); workingUrls.clear(); } } } private static void writeUrls() throws IOException { String result = ""; for (URL url : workingUrls) { result += "\n" + url.toString(); } FileUtils.writeStringToFile(workingUrlsFile, result, true); } }
src/main/java/org/welleby/web/scrape/aftonbladet/Application.java
package org.welleby.web.scrape.aftonbladet; import org.apache.commons.io.FileUtils; import org.apache.commons.io.input.ReversedLinesFileReader; import org.apache.logging.log4j.*; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; /** * Created by kerling on 01/11/15. */ public class Application { private static String baseUrl = "http://www.aftonbladet.se/article"; private static final String URL_FILE = "workingUrls.txt"; private static Logger logger = LogManager.getLogger(Application.class); private static File workingUrlsFile; private static List<URL> workingUrls = new ArrayList<URL>(); private static final int WRITE_BUFFER = 1000; public static void main(String[] args) throws IOException { workingUrlsFile = new File(URL_FILE); ReversedLinesFileReader fileReader = new ReversedLinesFileReader(workingUrlsFile); int currentId; try { logger.debug("Reading file " + URL_FILE + " to pick up where we left of."); String lastUrl = fileReader.readLine(); currentId = Integer.parseInt(lastUrl.replaceAll("[^-?0-9]+", "")); logger.debug("Starting at " + currentId); } catch (FileNotFoundException exception) { currentId = 446; } finally { fileReader.close(); } for (int i = currentId + 1; i < 21684046; i++) { URL url = new URL(baseUrl + i + ".ab"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("HEAD"); connection.setInstanceFollowRedirects(false); int responseCode = connection.getResponseCode(); if (responseCode == 301 || responseCode == 200) { logger.info("Found url: " + url); workingUrls.add(url); } else { logger.info(responseCode + " on url: " + url); } if (workingUrls.size() >= WRITE_BUFFER) { writeUrls(); workingUrls.clear(); } } } private static void writeUrls() throws IOException { String result = ""; for (URL url : workingUrls) { result += "\n" + url.toString(); } FileUtils.writeStringToFile(workingUrlsFile, result, true); } }
Changed the way workingUrl-file is handled. Now it wont throw exception if the file does not exist.
src/main/java/org/welleby/web/scrape/aftonbladet/Application.java
Changed the way workingUrl-file is handled. Now it wont throw exception if the file does not exist.
<ide><path>rc/main/java/org/welleby/web/scrape/aftonbladet/Application.java <ide> <ide> public static void main(String[] args) throws IOException { <ide> workingUrlsFile = new File(URL_FILE); <del> ReversedLinesFileReader fileReader = new ReversedLinesFileReader(workingUrlsFile); <add> <ide> int currentId; <del> try { <add> try (ReversedLinesFileReader fileReader = new ReversedLinesFileReader(workingUrlsFile)){ <ide> logger.debug("Reading file " + URL_FILE + " to pick up where we left of."); <ide> String lastUrl = fileReader.readLine(); <ide> <ide> logger.debug("Starting at " + currentId); <ide> } catch (FileNotFoundException exception) { <ide> currentId = 446; <del> } finally { <del> fileReader.close(); <del> } <add> } <ide> <ide> for (int i = currentId + 1; i < 21684046; i++) { <ide> URL url = new URL(baseUrl + i + ".ab");
Java
bsd-3-clause
3944059a2193cd846ed75c3cd1c737dbff34b718
0
muloem/xins,muloem/xins,muloem/xins
/* * $Id$ */ package org.xins.util.collections.expiry; import java.util.HashMap; import java.util.Map; import org.xins.util.MandatoryArgumentChecker; /** * Expiry folder. Contains values indexed by key. Items in this map will * expire after a predefined amount of time, unless they're access within that * timeframe. * * <p>This class is thread-safe. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>) */ public abstract class ExpiryFolder extends Object { //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------- /** * Constructs a new <code>ExpiryFolder</code>. * * @param strategy * the strategy that should be applied, not <code>null</code>. * * @throws IllegalArgumentException * if <code>strategy == null</code>. */ public ExpiryFolder(ExpiryStrategy strategy) throws IllegalArgumentException { MandatoryArgumentChecker.check("strategy", strategy); _strategy = strategy; // XXX: Allow customization of Map construction? _recentlyAccessed = new HashMap(89); _slots = new Map[strategy.getSlotCount()]; } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- /** * The strategy used. This field cannot be <code>null</code>. */ private final ExpiryStrategy _strategy; /** * The most recently accessed entries. This field cannot be * <code>null</code>. The entries in this map will expire after * {@link ExpiryStrategy#getTimeOut()} milliseconds, plus at maximum * {@link ExpiryStrategy#getPrecision()} milliseconds. */ private final Map _recentlyAccessed; /** * Slots to contain the maps with entries that are not the most recently * accessed. The further back in the array, the faster the entries will * expire. */ private final Map[] _slots; //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Touches the entry that is identified by the specified key. * * @param key * the key that identifies the entry, can be <code>null</code>. * * @throws NoSuchEntryException * if there was no entry with the specified key in this map; the entry * may have expired. */ public abstract void touch(Object key) throws NoSuchEntryException; /** * Notifies this map that the precision time frame has passed since the * last tick. * * <p>If any entries are expirable, they will be removed from this map. */ abstract void tick(); /** * Gets the number of entries. * * @return * the number of entries in this expiry folder, always &gt;= 0. */ public int size() { int size; synchronized (_recentlyAccessed) { synchronized (_slots) { size = _recentlyAccessed.size(); for (int i = 0; i < _slots.length; i++) { size += _slots[i].size(); } } } return size; } /** * Checks if this folder is completely empty. * * @return * <code>true</code> if and only if there are no entries in this folder. */ public boolean isEmpty() { synchronized (_recentlyAccessed) { if (_recentlyAccessed.isEmpty() == false) { return false; } } for (int i = 0; i < _slots.length; i++) { Map slot = _slots[i]; synchronized (slot) { if (slot.isEmpty() == false) { return false; } } } return true; } /** * Gets the value associated with a key. * * @param key * the key to lookup, cannot be <code>null</code>. * * @return * the value associated with the specified key, or <code>null</code> if * and only if this folder does not contain an entry with the specified * key. * * @throws IllegalArgumentException * if <code>key == null</code>. */ public Object get(Object key) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("key", key); // Check _recentlyAccessed synchronized (_recentlyAccessed) { Object o = _recentlyAccessed.get(key); if (o != null) { return o; } } // Check all slots for (int i = 0; i < _slots.length; i++) { Map slot = _slots[i]; synchronized (slot) { Object o = slot.get(key); if (o != null) { return o; } } } return null; } /** * Associates the specified value with the specified key in this folder. * * @param key * they key for the entry, cannot be <code>null</code>. * * @param value * they value for the entry, cannot be <code>null</code>. * * @throws IllegalArgumentException * if <code>key == null || value == null</code>. */ public void put(Object key, Object value) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("key", key, "value", value); synchronized (_recentlyAccessed) { _recentlyAccessed.put(key, value); } } /** * Removes all entries. */ public void clear() { synchronized (_recentlyAccessed) { _recentlyAccessed.clear(); for (int i = 0; i < _slots.length; i++) { Map slot = _slots[i]; synchronized (slot) { slot.clear(); } } } } }
src/java-common/org/xins/util/collections/expiry/ExpiryFolder.java
/* * $Id$ */ package org.xins.util.collections.expiry; import java.util.HashMap; import java.util.Map; import org.xins.util.MandatoryArgumentChecker; /** * Expiry folder. Contains values indexed by key. Items in this map will * expire after a predefined amount of time, unless they're access within that * timeframe. * * <p>This class is thread-safe. * * @version $Revision$ $Date$ * @author Ernst de Haan (<a href="mailto:[email protected]">[email protected]</a>) */ public abstract class ExpiryFolder extends Object { //------------------------------------------------------------------------- // Class fields //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Class functions //------------------------------------------------------------------------- //------------------------------------------------------------------------- // Constructor //------------------------------------------------------------------------- /** * Constructs a new <code>ExpiryMap</code>. * * @param strategy * the strategy that should be applied, not <code>null</code>. * * @throws IllegalArgumentException * if <code>strategy == null</code>. */ public ExpiryFolder(ExpiryStrategy strategy) throws IllegalArgumentException { MandatoryArgumentChecker.check("strategy", strategy); _strategy = strategy; // XXX: Allow customization of Map construction? _recentlyAccessed = new HashMap(89); _slots = new Map[strategy.getSlotCount()]; } //------------------------------------------------------------------------- // Fields //------------------------------------------------------------------------- /** * The strategy used. This field cannot be <code>null</code>. */ private final ExpiryStrategy _strategy; /** * The most recently accessed entries. This field cannot be * <code>null</code>. The entries in this map will expire after * {@link ExpiryStrategy#getTimeOut()} milliseconds, plus at maximum * {@link ExpiryStrategy#getPrecision()} milliseconds. */ private final Map _recentlyAccessed; /** * Slots to contain the maps with entries that are not the most recently * accessed. The further back in the array, the faster the entries will * expire. */ private final Map[] _slots; //------------------------------------------------------------------------- // Methods //------------------------------------------------------------------------- /** * Touches the entry that is identified by the specified key. * * @param key * the key that identifies the entry, can be <code>null</code>. * * @throws NoSuchEntryException * if there was no entry with the specified key in this map; the entry * may have expired. */ public abstract void touch(Object key) throws NoSuchEntryException; /** * Notifies this map that the precision time frame has passed since the * last tick. * * <p>If any entries are expirable, they will be removed from this map. */ abstract void tick(); /** * Gets the number of entries. * * @return * the number of entries in this expiry folder, always &gt;= 0. */ public int size() { int size; synchronized (_recentlyAccessed) { synchronized (_slots) { size = _recentlyAccessed.size(); for (int i = 0; i < _slots.length; i++) { size += _slots[i].size(); } } } return size; } /** * Checks if this folder is completely empty. * * @return * <code>true</code> if and only if there are no entries in this folder. */ public boolean isEmpty() { synchronized (_recentlyAccessed) { if (_recentlyAccessed.isEmpty() == false) { return false; } } for (int i = 0; i < _slots.length; i++) { Map slot = _slots[i]; synchronized (slot) { if (slot.isEmpty() == false) { return false; } } } return true; } /** * Gets the value associated with a key. * * @param key * the key to lookup, cannot be <code>null</code>. * * @return * the value associated with the specified key, or <code>null</code> if * and only if this folder does not contain an entry with the specified * key. * * @throws IllegalArgumentException * if <code>key == null</code>. */ public Object get(Object key) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("key", key); // Check _recentlyAccessed synchronized (_recentlyAccessed) { Object o = _recentlyAccessed.get(key); if (o != null) { return o; } } // Check all slots for (int i = 0; i < _slots.length; i++) { Map slot = _slots[i]; synchronized (slot) { Object o = slot.get(key); if (o != null) { return o; } } } return null; } /** * Associates the specified value with the specified key in this folder. * * @param key * they key for the entry, cannot be <code>null</code>. * * @param value * they value for the entry, cannot be <code>null</code>. * * @throws IllegalArgumentException * if <code>key == null || value == null</code>. */ public void put(Object key, Object value) throws IllegalArgumentException { // Check preconditions MandatoryArgumentChecker.check("key", key, "value", value); synchronized (_recentlyAccessed) { _recentlyAccessed.put(key, value); } } /** * Removes all entries. */ public void clear() { synchronized (_recentlyAccessed) { _recentlyAccessed.clear(); for (int i = 0; i < _slots.length; i++) { Map slot = _slots[i]; synchronized (slot) { slot.clear(); } } } } }
Fixed Javadoc comment.
src/java-common/org/xins/util/collections/expiry/ExpiryFolder.java
Fixed Javadoc comment.
<ide><path>rc/java-common/org/xins/util/collections/expiry/ExpiryFolder.java <ide> //------------------------------------------------------------------------- <ide> <ide> /** <del> * Constructs a new <code>ExpiryMap</code>. <add> * Constructs a new <code>ExpiryFolder</code>. <ide> * <ide> * @param strategy <ide> * the strategy that should be applied, not <code>null</code>.
Java
mit
873cef3e52c70aa6158080d5db6064868c17ae02
0
cs2103aug2014-t09-4j/main
//@author A0115160X package bakatxt.core; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; public class BakaParser implements BakaParserInterface { private static final String STRING_EMPTY = ""; private static final String STRING_SPACE = " "; private static final String STRING_ADD = "@"; private static final String STRING_DOUBLE_DASH = "--"; private static final String STRING_COMMA = ","; private static final String STRING_AT = "at"; private static final String STRING_ON = "on"; private static final String STRING_TO = "to"; private static final String STRING_DASH = "-"; private static final String STRING_YEAR = "2014"; private static final String STRING_YEAR_FRAG = "20"; private static final String STRING_CANT_PARSE = "vista"; private static final String STRING_REPLACEMENT = "\\/ista"; private static final String STRING_TMR = "tomorrow"; private static final String STRING_TODAY = "today"; private static final String STRING_TONIGHT = "tonight"; private static final String STRING_TONIGHT_TIME = "1900"; private static final String DATE_FORMAT_DDMMYY_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])[/-](\\d\\d)"; private static final String DATE_FORMAT_DDMMYYYY_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])[/-]((19|2[01])\\d\\d)"; private static final String DATE_FORMAT_DDMM_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])"; private static final String DATE_FORMAT_DIVIDER_REGEX = "[/-]"; private static final String DATE_FORMAT_STANDARD = "yyyy-MM-dd"; private static final String DISABLE_NUMBER_REGEX = "\\d{3,}?"; private static final String DISABLE_PARSING_REGEX = "(([0-2]\\d[0-5]\\d)|(\\d{1,2}))[^h]"; private static final String DISABLE_FAKE_TIME_REGEX = "\\D\\S+\\d"; private static boolean _isDate; private static boolean _isTime; private static boolean _isVenue; private static boolean _isDescription; private static boolean _isExceptionString; private static String _title; private static String _date; private static String _time; private static String _endTime; private static String _venue; private static String _description; private static String _inputDate; private static String _inputTime; private static String _inputDateThatCantParse; private static ArrayList<String> _inputThatCantParse; public BakaParser() { _isDate = false; _isTime = false; _isVenue = false; _isDescription = false; } /** * Takes in a String and parse it. First, the description will be * identified, followed by the date, time, venue and title. * * @param str * is the <code>String</code> containing the command and details * @return task containing the parsed information */ @Override public Task add(String str) { resetDetails(); String firstWord = getFirstWord(str); if (firstWord.toLowerCase().equals("add")) { str = str.replaceFirst(firstWord, STRING_EMPTY).trim(); } if (str.contains(STRING_DOUBLE_DASH)) { str = str.replace(STRING_DOUBLE_DASH + STRING_SPACE, STRING_DOUBLE_DASH); identifyDescription(str); str = replaceDescription(str); } if (str.contains(STRING_CANT_PARSE)) { str = str.replaceAll(STRING_CANT_PARSE, STRING_REPLACEMENT); _isExceptionString = true; } if (str.contains(STRING_ADD)) { str = str.replace(STRING_ADD + STRING_SPACE, STRING_ADD); } identifyDate(str); if (_date != null) { _isDate = true; } identifyTime(str); if (_time != null) { _isTime = true; } if (_isExceptionString) { str = str.replaceAll(STRING_REPLACEMENT, STRING_CANT_PARSE); } if (str.contains(STRING_ADD)) { identifyVenue(str); } identifyTitle(str); Task task = new Task(_title); task.setDate(_date); if (_time != null) { String[] part = _time.split(STRING_DASH); _time = part[0].trim(); if (part.length > 1) { _endTime = part[1].trim(); } } task.setTime(_time); task.setEndTime(_endTime); task.setVenue(_venue); task.setDescription(_description); if (!_isDate && !_isTime) { task.setFloating(true); } return task; } private static String getFirstWord(String input) { String[] part = input.split(STRING_SPACE); return part[0].trim(); } private static void resetDetails() { _date = null; _time = null; _endTime = null; _venue = null; _description = null; _inputThatCantParse = new ArrayList<String>(); } private static String replaceDateTimeDescription(String input) { if (_isDate) { input = input.replace(_inputDate, STRING_SPACE); if (_inputDateThatCantParse != null) { input = input.replace(_inputDateThatCantParse, STRING_SPACE); } } if (_isTime) { input = input.replace(_inputTime, STRING_SPACE); } if (_isDescription) { input = replaceDescription(input); } return input; } private static String removePrepositions(String input) { input = input.replace("\\s+", "\\s"); String[] part = input.trim().split(STRING_SPACE); do { int lastIndex = part.length - 1; if (part[lastIndex].equals(STRING_AT) || part[lastIndex].equals(STRING_ON)) { input = input.substring(0, input.length() - 2).trim(); } part = input.split(STRING_SPACE); } while (part[part.length - 1].equals(STRING_AT) || part[part.length - 1].equals(STRING_ON)); return input; } private static String replaceDescription(String input) { if (_isDescription) { String descriptionTemp = STRING_DOUBLE_DASH + _description; input = input.replace(descriptionTemp, STRING_SPACE).trim(); } return input; } private static void identifyTitle(String input) { input = replaceDateTimeDescription(input); if (_isVenue) { String venueTemp = STRING_ADD + _venue; input = input.replace(venueTemp, STRING_SPACE); } input = input.trim(); if (input.isEmpty()) { _title = input; } else { _title = removePrepositions(input).trim(); } } private static void identifyDescription(String input) { String[] part = input.split(STRING_DOUBLE_DASH); _description = part[1].trim(); _isDescription = true; } private static void identifyVenue(String input) { input = replaceDateTimeDescription(input); int index = input.indexOf(STRING_ADD) + 1; _isVenue = true; input = input.substring(index).trim(); _venue = removePrepositions(input).trim(); } private static void identifyDate(String input) { Parser parser = new Parser(); String[] temp = input.split(STRING_SPACE); String newDate; String[] dateFragment; for (int i = 0; i < temp.length; i++) { String messageFragment = temp[i]; String originalFragment = temp[i]; // dd/MM/YY or dd/MM/YYYY or dd/MM if (messageFragment.matches(DATE_FORMAT_DDMMYYYY_REGEX) || messageFragment.matches(DATE_FORMAT_DDMMYY_REGEX) || messageFragment.matches(DATE_FORMAT_DDMM_REGEX)) { // dd/MM if (messageFragment.length() <= 5 && messageFragment.length() > 2) { messageFragment = messageFragment + STRING_DASH + STRING_YEAR; } dateFragment = messageFragment.split(DATE_FORMAT_DIVIDER_REGEX); if (dateFragment[2].length() == 2) { dateFragment[2] = STRING_YEAR_FRAG + dateFragment[2]; } newDate = dateFragment[2] + STRING_DASH + dateFragment[1] + STRING_DASH + dateFragment[0]; input = input.replace(originalFragment, newDate); _inputDateThatCantParse = originalFragment; } if (input.contains(STRING_TMR)) { _inputDateThatCantParse = STRING_TMR; } if (input.contains(STRING_TODAY)) { _inputDateThatCantParse = STRING_TODAY; } if (messageFragment.matches(DISABLE_NUMBER_REGEX) || messageFragment.matches(DISABLE_PARSING_REGEX) || messageFragment.matches(DISABLE_FAKE_TIME_REGEX)) { _inputThatCantParse.add(originalFragment); input = input.replace(originalFragment, STRING_SPACE); } } List<DateGroup> dateGroup = parser.parse(input); if (dateGroup.size() > 0) { Date date = dateGroup.get(0).getDates().get(0); _inputDate = dateGroup.get(0).getText(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( DATE_FORMAT_STANDARD); String output = DATE_FORMAT.format(date); _date = output; } else { _date = null; } } private static void identifyTime(String input) { Parser parser = new Parser(); if (_inputDateThatCantParse != null) { input = input.replace(_inputDateThatCantParse, STRING_SPACE); } for (int i = 0; i < _inputThatCantParse.size(); i++) { input = input.replace(_inputThatCantParse.get(i), STRING_SPACE); } if (input.contains(STRING_TONIGHT)) { input = input.replace(STRING_TONIGHT, STRING_TONIGHT_TIME); } List<DateGroup> dateGroup = parser.parse(input); if (dateGroup.size() > 0) { Date timeStart = null; Date timeEnd = null; String output; if (dateGroup.get(0).getDates().size() == 1) { timeStart = dateGroup.get(0).getDates().get(0); } else { timeStart = dateGroup.get(0).getDates().get(0); timeEnd = dateGroup.get(0).getDates().get(1); } _inputTime = dateGroup.get(0).getText(); SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HHmm"); String outputStart = TIME_FORMAT.format(timeStart); if (timeEnd != null) { String outputEnd = TIME_FORMAT.format(timeEnd); output = outputStart + STRING_SPACE + STRING_DASH + STRING_SPACE + outputEnd; } else { output = outputStart; } _time = output; } else { _time = null; } } /** * @param input * a <code>String</code> that contains a command and details. * @return <code>String</code> of details without the command. */ @Override public String getString(String input) { int index = input.indexOf(STRING_SPACE); input = input.substring(index).trim(); return input; } /** * @param input * a <code>String</code> that contains a command and details. * @return <code>String</code> of the command without the details. */ @Override public String getCommand(String input) { String[] part = input.split(STRING_SPACE); return part[0].toUpperCase(); } /** * Creates an <code>ArrayList</code> of <code>Integer</code> from the input * <code>String</code>. When there is more than one index, the indices are * identified by a comma, a space, a dash or "to". * * @param input * a <code>String</code> containing the indices or a range of * indices. * @return an <code>ArrayList</code> of the indices. */ @Override public ArrayList<Integer> getIndexList(String input) { input = input.trim(); ArrayList<Integer> list = new ArrayList<Integer>(); String[] num; if (input.contains(STRING_DASH) || input.contains(STRING_TO)) { input = input.replaceAll("\\s+", STRING_EMPTY); if (input.contains(STRING_DASH)) { num = input.split(STRING_DASH); } else { num = input.split(STRING_TO); } int firstIndex = Integer.valueOf(num[0]); int lastIndex = Integer.valueOf(num[1]); for (int i = firstIndex; i <= lastIndex; i++) { list.add(i); } } else { if (input.contains(STRING_COMMA)) { num = input.split(STRING_COMMA); } else { num = input.split("\\s+"); } for (int i = 0; i < num.length; i++) { list.add(Integer.valueOf(num[i].trim())); } } return list; } /** * Takes in a String and parse the date. * * @param input * a <code>String</code> containing a date. * @return a <code>String</code> of the date in YYYY-MM-DD format or null * when the input cannot be parsed. */ @Override public String getDate(String input) { if (input != null) { identifyDate(input); } else { _date = null; } return _date; } /** * Takes in a String and parse the time. * * @param input * a <code>String</code> containing a time. * @return a <code>String</code> of the time in HHHH, 24 hours format or * null when the input cannot be parsed. */ @Override public String getTime(String input) { if (input != null) { identifyTime(input); } else { _time = null; } return _time; } }
src/bakatxt/core/BakaParser.java
//@author A0115160X package bakatxt.core; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import com.joestelmach.natty.DateGroup; import com.joestelmach.natty.Parser; public class BakaParser implements BakaParserInterface { private static final String STRING_EMPTY = ""; private static final String STRING_SPACE = " "; private static final String STRING_ADD = "@"; private static final String STRING_DOUBLE_DASH = "--"; private static final String STRING_COMMA = ","; private static final String STRING_AT = "at"; private static final String STRING_ON = "on"; private static final String STRING_TO = "to"; private static final String STRING_DASH = "-"; private static final String STRING_YEAR = "2014"; private static final String STRING_YEAR_FRAG = "20"; private static final String STRING_CANT_PARSE = "vista"; private static final String STRING_REPLACEMENT = "\\/ista"; private static final String STRING_TMR = "tomorrow"; private static final String STRING_TODAY = "today"; private static final String STRING_TONIGHT = "tonight"; private static final String STRING_TONIGHT_TIME = "1900"; private static final String DATE_FORMAT_DDMMYY_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])[/-](\\d\\d)"; private static final String DATE_FORMAT_DDMMYYYY_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])[/-]((19|2[01])\\d\\d)"; private static final String DATE_FORMAT_DDMM_REGEX = "(0?[12]?[0-9]|3[01])[/-](0?[1-9]|1[012])"; private static final String DATE_FORMAT_DIVIDER_REGEX = "[/-]"; private static final String DATE_FORMAT_STANDARD = "yyyy-MM-dd"; private static final String DISABLE_NUMBER_REGEX = "\\d{3,}?"; private static final String DISABLE_PARSING_REGEX = "(([0-2]\\d[0-5]\\d)|(\\d{1,2}))[^h]"; private static final String DISABLE_FAKE_TIME_REGEX = "\\D+\\d"; private static boolean _isDate; private static boolean _isTime; private static boolean _isVenue; private static boolean _isDescription; private static boolean _isExceptionString; private static String _title; private static String _date; private static String _time; private static String _endTime; private static String _venue; private static String _description; private static String _inputDate; private static String _inputTime; private static String _inputDateThatCantParse; private static ArrayList<String> _inputThatCantParse; public BakaParser() { _isDate = false; _isTime = false; _isVenue = false; _isDescription = false; } /** * Takes in a String and parse it. First, the description will be * identified, followed by the date, time, venue and title. * * @param str * is the <code>String</code> containing the command and details * @return task containing the parsed information */ @Override public Task add(String str) { resetDetails(); String firstWord = getFirstWord(str); if (firstWord.toLowerCase().equals("add")) { str = str.replaceFirst(firstWord, STRING_EMPTY).trim(); } if (str.contains(STRING_DOUBLE_DASH)) { str = str.replace(STRING_DOUBLE_DASH + STRING_SPACE, STRING_DOUBLE_DASH); identifyDescription(str); str = replaceDescription(str); } if (str.contains(STRING_CANT_PARSE)) { str = str.replaceAll(STRING_CANT_PARSE, STRING_REPLACEMENT); _isExceptionString = true; } if (str.contains(STRING_ADD)) { str = str.replace(STRING_ADD + STRING_SPACE, STRING_ADD); } identifyDate(str); if (_date != null) { _isDate = true; } identifyTime(str); if (_time != null) { _isTime = true; } if (_isExceptionString) { str = str.replaceAll(STRING_REPLACEMENT, STRING_CANT_PARSE); } if (str.contains(STRING_ADD)) { identifyVenue(str); } identifyTitle(str); Task task = new Task(_title); task.setDate(_date); if (_time != null) { String[] part = _time.split(STRING_DASH); _time = part[0].trim(); if (part.length > 1) { _endTime = part[1].trim(); } } task.setTime(_time); task.setEndTime(_endTime); task.setVenue(_venue); task.setDescription(_description); if (!_isDate && !_isTime) { task.setFloating(true); } return task; } private static String getFirstWord(String input) { String[] part = input.split(STRING_SPACE); return part[0].trim(); } private static void resetDetails() { _date = null; _time = null; _endTime = null; _venue = null; _description = null; _inputThatCantParse = new ArrayList<String>(); } private static String replaceDateTimeDescription(String input) { if (_isDate) { input = input.replace(_inputDate, STRING_SPACE); if (_inputDateThatCantParse != null) { input = input.replace(_inputDateThatCantParse, STRING_SPACE); } } if (_isTime) { input = input.replace(_inputTime, STRING_SPACE); } if (_isDescription) { input = replaceDescription(input); } return input; } private static String removePrepositions(String input) { input = input.replace("\\s+", "\\s"); String[] part = input.trim().split(STRING_SPACE); do { int lastIndex = part.length - 1; if (part[lastIndex].equals(STRING_AT) || part[lastIndex].equals(STRING_ON)) { input = input.substring(0, input.length() - 2).trim(); } part = input.split(STRING_SPACE); } while (part[part.length - 1].equals(STRING_AT) || part[part.length - 1].equals(STRING_ON)); return input; } private static String replaceDescription(String input) { if (_isDescription) { String descriptionTemp = STRING_DOUBLE_DASH + _description; input = input.replace(descriptionTemp, STRING_SPACE).trim(); } return input; } private static void identifyTitle(String input) { input = replaceDateTimeDescription(input); if (_isVenue) { String venueTemp = STRING_ADD + _venue; input = input.replace(venueTemp, STRING_SPACE); } input = input.trim(); if (input.isEmpty()) { _title = input; } else { _title = removePrepositions(input).trim(); } } private static void identifyDescription(String input) { String[] part = input.split(STRING_DOUBLE_DASH); _description = part[1].trim(); _isDescription = true; } private static void identifyVenue(String input) { input = replaceDateTimeDescription(input); int index = input.indexOf(STRING_ADD) + 1; _isVenue = true; input = input.substring(index).trim(); _venue = removePrepositions(input).trim(); } private static void identifyDate(String input) { Parser parser = new Parser(); String[] temp = input.split(STRING_SPACE); String newDate; String[] dateFragment; for (int i = 0; i < temp.length; i++) { String messageFragment = temp[i]; String originalFragment = temp[i]; // dd/MM/YY or dd/MM/YYYY or dd/MM if (messageFragment.matches(DATE_FORMAT_DDMMYYYY_REGEX) || messageFragment.matches(DATE_FORMAT_DDMMYY_REGEX) || messageFragment.matches(DATE_FORMAT_DDMM_REGEX)) { // dd/MM if (messageFragment.length() <= 5 && messageFragment.length() > 2) { messageFragment = messageFragment + STRING_DASH + STRING_YEAR; } dateFragment = messageFragment.split(DATE_FORMAT_DIVIDER_REGEX); if (dateFragment[2].length() == 2) { dateFragment[2] = STRING_YEAR_FRAG + dateFragment[2]; } newDate = dateFragment[2] + STRING_DASH + dateFragment[1] + STRING_DASH + dateFragment[0]; input = input.replace(originalFragment, newDate); _inputDateThatCantParse = originalFragment; } if (input.contains(STRING_TMR)) { _inputDateThatCantParse = STRING_TMR; } if (input.contains(STRING_TODAY)) { _inputDateThatCantParse = STRING_TODAY; } if (messageFragment.matches(DISABLE_NUMBER_REGEX) || messageFragment.matches(DISABLE_PARSING_REGEX) || messageFragment.matches(DISABLE_FAKE_TIME_REGEX)) { _inputThatCantParse.add(originalFragment); input = input.replace(originalFragment, STRING_SPACE); } } List<DateGroup> dateGroup = parser.parse(input); if (dateGroup.size() > 0) { Date date = dateGroup.get(0).getDates().get(0); _inputDate = dateGroup.get(0).getText(); SimpleDateFormat DATE_FORMAT = new SimpleDateFormat( DATE_FORMAT_STANDARD); String output = DATE_FORMAT.format(date); _date = output; } else { _date = null; } } private static void identifyTime(String input) { Parser parser = new Parser(); if (_inputDateThatCantParse != null) { input = input.replace(_inputDateThatCantParse, STRING_SPACE); } for (int i = 0; i < _inputThatCantParse.size(); i++) { input = input.replace(_inputThatCantParse.get(i), STRING_SPACE); } if (input.contains(STRING_TONIGHT)) { input = input.replace(STRING_TONIGHT, STRING_TONIGHT_TIME); } List<DateGroup> dateGroup = parser.parse(input); if (dateGroup.size() > 0) { Date timeStart = null; Date timeEnd = null; String output; if (dateGroup.get(0).getDates().size() == 1) { timeStart = dateGroup.get(0).getDates().get(0); } else { timeStart = dateGroup.get(0).getDates().get(0); timeEnd = dateGroup.get(0).getDates().get(1); } _inputTime = dateGroup.get(0).getText(); SimpleDateFormat TIME_FORMAT = new SimpleDateFormat("HHmm"); String outputStart = TIME_FORMAT.format(timeStart); if (timeEnd != null) { String outputEnd = TIME_FORMAT.format(timeEnd); output = outputStart + STRING_SPACE + STRING_DASH + STRING_SPACE + outputEnd; } else { output = outputStart; } _time = output; } else { _time = null; } } /** * @param input * a <code>String</code> that contains a command and details. * @return <code>String</code> of details without the command. */ @Override public String getString(String input) { int index = input.indexOf(STRING_SPACE); input = input.substring(index).trim(); return input; } /** * @param input * a <code>String</code> that contains a command and details. * @return <code>String</code> of the command without the details. */ @Override public String getCommand(String input) { String[] part = input.split(STRING_SPACE); return part[0].toUpperCase(); } /** * Creates an <code>ArrayList</code> of <code>Integer</code> from the input * <code>String</code>. When there is more than one index, the indices are * identified by a comma, a space, a dash or "to". * * @param input * a <code>String</code> containing the indices or a range of * indices. * @return an <code>ArrayList</code> of the indices. */ @Override public ArrayList<Integer> getIndexList(String input) { input = input.trim(); ArrayList<Integer> list = new ArrayList<Integer>(); String[] num; if (input.contains(STRING_DASH) || input.contains(STRING_TO)) { input = input.replaceAll("\\s+", STRING_EMPTY); if (input.contains(STRING_DASH)) { num = input.split(STRING_DASH); } else { num = input.split(STRING_TO); } int firstIndex = Integer.valueOf(num[0]); int lastIndex = Integer.valueOf(num[1]); for (int i = firstIndex; i <= lastIndex; i++) { list.add(i); } } else { if (input.contains(STRING_COMMA)) { num = input.split(STRING_COMMA); } else { num = input.split("\\s+"); } for (int i = 0; i < num.length; i++) { list.add(Integer.valueOf(num[i].trim())); } } return list; } /** * Takes in a String and parse the date. * * @param input * a <code>String</code> containing a date. * @return a <code>String</code> of the date in YYYY-MM-DD format or null * when the input cannot be parsed. */ @Override public String getDate(String input) { if (input != null) { identifyDate(input); } else { _date = null; } return _date; } /** * Takes in a String and parse the time. * * @param input * a <code>String</code> containing a time. * @return a <code>String</code> of the time in HHHH, 24 hours format or * null when the input cannot be parsed. */ @Override public String getTime(String input) { if (input != null) { identifyTime(input); } else { _time = null; } return _time; } }
Edit one of the existing regex
src/bakatxt/core/BakaParser.java
Edit one of the existing regex
<ide><path>rc/bakatxt/core/BakaParser.java <ide> private static final String DATE_FORMAT_STANDARD = "yyyy-MM-dd"; <ide> private static final String DISABLE_NUMBER_REGEX = "\\d{3,}?"; <ide> private static final String DISABLE_PARSING_REGEX = "(([0-2]\\d[0-5]\\d)|(\\d{1,2}))[^h]"; <del> private static final String DISABLE_FAKE_TIME_REGEX = "\\D+\\d"; <add> private static final String DISABLE_FAKE_TIME_REGEX = "\\D\\S+\\d"; <ide> <ide> private static boolean _isDate; <ide> private static boolean _isTime;
Java
apache-2.0
3565112ec588b5e1d8280a0ecbaf5eae94bdc094
0
apache/directory-project
/* * 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.mina.transport.vmpipe.support; import java.io.IOException; import java.net.SocketAddress; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.common.support.BaseIoSessionConfig; import org.apache.mina.common.support.IoServiceListenerSupport; import org.apache.mina.util.Queue; /** * A {@link IoSession} for in-VM transport (VM_PIPE). * * @author The Apache Directory Project ([email protected]) * @version $Rev$, $Date$ */ public class VmPipeSessionImpl extends BaseIoSession { private static final IoSessionConfig CONFIG = new BaseIoSessionConfig() {}; private final IoService service; private final IoServiceConfig serviceConfig; private final IoServiceListenerSupport serviceListeners; private final SocketAddress localAddress; private final SocketAddress remoteAddress; private final SocketAddress serviceAddress; private final IoHandler handler; private final VmPipeFilterChain filterChain; final VmPipeSessionImpl remoteSession; final Object lock; final Queue pendingDataQueue; /** * Constructor for client-side session. */ public VmPipeSessionImpl( IoService service, IoServiceConfig serviceConfig, IoServiceListenerSupport serviceListeners, Object lock, SocketAddress localAddress, IoHandler handler, VmPipe remoteEntry ) throws IOException { this.service = service; this.serviceConfig = serviceConfig; this.serviceListeners = serviceListeners; this.lock = lock; this.localAddress = localAddress; this.remoteAddress = this.serviceAddress = remoteEntry.getAddress(); this.handler = handler; this.filterChain = new VmPipeFilterChain( this ); this.pendingDataQueue = new Queue(); remoteSession = new VmPipeSessionImpl( this, remoteEntry ); // initialize connector session try { service.getFilterChainBuilder().buildFilterChain( filterChain ); serviceConfig.getFilterChainBuilder().buildFilterChain( filterChain ); serviceConfig.getThreadModel().buildFilterChain( filterChain ); serviceListeners.fireSessionCreated( this ); } catch( Throwable t ) { throw ( IOException ) new IOException( "Failed to create a connector session." ).initCause( t ); } VmPipeIdleStatusChecker.getInstance().addSession( this ); } /** * Constructor for server-side session. */ private VmPipeSessionImpl( VmPipeSessionImpl remoteSession, VmPipe entry ) throws IOException { this.service = entry.getAcceptor(); this.serviceConfig = entry.getConfig(); this.serviceListeners = entry.getListeners(); this.lock = remoteSession.lock; this.localAddress = this.serviceAddress = remoteSession.remoteAddress; this.remoteAddress = remoteSession.localAddress; this.handler = entry.getHandler(); this.filterChain = new VmPipeFilterChain( this ); this.remoteSession = remoteSession; this.pendingDataQueue = new Queue(); // initialize acceptor session try { entry.getAcceptor().getFilterChainBuilder().buildFilterChain( this.getFilterChain() ); entry.getConfig().getFilterChainBuilder().buildFilterChain( this.getFilterChain() ); entry.getConfig().getThreadModel().buildFilterChain( this.getFilterChain() ); serviceListeners.fireSessionCreated( this ); } catch( Throwable t ) { ExceptionMonitor.getInstance().exceptionCaught( t ); IOException e = new IOException( "Failed to initialize acceptor session." ); e.initCause( t ); throw e; } VmPipeIdleStatusChecker.getInstance().addSession( this ); } public IoService getService() { return service; } IoServiceListenerSupport getServiceListeners() { return serviceListeners; } public IoServiceConfig getServiceConfig() { return serviceConfig; } public IoSessionConfig getConfig() { return CONFIG; } public IoFilterChain getFilterChain() { return filterChain; } public IoHandler getHandler() { return handler; } protected void close0() { filterChain.fireFilterClose( this ); } protected void write0( WriteRequest writeRequest ) { this.filterChain.fireFilterWrite( this, writeRequest ); } public int getScheduledWriteRequests() { return 0; } public int getScheduledWriteBytes() { return 0; } public TransportType getTransportType() { return TransportType.VM_PIPE; } public SocketAddress getRemoteAddress() { return remoteAddress; } public SocketAddress getLocalAddress() { return localAddress; } public SocketAddress getServiceAddress() { return serviceAddress; } protected void updateTrafficMask() { if( getTrafficMask().isReadable() || getTrafficMask().isWritable()) { Object[] data; synchronized( pendingDataQueue ) { data = pendingDataQueue.toArray(); pendingDataQueue.clear(); } for( int i = 0; i < data.length; i++ ) { if( data[ i ] instanceof WriteRequest ) { WriteRequest wr = ( WriteRequest ) data[ i ]; filterChain.doWrite( this, wr ); } else { filterChain.fireMessageReceived( this, data[ i ] ); } } } } }
mina/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeSessionImpl.java
/* * 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.mina.transport.vmpipe.support; import java.io.IOException; import java.net.SocketAddress; import org.apache.mina.common.ExceptionMonitor; import org.apache.mina.common.IoFilterChain; import org.apache.mina.common.IoHandler; import org.apache.mina.common.IoService; import org.apache.mina.common.IoServiceConfig; import org.apache.mina.common.IoSession; import org.apache.mina.common.IoSessionConfig; import org.apache.mina.common.TransportType; import org.apache.mina.common.IoFilter.WriteRequest; import org.apache.mina.common.support.BaseIoSession; import org.apache.mina.common.support.BaseIoSessionConfig; import org.apache.mina.common.support.IoServiceListenerSupport; import org.apache.mina.util.Queue; /** * A {@link IoSession} for in-VM transport (VM_PIPE). * * @author The Apache Directory Project ([email protected]) * @version $Rev$, $Date$ */ public class VmPipeSessionImpl extends BaseIoSession { private static final IoSessionConfig CONFIG = new BaseIoSessionConfig() {}; private final IoService service; private final IoServiceConfig serviceConfig; private final IoServiceListenerSupport serviceListeners; private final SocketAddress localAddress; private final SocketAddress remoteAddress; private final SocketAddress serviceAddress; private final IoHandler handler; private final VmPipeFilterChain filterChain; final VmPipeSessionImpl remoteSession; final Object lock; final Queue pendingDataQueue; /** * Constructor for client-side session. */ public VmPipeSessionImpl( IoService service, IoServiceConfig serviceConfig, IoServiceListenerSupport serviceListeners, Object lock, SocketAddress localAddress, IoHandler handler, VmPipe remoteEntry ) throws IOException { this.service = service; this.serviceConfig = serviceConfig; this.serviceListeners = serviceListeners; this.lock = lock; this.localAddress = localAddress; this.remoteAddress = this.serviceAddress = remoteEntry.getAddress(); this.handler = handler; this.filterChain = new VmPipeFilterChain( this ); this.pendingDataQueue = new Queue(); remoteSession = new VmPipeSessionImpl( service, this, remoteEntry ); // initialize connector session try { service.getFilterChainBuilder().buildFilterChain( filterChain ); serviceConfig.getFilterChainBuilder().buildFilterChain( filterChain ); serviceConfig.getThreadModel().buildFilterChain( filterChain ); serviceListeners.fireSessionCreated( this ); } catch( Throwable t ) { throw ( IOException ) new IOException( "Failed to create a connector session." ).initCause( t ); } VmPipeIdleStatusChecker.getInstance().addSession( this ); } /** * Constructor for server-side session. */ private VmPipeSessionImpl( IoService service, VmPipeSessionImpl remoteSession, VmPipe entry ) throws IOException { this.service = service; this.serviceConfig = entry.getConfig(); this.serviceListeners = entry.getListeners(); this.lock = remoteSession.lock; this.localAddress = this.serviceAddress = remoteSession.remoteAddress; this.remoteAddress = remoteSession.localAddress; this.handler = entry.getHandler(); this.filterChain = new VmPipeFilterChain( this ); this.remoteSession = remoteSession; this.pendingDataQueue = new Queue(); // initialize acceptor session try { entry.getAcceptor().getFilterChainBuilder().buildFilterChain( this.getFilterChain() ); entry.getConfig().getFilterChainBuilder().buildFilterChain( this.getFilterChain() ); entry.getConfig().getThreadModel().buildFilterChain( this.getFilterChain() ); serviceListeners.fireSessionCreated( this ); } catch( Throwable t ) { ExceptionMonitor.getInstance().exceptionCaught( t ); IOException e = new IOException( "Failed to initialize acceptor session." ); e.initCause( t ); throw e; } VmPipeIdleStatusChecker.getInstance().addSession( this ); } public IoService getService() { return service; } IoServiceListenerSupport getServiceListeners() { return serviceListeners; } public IoServiceConfig getServiceConfig() { return serviceConfig; } public IoSessionConfig getConfig() { return CONFIG; } public IoFilterChain getFilterChain() { return filterChain; } public IoHandler getHandler() { return handler; } protected void close0() { filterChain.fireFilterClose( this ); } protected void write0( WriteRequest writeRequest ) { this.filterChain.fireFilterWrite( this, writeRequest ); } public int getScheduledWriteRequests() { return 0; } public int getScheduledWriteBytes() { return 0; } public TransportType getTransportType() { return TransportType.VM_PIPE; } public SocketAddress getRemoteAddress() { return remoteAddress; } public SocketAddress getLocalAddress() { return localAddress; } public SocketAddress getServiceAddress() { return serviceAddress; } protected void updateTrafficMask() { if( getTrafficMask().isReadable() || getTrafficMask().isWritable()) { Object[] data = null; synchronized( pendingDataQueue ) { data = pendingDataQueue.toArray(); pendingDataQueue.clear(); } for( int i = 0; i < data.length; i++ ) { if( data[ i ] instanceof WriteRequest ) { WriteRequest wr = ( WriteRequest ) data[ i ]; filterChain.doWrite( this, wr ); } else { filterChain.fireMessageReceived( this, data[ i ] ); } } } } }
DIRMINA-264 - Put the right Service on the remote end. git-svn-id: 5c3b06693d750a6aefbf1081b6b7d57c0165fdb2@446658 13f79535-47bb-0310-9956-ffa450edef68
mina/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeSessionImpl.java
DIRMINA-264 - Put the right Service on the remote end.
<ide><path>ina/core/src/main/java/org/apache/mina/transport/vmpipe/support/VmPipeSessionImpl.java <ide> this.filterChain = new VmPipeFilterChain( this ); <ide> this.pendingDataQueue = new Queue(); <ide> <del> remoteSession = new VmPipeSessionImpl( service, this, remoteEntry ); <add> remoteSession = new VmPipeSessionImpl( this, remoteEntry ); <ide> <ide> // initialize connector session <ide> try <ide> /** <ide> * Constructor for server-side session. <ide> */ <del> private VmPipeSessionImpl( IoService service, VmPipeSessionImpl remoteSession, VmPipe entry ) throws IOException <del> { <del> this.service = service; <add> private VmPipeSessionImpl( VmPipeSessionImpl remoteSession, VmPipe entry ) throws IOException <add> { <add> this.service = entry.getAcceptor(); <ide> this.serviceConfig = entry.getConfig(); <ide> this.serviceListeners = entry.getListeners(); <ide> this.lock = remoteSession.lock; <ide> { <ide> if( getTrafficMask().isReadable() || getTrafficMask().isWritable()) <ide> { <del> Object[] data = null; <add> Object[] data; <ide> synchronized( pendingDataQueue ) <ide> { <ide> data = pendingDataQueue.toArray();
Java
bsd-3-clause
c1139647c17fd1790dc030f5c6dd8229277f2749
0
NCIP/psc,NCIP/psc,NCIP/psc,NCIP/psc
package edu.northwestern.bioinformatics.studycalendar.domain; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Add; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Revision; import edu.northwestern.bioinformatics.studycalendar.domain.scheduledactivitystate.Conditional; import edu.northwestern.bioinformatics.studycalendar.domain.scheduledactivitystate.Scheduled; import edu.northwestern.bioinformatics.studycalendar.domain.scheduledactivitystate.ScheduledActivityState; import edu.northwestern.bioinformatics.studycalendar.service.AmendmentService; import edu.northwestern.bioinformatics.studycalendar.service.DeltaService; import edu.northwestern.bioinformatics.studycalendar.service.StudyService; import edu.northwestern.bioinformatics.studycalendar.service.TemplateSkeletonCreator; import edu.northwestern.bioinformatics.studycalendar.service.TestingTemplateService; import edu.northwestern.bioinformatics.studycalendar.service.delta.MemoryOnlyMutatorFactory; import edu.nwu.bioinformatics.commons.DateUtils; import gov.nih.nci.cabig.ctms.domain.DomainObject; import gov.nih.nci.cabig.ctms.domain.GridIdentifiable; import gov.nih.nci.cabig.ctms.domain.MutableDomainObject; import gov.nih.nci.cabig.ctms.lang.DateTools; import gov.nih.nci.cabig.ctms.lang.StaticNowFactory; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; /** * @author Rhett Sutphin */ public class Fixtures { private static final Logger log = LoggerFactory.getLogger(Fixtures.class); private static final DeltaService deltaService = new DeltaService(); private static final AmendmentService amendmentService = new AmendmentService(); public static final ActivityType DEFAULT_ACTIVITY_TYPE = createActivityType("LAB_TEST"); public static final Source DEFAULT_ACTIVITY_SOURCE = createNamedInstance("Fixtures Source", Source.class); static { deltaService.setMutatorFactory(new MemoryOnlyMutatorFactory()); deltaService.setTemplateService(new TestingTemplateService()); StaticNowFactory nowFactory = new StaticNowFactory(); nowFactory.setNowTimestamp(DateTools.createTimestamp(2000, Calendar.MARCH, 9)); deltaService.setNowFactory(nowFactory); amendmentService.setDeltaService(deltaService); amendmentService.setStudyService(new StudyService() { public void save(Study study) { /* No-op */ } }); } public static <T extends DomainObject> T setId(Integer id, T target) { target.setId(id); return target; } public static Study assignIds(Study study) { return assignIds(study, 0); } public static Study assignIds(Study study, int start) { setIds(start, study); assignIds(study.getPlannedCalendar(), start + 1); return study; } @SuppressWarnings({ "RawUseOfParameterizedType", "unchecked" }) public static <T extends MutableDomainObject> T assignIds(T node, int start) { int i = start; setIds(i, node); if (node instanceof Parent) { for (Object child : ((Parent) node).getChildren()) { i++; assignIds((MutableDomainObject) child, i * 50); } } return node; } public static <T extends MutableDomainObject> T setIds(int base, T target) { target.setId(base); target.setGridId("GRID-" + base); return target; } public static <T extends GridIdentifiable> T setGridId(String gridId, T target) { target.setGridId(gridId); return target; } public static Period createPeriod(int startDay, int dayCount, int repetitions) { return createPeriod(null, startDay, dayCount, repetitions); } public static Period createPeriod(String name, int startDay, int dayCount, int repetitions) { return createPeriod(name, startDay, Duration.Unit.day, dayCount, repetitions); } public static Period createPeriod(String name, int startDay, Duration.Unit dUnit, int dQuantity, int repetitions) { Period p = new Period(); p.setName(name); p.setStartDay(startDay); p.getDuration().setUnit(dUnit); p.getDuration().setQuantity(dQuantity); p.setRepetitions(repetitions); return p; } public static PlannedActivity createPlannedActivity(Activity activity, int day) { PlannedActivity event = new PlannedActivity(); event.setActivity(activity); event.setDay(day); return event; } public static PlannedActivity createPlannedActivity(String activityName, int day) { Activity activity = createActivity(activityName); return createPlannedActivity(activity, day); } public static PlannedActivity createPlannedActivity(String activityName, int day, String details) { PlannedActivity event = createPlannedActivity(activityName, day); event.setDetails(details); return event; } public static PlannedActivity createPlannedActivity(String activityName, int day, String details, String condition) { PlannedActivity event = createPlannedActivity(activityName, day, details); event.setCondition(condition); return event; } public static void labelPlannedActivity(PlannedActivity pa, String... labels) { labelPlannedActivity(pa, null, labels); } public static void labelPlannedActivity(PlannedActivity pa, Integer repetitionNumber, String... labels) { for (String label : labels) { PlannedActivityLabel paLabel = new PlannedActivityLabel(); paLabel.setLabel(label); paLabel.setRepetitionNumber(repetitionNumber); pa.addPlannedActivityLabel(paLabel); } } public static PlannedActivityLabel createPlannedActivityLabel(String label) { PlannedActivityLabel pal = new PlannedActivityLabel(); pal.setLabel(label); return pal; } public static PlannedActivityLabel createPlannedActivityLabel(String label, Integer repetitionNumber) { PlannedActivityLabel pal = createPlannedActivityLabel(label); pal.setRepetitionNumber(repetitionNumber); return pal; } public static PlannedActivityLabel createPlannedActivityLabel(PlannedActivity activity, String label, Integer repetitionNumber) { PlannedActivityLabel paLabel = createPlannedActivityLabel(label, repetitionNumber); paLabel.setPlannedActivity(activity); return paLabel; } public static Study createSingleEpochStudy(String studyName, String epochName, String... studySegmentNames) { Study study = createNamedInstance(studyName, Study.class); study.setPlannedCalendar(new PlannedCalendar()); study.getPlannedCalendar().addEpoch(Epoch.create(epochName, studySegmentNames)); return study; } public static Study createBlankTemplate() { return createApprovedTemplate(TemplateSkeletonCreator.BLANK); } public static Study createBasicTemplate() { return createApprovedTemplate(TemplateSkeletonCreator.BASIC); } private static Study createApprovedTemplate(TemplateSkeletonCreator skeletonCreator) { log.debug("Creating concrete template from skeleton"); Study dev = skeletonCreator.create(null); amendmentService.amend(dev); return dev; } /** * A fixture-compatible version of AmendmentService#amend */ public static void amend(Study study) { amendmentService.amend(study); } public static Study revise(Study study, Revision revision) { return deltaService.revise(study, revision); } public static DeltaService getTestingDeltaService() { return deltaService; } public static StudySite createStudySite(Study study, Site site) { StudySite studySite = new StudySite(); if (study != null) study.addStudySite(studySite); if (site != null) site.addStudySite(studySite); return studySite; } public static Subject createSubject(String firstName, String lastName) { Subject p = new Subject(); p.setFirstName(firstName); p.setLastName(lastName); return p; } public static Subject createSubject(String personId, String firstName, String lastName, Date birthDate, Gender gender) { Subject subject = createSubject(firstName, lastName); subject.setPersonId(personId); subject.setDateOfBirth(birthDate); subject.setGender(gender); return subject; } public static StudySubjectAssignment createAssignment(Study study, Site site, Subject subject) { StudySubjectAssignment assignment = new StudySubjectAssignment(); assignment.setScheduledCalendar(new ScheduledCalendar()); if (subject != null) subject.addAssignment(assignment); StudySite ss = createStudySite(study, site); ss.addStudySubjectAssignment(assignment); return assignment; } public static ScheduledStudySegment createScheduledStudySegment(StudySegment studySegment) { ScheduledStudySegment scheduledStudySegment = new ScheduledStudySegment(); scheduledStudySegment.setStudySegment(studySegment); scheduledStudySegment.setStartDay(1); scheduledStudySegment.setStartDate(DateTools.createDate(1997, Calendar.JANUARY, 12)); return scheduledStudySegment; } public static ScheduledActivity createScheduledActivity( String activityName, int year, int month, int day, ScheduledActivityState state ) { ScheduledActivity scheduled = createScheduledActivity(activityName, year, month, day); scheduled.changeState(state); return scheduled; } public static ScheduledActivity createScheduledActivity( PlannedActivity planned, int year, int month, int day, ScheduledActivityState state ) { ScheduledActivity scheduledActivity = createScheduledActivity(planned, year, month, day); scheduledActivity.changeState(state); return scheduledActivity; } public static ScheduledActivity createScheduledActivity(String activityName, int year, int month, int day) { PlannedActivity baseEvent = createPlannedActivity(activityName, 0); return createScheduledActivity(baseEvent, year, month, day); } public static ScheduledActivity createScheduledActivity(PlannedActivity planned, int year, int month, int day) { ScheduledActivity event = new ScheduledActivity(); event.setPlannedActivity(planned); event.setActivity(planned.getActivity()); event.setIdealDate(DateUtils.createDate(year, month, day - 2)); event.changeState(new Scheduled(null, DateUtils.createDate(year, month, day))); return event; } public static ScheduledActivity createConditionalEvent(String activityName, int year, int month, int day) { PlannedActivity baseEvent = createPlannedActivity(activityName, 0); baseEvent.setCondition("Details"); return createScheduledActivity(baseEvent, year, month, day, new Conditional()); } public static Source createSource(final String name) { return createNamedInstance(name, Source.class); } public static Activity createActivity(String name) { return createActivity(name, DEFAULT_ACTIVITY_TYPE); } public static ActivityType createActivityType(final String name) { return createNamedInstance(name, ActivityType.class); } public static Activity createActivity(String name, ActivityType type) { return createActivity(name, name, DEFAULT_ACTIVITY_SOURCE, type); } public static Activity createActivity(String name, String code, Source source, ActivityType type) { Activity activity = createNamedInstance(name, Activity.class); activity.setId(name.hashCode()); activity.setCode(code); activity.setType(type); if (source != null) { source.addActivity(activity); } return activity; } public static Activity createActivity(String name, String code, Source source, ActivityType type, String description) { Activity activity = createActivity(name, code, source, type); activity.setDescription(description); return activity; } public static void addEvents(ScheduledStudySegment scheduledStudySegment, ScheduledActivity... events) { for (ScheduledActivity event : events) { scheduledStudySegment.addEvent(event); } } public static Site createSite(String name) { return createSite(name, null); } public static Site createSite(String name, String assignedIdentifier) { Site site = createNamedInstance(name, Site.class); site.setAssignedIdentifier(assignedIdentifier); return site; } public static void setUserRoles(User user, Role... roles) { user.clearUserRoles(); for (Role role : roles) { UserRole userRole = new UserRole(user, role); user.getUserRoles().add(userRole); } } public static User createUser(String name, Role... roles) { return createUser(null, name, null, true, roles); } public static User createUser(Integer id, String name, Long csmUserId, boolean activeFlag, Role... roles) { User user = new User(); user.setId(id); user.setName(name); user.setCsmUserId(csmUserId); user.setActiveFlag(activeFlag); setUserRoles(user, roles); return user; } public static UserRole createUserRole(User user, Role role, Site... sites) { UserRole userRole = new UserRole(user, role, sites); user.addUserRole(userRole); return userRole; } public static ProtectionGroup createProtectionGroup(Long aId, String aName) { ProtectionGroup myProtectionGroup = new ProtectionGroup(); myProtectionGroup.setProtectionGroupName(aName); myProtectionGroup.setProtectionGroupId(aId); return myProtectionGroup; } public static <T extends Named> T createNamedInstance(String name, Class<T> clazz) { try { T instance = clazz.newInstance(); instance.setName(name); return instance; } catch (InstantiationException e) { throw new RuntimeException("Creating domain obj of class " + clazz.getName() + " failed", e); } catch (IllegalAccessException e) { throw new RuntimeException("Creating domain obj of class " + clazz.getName() + " failed", e); } } public static Population createPopulation() { return createPopulation("P", "People"); } public static Population createPopulation(String abbreviation, String name) { Population population = new Population(); population.setAbbreviation(abbreviation); population.setName(name); return population; } public static Amendment createAmendment(String name, Date date) { return createAmendment(name, date, true); } public static Amendment createAmendment(String name, Date date, boolean mandatory) { Amendment amendment = new Amendment(); amendment.setMandatory(mandatory); amendment.setName(name); amendment.setDate(date); amendment.setReleasedDate(date); return amendment; } /** * Creates a chain of amendments with the given names, returning the one at the end of the * chain (the most recent one). */ public static Amendment createAmendments(String... nameHistory) { Amendment current = new Amendment(); Calendar cal = Calendar.getInstance(); cal.set(2001, Calendar.JANUARY, 1); for (int i = 0; i < nameHistory.length - 1; i++) { String name = nameHistory[i]; current.setName(name); current.setDate(cal.getTime()); Amendment next = new Amendment(); next.setPreviousAmendment(current); current = next; cal.add(Calendar.DAY_OF_YEAR, 1); } current.setName(nameHistory[nameHistory.length - 1]); return current; } /** * Creates a chain of amendments with the given dates, returning the one at the end of the * chain (the most recent one). */ public static Amendment createAmendments(Date... dateHistory) { Amendment current = new Amendment(); for (int i = 0; i < dateHistory.length - 1; i++) { Date date = dateHistory[i]; current.setDate(date); Amendment next = new Amendment(); next.setPreviousAmendment(current); current = next; } current.setDate(dateHistory[dateHistory.length - 1]); return current; } public static Add createAddChange(Integer newChildId, Integer index) { Add add = new Add(); add.setChildId(newChildId); add.setIndex(index); return add; } // static class private Fixtures() { } }
src/test/java/edu/northwestern/bioinformatics/studycalendar/domain/Fixtures.java
package edu.northwestern.bioinformatics.studycalendar.domain; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Add; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Amendment; import edu.northwestern.bioinformatics.studycalendar.domain.delta.Revision; import edu.northwestern.bioinformatics.studycalendar.domain.scheduledactivitystate.Conditional; import edu.northwestern.bioinformatics.studycalendar.domain.scheduledactivitystate.Scheduled; import edu.northwestern.bioinformatics.studycalendar.domain.scheduledactivitystate.ScheduledActivityState; import edu.northwestern.bioinformatics.studycalendar.service.AmendmentService; import edu.northwestern.bioinformatics.studycalendar.service.DeltaService; import edu.northwestern.bioinformatics.studycalendar.service.StudyService; import edu.northwestern.bioinformatics.studycalendar.service.TemplateSkeletonCreator; import edu.northwestern.bioinformatics.studycalendar.service.TestingTemplateService; import edu.northwestern.bioinformatics.studycalendar.service.delta.MemoryOnlyMutatorFactory; import edu.nwu.bioinformatics.commons.DateUtils; import gov.nih.nci.cabig.ctms.domain.DomainObject; import gov.nih.nci.cabig.ctms.domain.GridIdentifiable; import gov.nih.nci.cabig.ctms.domain.MutableDomainObject; import gov.nih.nci.cabig.ctms.lang.DateTools; import gov.nih.nci.cabig.ctms.lang.StaticNowFactory; import gov.nih.nci.security.authorization.domainobjects.ProtectionGroup; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Calendar; import java.util.Date; /** * @author Rhett Sutphin */ public class Fixtures { private static final Logger log = LoggerFactory.getLogger(Fixtures.class); private static final DeltaService deltaService = new DeltaService(); private static final AmendmentService amendmentService = new AmendmentService(); public static final ActivityType DEFAULT_ACTIVITY_TYPE = createActivityType("LAB_TEST"); public static final Source DEFAULT_ACTIVITY_SOURCE = createNamedInstance("Fixtures Source", Source.class); static { deltaService.setMutatorFactory(new MemoryOnlyMutatorFactory()); deltaService.setTemplateService(new TestingTemplateService()); StaticNowFactory nowFactory = new StaticNowFactory(); nowFactory.setNowTimestamp(DateTools.createTimestamp(2000, Calendar.MARCH, 9)); deltaService.setNowFactory(nowFactory); amendmentService.setDeltaService(deltaService); amendmentService.setStudyService(new StudyService() { public void save(Study study) { /* No-op */ } }); } public static <T extends DomainObject> T setId(Integer id, T target) { target.setId(id); return target; } public static Study assignIds(Study study) { return assignIds(study, 0); } public static Study assignIds(Study study, int start) { setIds(start, study); assignIds(study.getPlannedCalendar(), start + 1); return study; } @SuppressWarnings({ "RawUseOfParameterizedType", "unchecked" }) public static <T extends MutableDomainObject> T assignIds(T node, int start) { int i = start; setIds(i, node); if (node instanceof Parent) { for (Object child : ((Parent) node).getChildren()) { i++; assignIds((MutableDomainObject) child, i * 50); } } return node; } public static <T extends MutableDomainObject> T setIds(int base, T target) { target.setId(base); target.setGridId("GRID-" + base); return target; } public static <T extends GridIdentifiable> T setGridId(String gridId, T target) { target.setGridId(gridId); return target; } public static Period createPeriod(int startDay, int dayCount, int repetitions) { return createPeriod(null, startDay, dayCount, repetitions); } public static Period createPeriod(String name, int startDay, int dayCount, int repetitions) { return createPeriod(name, startDay, Duration.Unit.day, dayCount, repetitions); } public static Period createPeriod(String name, int startDay, Duration.Unit dUnit, int dQuantity, int repetitions) { Period p = new Period(); p.setName(name); p.setStartDay(startDay); p.getDuration().setUnit(dUnit); p.getDuration().setQuantity(dQuantity); p.setRepetitions(repetitions); return p; } public static PlannedActivity createPlannedActivity(Activity activity, int day) { PlannedActivity event = new PlannedActivity(); event.setActivity(activity); event.setDay(day); return event; } public static PlannedActivity createPlannedActivity(String activityName, int day) { Activity activity = createActivity(activityName); return createPlannedActivity(activity, day); } public static PlannedActivity createPlannedActivity(String activityName, int day, String details) { PlannedActivity event = createPlannedActivity(activityName, day); event.setDetails(details); return event; } public static PlannedActivity createPlannedActivity(String activityName, int day, String details, String condition) { PlannedActivity event = createPlannedActivity(activityName, day, details); event.setCondition(condition); return event; } public static void labelPlannedActivity(PlannedActivity pa, String... labels) { labelPlannedActivity(pa, null, labels); } public static void labelPlannedActivity(PlannedActivity pa, Integer repetitionNumber, String... labels) { for (String label : labels) { PlannedActivityLabel paLabel = new PlannedActivityLabel(); paLabel.setLabel(label); paLabel.setRepetitionNumber(repetitionNumber); pa.addPlannedActivityLabel(paLabel); } } public static PlannedActivityLabel createPlannedActivityLabel(String label) { PlannedActivityLabel pal = new PlannedActivityLabel(); pal.setLabel(label); return pal; } public static PlannedActivityLabel createPlannedActivityLabel(String label, Integer repetitionNumber) { PlannedActivityLabel pal = createPlannedActivityLabel(label); pal.setRepetitionNumber(repetitionNumber); return pal; } public static PlannedActivityLabel createPlannedActivityLabel(PlannedActivity activity, String label, Integer repetitionNumber) { PlannedActivityLabel paLabel = createPlannedActivityLabel(label, repetitionNumber); paLabel.setPlannedActivity(activity); return paLabel; } public static Study createSingleEpochStudy(String studyName, String epochName, String... studySegmentNames) { Study study = createNamedInstance(studyName, Study.class); study.setPlannedCalendar(new PlannedCalendar()); study.getPlannedCalendar().addEpoch(Epoch.create(epochName, studySegmentNames)); return study; } public static Study createBlankTemplate() { return createApprovedTemplate(TemplateSkeletonCreator.BLANK); } public static Study createBasicTemplate() { return createApprovedTemplate(TemplateSkeletonCreator.BASIC); } private static Study createApprovedTemplate(TemplateSkeletonCreator skeletonCreator) { log.debug("Creating concrete template from skeleton"); Study dev = skeletonCreator.create(null); amendmentService.amend(dev); return dev; } /** * A fixture-compatible version of AmendmentService#amend */ public static void amend(Study study) { amendmentService.amend(study); } public static Study revise(Study study, Revision revision) { return deltaService.revise(study, revision); } public static DeltaService getTestingDeltaService() { return deltaService; } public static StudySite createStudySite(Study study, Site site) { StudySite studySite = new StudySite(); if (study != null) study.addStudySite(studySite); if (site != null) site.addStudySite(studySite); return studySite; } public static Subject createSubject(String firstName, String lastName) { Subject p = new Subject(); p.setFirstName(firstName); p.setLastName(lastName); return p; } public static Subject createSubject(String personId, String firstName, String lastName, Date birthDate, Gender gender) { Subject subject = createSubject(firstName, lastName); subject.setPersonId(personId); subject.setDateOfBirth(birthDate); subject.setGender(gender); return subject; } public static StudySubjectAssignment createAssignment(Study study, Site site, Subject subject) { StudySubjectAssignment assignment = new StudySubjectAssignment(); assignment.setScheduledCalendar(new ScheduledCalendar()); if (subject != null) subject.addAssignment(assignment); StudySite ss = createStudySite(study, site); ss.addStudySubjectAssignment(assignment); return assignment; } public static ScheduledStudySegment createScheduledStudySegment(StudySegment studySegment) { ScheduledStudySegment scheduledStudySegment = new ScheduledStudySegment(); scheduledStudySegment.setStudySegment(studySegment); scheduledStudySegment.setStartDay(1); scheduledStudySegment.setStartDate(DateTools.createDate(1997, Calendar.JANUARY, 12)); return scheduledStudySegment; } public static ScheduledActivity createScheduledActivity( String activityName, int year, int month, int day, ScheduledActivityState state ) { ScheduledActivity scheduled = createScheduledActivity(activityName, year, month, day); scheduled.changeState(state); return scheduled; } public static ScheduledActivity createScheduledActivity( PlannedActivity planned, int year, int month, int day, ScheduledActivityState state ) { ScheduledActivity scheduledActivity = createScheduledActivity(planned, year, month, day); scheduledActivity.changeState(state); return scheduledActivity; } public static ScheduledActivity createScheduledActivity(String activityName, int year, int month, int day) { PlannedActivity baseEvent = createPlannedActivity(activityName, 0); return createScheduledActivity(baseEvent, year, month, day); } public static ScheduledActivity createScheduledActivity(PlannedActivity planned, int year, int month, int day) { ScheduledActivity event = new ScheduledActivity(); event.setPlannedActivity(planned); event.setActivity(planned.getActivity()); event.setIdealDate(DateUtils.createDate(year, month, day - 2)); event.changeState(new Scheduled(null, DateUtils.createDate(year, month, day))); return event; } public static ScheduledActivity createConditionalEvent(String activityName, int year, int month, int day) { PlannedActivity baseEvent = createPlannedActivity(activityName, 0); baseEvent.setCondition("Details"); return createScheduledActivity(baseEvent, year, month, day, new Conditional()); } public static Source createSource(final String name) { return createNamedInstance(name, Source.class); } public static Activity createActivity(String name) { return createActivity(name, DEFAULT_ACTIVITY_TYPE); } public static ActivityType createActivityType(final String name) { return createNamedInstance(name, ActivityType.class); } public static Activity createActivity(String name, ActivityType type) { return createActivity(name, name, DEFAULT_ACTIVITY_SOURCE, type); } public static Activity createActivity(String name, String code, Source source, ActivityType type) { Activity activity = createNamedInstance(name, Activity.class); activity.setId(name.hashCode()); activity.setCode(code); activity.setType(type); if (source != null) { source.addActivity(activity); } return activity; } public static Activity createActivity(String name, String code, Source source, ActivityType type, String description) { Activity activity = createActivity(name, code, source, type); activity.setDescription(description); return activity; } public static void addEvents(ScheduledStudySegment scheduledStudySegment, ScheduledActivity... events) { for (ScheduledActivity event : events) { scheduledStudySegment.addEvent(event); } } public static void setUserRoles(User user, Role... roles) { user.clearUserRoles(); for (Role role : roles) { UserRole userRole = new UserRole(user, role); user.getUserRoles().add(userRole); } } public static User createUser(String name, Role... roles) { return createUser(null, name, null, true, roles); } public static User createUser(Integer id, String name, Long csmUserId, boolean activeFlag, Role... roles) { User user = new User(); user.setId(id); user.setName(name); user.setCsmUserId(csmUserId); user.setActiveFlag(activeFlag); setUserRoles(user, roles); return user; } public static UserRole createUserRole(User user, Role role, Site... sites) { UserRole userRole = new UserRole(user, role, sites); user.addUserRole(userRole); return userRole; } public static ProtectionGroup createProtectionGroup(Long aId, String aName) { ProtectionGroup myProtectionGroup = new ProtectionGroup(); myProtectionGroup.setProtectionGroupName(aName); myProtectionGroup.setProtectionGroupId(aId); return myProtectionGroup; } public static <T extends Named> T createNamedInstance(String name, Class<T> clazz) { try { T instance = clazz.newInstance(); instance.setName(name); return instance; } catch (InstantiationException e) { throw new RuntimeException("Creating domain obj of class " + clazz.getName() + " failed", e); } catch (IllegalAccessException e) { throw new RuntimeException("Creating domain obj of class " + clazz.getName() + " failed", e); } } public static Population createPopulation() { return createPopulation("P", "People"); } public static Population createPopulation(String abbreviation, String name) { Population population = new Population(); population.setAbbreviation(abbreviation); population.setName(name); return population; } public static Amendment createAmendment(String name, Date date) { return createAmendment(name, date, true); } public static Amendment createAmendment(String name, Date date, boolean mandatory) { Amendment amendment = new Amendment(); amendment.setMandatory(mandatory); amendment.setName(name); amendment.setDate(date); amendment.setReleasedDate(date); return amendment; } /** * Creates a chain of amendments with the given names, returning the one at the end of the * chain (the most recent one). */ public static Amendment createAmendments(String... nameHistory) { Amendment current = new Amendment(); Calendar cal = Calendar.getInstance(); cal.set(2001, Calendar.JANUARY, 1); for (int i = 0; i < nameHistory.length - 1; i++) { String name = nameHistory[i]; current.setName(name); current.setDate(cal.getTime()); Amendment next = new Amendment(); next.setPreviousAmendment(current); current = next; cal.add(Calendar.DAY_OF_YEAR, 1); } current.setName(nameHistory[nameHistory.length - 1]); return current; } /** * Creates a chain of amendments with the given dates, returning the one at the end of the * chain (the most recent one). */ public static Amendment createAmendments(Date... dateHistory) { Amendment current = new Amendment(); for (int i = 0; i < dateHistory.length - 1; i++) { Date date = dateHistory[i]; current.setDate(date); Amendment next = new Amendment(); next.setPreviousAmendment(current); current = next; } current.setDate(dateHistory[dateHistory.length - 1]); return current; } public static Add createAddChange(Integer newChildId, Integer index) { Add add = new Add(); add.setChildId(newChildId); add.setIndex(index); return add; } // static class private Fixtures() { } }
Add createSite fixture methods. Related to #516.
src/test/java/edu/northwestern/bioinformatics/studycalendar/domain/Fixtures.java
Add createSite fixture methods. Related to #516.
<ide><path>rc/test/java/edu/northwestern/bioinformatics/studycalendar/domain/Fixtures.java <ide> } <ide> } <ide> <add> public static Site createSite(String name) { <add> return createSite(name, null); <add> } <add> <add> public static Site createSite(String name, String assignedIdentifier) { <add> Site site = createNamedInstance(name, Site.class); <add> site.setAssignedIdentifier(assignedIdentifier); <add> return site; <add> } <add> <ide> public static void setUserRoles(User user, Role... roles) { <ide> user.clearUserRoles(); <ide> for (Role role : roles) {
JavaScript
mit
7afb94e972571fc1390f774b3e5a5af8ab0809d4
0
scarwu/Diablo3Calculator,scarwu/Diablo3Calculator
// JavaScript Document 'use strict'; $(function() { var character = { 1: getCookie('character1'), 2: getCookie('character2'), 3: getCookie('character3'), 4: getCookie('character4'), 5: getCookie('character5') }; var order = getCookie('order'); var based = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; var replacement = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; var temp = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; var default_point = { main_attribute : 187, skill_damage : 0, attack_per_speed: 1, critical_chance : 5, critical_damage : 50 }; var diff_equip = { skill: false, belt: false, boots: false, braces: false, chest: false, glovers: false, helm: false, pants: false, shoulders: false, amulet: false, ring_1: false, ring_2: false, weapon_1: false, weapon_2: false } // Load Profile function loadProfile() { if(order == null) order = 1; else order = parseInt(order, 10); $.each(character, function(key, value) { if(character[key] == null) { character[key] = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; } else character[key] = JSON.parse(Base64.decode(character[key])); }); } // Svae Profile function saveProfile() { character[order] = based; setCookie('order', order); setCookie('character' + order, Base64.encode(JSON.stringify(character[order]))); } // Reset function reset() { // Set selected character $('.character .order').val(order); // Reset field $('input').val(0); $('.minor_dps').text(0); // Set default point $.each(default_point, function(key, value) { $('#based .attribute .' + key).val(value); }); // Set character data $.each(based, function(key, value) { $.each(value, function(key2, value2) { if(key == 'skill') $('#based .skill .' + key2).val(value2); else $('#equip .based .' + key + ' .' + key2).val(value2); }); }); } $(document).ready(function() { // Load Data loadProfile(); // Load based = character[order]; reset(); totalAttribute(based, 'based'); diff(); totalAttribute(replacement, 'replacement'); calculate(based, 'based'); calculate(replacement, 'replacement'); // Minor DPS calculateMinorDPS('based'); //calculateMinorDPS('replacement'); // If User change character profile $('.character .order').change(function() { order = $(this).val(); based = character[order]; // Reset Profile reset(); totalAttribute(based, 'based'); diff(); totalAttribute(replacement, 'replacement'); calculate(based, 'based'); calculate(replacement, 'replacement'); // Minor DPS calculateMinorDPS('based'); //calculateMinorDPS('replacement'); // Save data saveProfile(); }); // Based $('#based .skill input').change(function() { var key = $(this).attr('class'); based['skill'][key] = parseFloat($(this).val()); $(this).val(based['skill'][key]); based['skill'][key] = $(this).val(); if(based['skill'][key] == 'NaN') based['skill'][key] = 0; if(based['skill'][key] < 0) based['skill'][key] = 0; $(this).val(based['skill'][key]); saveProfile(); diff(); calculate(based, 'based'); calculate(replacement, 'replacement'); // Minor DPS calculateMinorDPS('based'); //calculateMinorDPS('replacement'); }); $('#equip .based input').change(function() { var key1 = $(this).parent().parent().attr('class'); var key2 = $(this).attr('class'); based[key1][key2] = parseFloat($(this).val()); $(this).val(based[key1][key2]); based[key1][key2] = $(this).val(); if(based[key1][key2] == 'NaN') based[key1][key2] = 0; if(based[key1][key2] < 0) based[key1][key2] = 0; $(this).val(based[key1][key2]); saveProfile(); totalAttribute(based, 'based'); diff(); totalAttribute(replacement, 'replacement'); calculate(based, 'based'); calculate(replacement, 'replacement'); // Minor DPS calculateMinorDPS('based'); //calculateMinorDPS('replacement'); }); // Replacement $('#replacement .skill input').change(function() { var key = $(this).attr('class'); temp['skill'][key] = parseFloat($(this).val()); $(this).val(temp['skill'][key]); temp['skill'][key] = $(this).val(); if(temp['skill'][key] == 'NaN') temp['skill'][key] = 0; if(temp['skill'][key] < 0) temp['skill'][key] = 0; $(this).val(temp['skill'][key]); diff_equip['skill'] = false; $.each($('#replacement .skill input'), function() { if(parseFloat($(this).val()) > 0) diff_equip['skill'] = true; }); diff(); calculate(replacement, 'replacement'); }); $('#equip .replacement input').change(function() { var key1 = $(this).parent().parent().attr('class'); var key2 = $(this).attr('class'); temp[key1][key2] = parseFloat($(this).val()); $(this).val(temp[key1][key2]); temp[key1][key2] = $(this).val(); if(temp[key1][key2] == 'NaN') temp[key1][key2] = 0; if(temp[key1][key2] < 0) temp[key1][key2] = 0; $(this).val(temp[key1][key2]); diff_equip[key1] = false; $.each($('#equip .replacement .' + key1 + ' input'), function() { if(parseFloat($(this).val()) > 0) diff_equip[key1] = true; }); diff(); totalAttribute(replacement, 'replacement'); calculate(replacement, 'replacement'); }); }); // Find difference function diff() { replacement = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; $.each(diff_equip, function(key, value) { if(value) { replacement[key] = temp[key]; } else { replacement[key] = based[key]; } }); } function totalAttribute(data, target) { var total = { main_attribute: 0, attack_speed: 0, critical_chance: 0, critical_damage: 0, min_damage: 0, max_damage: 0 }; $.each(data, function(key, value) { if(key != 'skill') $.each(value, function(key2, value2) { total[key2] += parseFloat(value2); }); }); $('#' + target + ' .total .main_attribute').val(total['main_attribute']); $('#' + target + ' .total .attack_speed').val(total['attack_speed']); $('#' + target + ' .total .critical_chance').val(total['critical_chance']); $('#' + target + ' .total .critical_damage').val(total['critical_damage']); $('#' + target + ' .total .min_damage').val(total['min_damage']); $('#' + target + ' .total .max_damage').val(total['max_damage']); } function calculateMinorDPS(target) { $.each($('#equip .' + target + ' > div'), function() { var key = $(this).attr('class'); if(key != 'weapon_1' && key != 'weapon_2') { var total = { main_attribute: parseFloat($('#' + target + ' .attribute .main_attribute').val()), critical_chance: parseFloat($('#' + target + ' .attribute .critical_chance').val()), critical_damage: parseFloat($('#' + target + ' .attribute .critical_damage').val()), attack_speed: parseFloat($('#' + target + ' .total .attack_speed').val()), min_damage: parseFloat($('#' + target + ' .total .min_damage').val()), max_damage: parseFloat($('#' + target + ' .total .max_damage').val()) }; $.each($('#equip .' + target + ' .' + key + ' input'), function() { total[$(this).attr('class')] -= parseFloat($(this).val()); }); var weapon_attack_per_second_1 = parseFloat($('#equip .' + target + ' .weapon_attack_per_second_1').val()); var weapon_min_damage_1 = parseFloat($('#equip .' + target + ' .weapon_min_damage_1').val());; var weapon_max_damage_1 = parseFloat($('#equip .' + target + ' .weapon_max_damage_1').val());; var weapon_attack_per_second_2 = parseFloat($('#equip .' + target + ' .weapon_attack_per_second_2').val());; var weapon_min_damage_2 = parseFloat($('#equip .' + target + ' .weapon_min_damage_2').val());; var weapon_max_damage_2 = parseFloat($('#equip .' + target + ' .weapon_max_damage_2').val());; var main_attribute = total['main_attribute']; var critical_chance = total['critical_chance']; var critical_damage = total['critical_damage']; var attack_speed = total['attack_speed']; var min_damage = total['min_damage']; var max_damage = total['max_damage']; var attack_per_second_1 = weapon_attack_per_second_1 * (attack_speed / 100 + 1); var attack_per_second_2 = weapon_attack_per_second_2 * (attack_speed / 100 + 1); if(attack_per_second_2 != 0) var average_aps = (attack_per_second_1 + attack_per_second_2) / 2; else var average_aps = attack_per_second_1; if(average_aps == 0) average_aps = 1; // Skill bonus damage var skill_damage = parseFloat($('#' + target + ' .skill .damage').val()); var dps = parseFloat($('#' + target + ' .attribute .damage_per_second').val()); // Damage per second var minor_dps = (weapon_min_damage_1 + weapon_max_damage_1 + weapon_min_damage_2 + weapon_max_damage_2) / 2; minor_dps += (min_damage + max_damage) / 2; minor_dps *= average_aps; minor_dps *= main_attribute / 100 + 1; minor_dps *= (critical_chance * critical_damage / 10000) + 1; minor_dps *= skill_damage / 100 + 1; minor_dps = dps - minor_dps; minor_dps = parseInt(minor_dps, 10); $('#equip .' + target + ' .' + key + ' .minor_dps').text(minor_dps + ' DPS'); } }); } function calculate(data, target) { var main_attribute = parseFloat($('#' + target + ' .total .main_attribute').val()); main_attribute += parseFloat(default_point['main_attribute']); var critical_chance = parseFloat($('#' + target + ' .total .critical_chance').val()); critical_chance += parseFloat(data['skill']['critical_chance']); critical_chance += default_point['critical_chance']; var critical_damage = parseFloat($('#' + target + ' .total .critical_damage').val()); critical_damage += parseFloat(data['skill']['critical_damage']); critical_damage += default_point['critical_damage']; var attack_speed = parseFloat($('#' + target + ' .total .attack_speed').val()); var min_damage = parseFloat($('#' + target + ' .total .min_damage').val()); var max_damage = parseFloat($('#' + target + ' .total .max_damage').val()); // Display attribute $('#' + target + ' .attribute .main_attribute').val(main_attribute); $('#' + target + ' .attribute .critical_chance').val(critical_chance); $('#' + target + ' .attribute .critical_damage').val(critical_damage); // Weapon data var weapon_attack_per_second_1 = 0; var weapon_min_damage_1 = 0; var weapon_max_damage_1 = 0; if(data['weapon_1']['weapon_attack_per_second_1'] != undefined) weapon_attack_per_second_1 = parseFloat(data['weapon_1']['weapon_attack_per_second_1']); if(data['weapon_1']['weapon_min_damage_1'] != undefined) weapon_min_damage_1 = parseFloat(data['weapon_1']['weapon_min_damage_1']); if(data['weapon_1']['weapon_max_damage_1'] != undefined) weapon_max_damage_1 = parseFloat(data['weapon_1']['weapon_max_damage_1']); var weapon_attack_per_second_2 = 0; var weapon_min_damage_2 = 0; var weapon_max_damage_2 = 0; if(data['weapon_2']['weapon_attack_per_second_2'] != undefined) weapon_attack_per_second_2 = parseFloat(data['weapon_2']['weapon_attack_per_second_2']); if(data['weapon_2']['weapon_min_damage_2'] != undefined) weapon_min_damage_2 = parseFloat(data['weapon_2']['weapon_min_damage_2']); if(data['weapon_2']['weapon_max_damage_2'] != undefined) weapon_max_damage_2 = parseFloat(data['weapon_2']['weapon_max_damage_2']); var attack_per_second_1 = weapon_attack_per_second_1 * (attack_speed / 100 + 1); var attack_per_second_2 = weapon_attack_per_second_2 * (attack_speed / 100 + 1); if(attack_per_second_2 != 0) var average_aps = (attack_per_second_1 + attack_per_second_2) / 2; else var average_aps = attack_per_second_1; if(average_aps == 0) average_aps = 1; // Display Aps $('#' + target + ' .attribute .attack_per_second').val(parseInt(average_aps * 100) / 100); // Skill bonus damage var skill_damage = parseFloat(data['skill']['damage']); // Damage per second var dps = (weapon_min_damage_1 + weapon_max_damage_1 + weapon_min_damage_2 + weapon_max_damage_2) / 2; dps += (min_damage + max_damage) / 2; dps *= average_aps; dps *= main_attribute / 100 + 1; dps *= (critical_chance * critical_damage / 10000) + 1; dps *= skill_damage / 100 + 1; dps = parseInt(dps * 100) / 100; // Normal damage range var min_normal_damage = (weapon_min_damage_1 + weapon_min_damage_2) / 2; min_normal_damage += min_damage / 2; min_normal_damage *= main_attribute / 100 + 1; min_normal_damage *= skill_damage / 100 + 1; min_normal_damage = parseInt(min_normal_damage * 100) / 100; var max_normal_damage = (weapon_max_damage_1 + weapon_max_damage_2) / 2; max_normal_damage += max_damage / 2; max_normal_damage *= main_attribute / 100 + 1; max_normal_damage *= skill_damage / 100 + 1; max_normal_damage = parseInt(max_normal_damage * 100) / 100; // Critical damage range var min_critical_damage = (weapon_min_damage_1 + weapon_min_damage_2) / 2; min_critical_damage += min_damage / 2; min_critical_damage *= main_attribute / 100 + 1; min_critical_damage *= critical_damage / 100 + 1; min_critical_damage *= skill_damage / 100 + 1; min_critical_damage = parseInt(min_critical_damage * 100) / 100; var max_critical_damage = (weapon_max_damage_1 + weapon_max_damage_2) / 2; max_critical_damage += max_damage / 2; max_critical_damage *= main_attribute / 100 + 1; max_critical_damage *= critical_damage / 100 + 1; max_critical_damage *= skill_damage / 100 + 1; max_critical_damage = parseInt(max_critical_damage * 100) / 100; // Display attribute $('#' + target + ' .attribute .damage_per_second').val(dps); $('#' + target + ' .attribute .normal_damage_range').val(min_normal_damage + ' - ' + max_normal_damage); $('#' + target + ' .attribute .critical_damage_range').val(min_critical_damage + ' - ' + max_critical_damage); } });
js/main.js
// JavaScript Document 'use strict'; $(function() { var character = getCookie('character'); var order = 1; var based = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; var replacement = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; var temp = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; var default_point = { main_attribute : 187, skill_damage : 0, attack_per_speed: 1, critical_chance : 5, critical_damage : 50 }; var diff_equip = { skill: false, belt: false, boots: false, braces: false, chest: false, glovers: false, helm: false, pants: false, shoulders: false, amulet: false, ring_1: false, ring_2: false, weapon_1: false, weapon_2: false } // Load Profile function loadProfile() { if(character == null) { character = { order: 1, 1: based, 2: based, 3: based, 4: based, 5: based }; } else character = JSON.parse(Base64.decode(character)); } // Svae Profile function saveProfile() { character['order'] = order; character[order] = based; setCookie('character', Base64.encode(JSON.stringify(character))); } // Reset function reset() { // Set selected character $('.character .order').val(order); // Reset field $('input').val(0); $('.minor_dps').text(0); // Set default point $.each(default_point, function(key, value) { $('#based .attribute .' + key).val(value); }); // Set character data $.each(based, function(key, value) { $.each(value, function(key2, value2) { if(key == 'skill') $('#based .skill .' + key2).val(value2); else $('#equip .based .' + key + ' .' + key2).val(value2); }); }); } function l(input) { console.log(JSON.stringify(input)); } $(document).ready(function() { // Load Data loadProfile(); // Load order = character['order']; based = character[order]; reset(); totalAttribute(based, 'based'); diff(); totalAttribute(replacement, 'replacement'); calculate(based, 'based'); calculate(replacement, 'replacement'); // Minor DPS calculateMinorDPS('based'); //calculateMinorDPS('replacement'); // If User change character profile $('.character .order').change(function() { order = $(this).val(); based = character[order]; // Reset Profile reset(); totalAttribute(based, 'based'); diff(); totalAttribute(replacement, 'replacement'); calculate(based, 'based'); calculate(replacement, 'replacement'); // Minor DPS calculateMinorDPS('based'); //calculateMinorDPS('replacement'); // Save data saveProfile(); }); // Based $('#based .skill input').change(function() { var key = $(this).attr('class'); based['skill'][key] = parseFloat($(this).val()); $(this).val(based['skill'][key]); based['skill'][key] = $(this).val(); if(based['skill'][key] == 'NaN') based['skill'][key] = 0; if(based['skill'][key] < 0) based['skill'][key] = 0; $(this).val(based['skill'][key]); saveProfile(); diff(); calculate(based, 'based'); calculate(replacement, 'replacement'); // Minor DPS calculateMinorDPS('based'); //calculateMinorDPS('replacement'); }); $('#equip .based input').change(function() { var key1 = $(this).parent().parent().attr('class'); var key2 = $(this).attr('class'); based[key1][key2] = parseFloat($(this).val()); $(this).val(based[key1][key2]); based[key1][key2] = $(this).val(); if(based[key1][key2] == 'NaN') based[key1][key2] = 0; if(based[key1][key2] < 0) based[key1][key2] = 0; $(this).val(based[key1][key2]); saveProfile(); totalAttribute(based, 'based'); diff(); totalAttribute(replacement, 'replacement'); calculate(based, 'based'); calculate(replacement, 'replacement'); // Minor DPS calculateMinorDPS('based'); //calculateMinorDPS('replacement'); }); // Replacement $('#replacement .skill input').change(function() { var key = $(this).attr('class'); temp['skill'][key] = parseFloat($(this).val()); $(this).val(temp['skill'][key]); temp['skill'][key] = $(this).val(); if(temp['skill'][key] == 'NaN') temp['skill'][key] = 0; if(temp['skill'][key] < 0) temp['skill'][key] = 0; $(this).val(temp['skill'][key]); diff_equip['skill'] = false; $.each($('#replacement .skill input'), function() { if(parseFloat($(this).val()) > 0) diff_equip['skill'] = true; }); diff(); calculate(replacement, 'replacement'); }); $('#equip .replacement input').change(function() { var key1 = $(this).parent().parent().attr('class'); var key2 = $(this).attr('class'); temp[key1][key2] = parseFloat($(this).val()); $(this).val(temp[key1][key2]); temp[key1][key2] = $(this).val(); if(temp[key1][key2] == 'NaN') temp[key1][key2] = 0; if(temp[key1][key2] < 0) temp[key1][key2] = 0; $(this).val(temp[key1][key2]); diff_equip[key1] = false; $.each($('#equip .replacement .' + key1 + ' input'), function() { if(parseFloat($(this).val()) > 0) diff_equip[key1] = true; }); diff(); totalAttribute(replacement, 'replacement'); calculate(replacement, 'replacement'); }); }); // Find difference function diff() { replacement = { skill: { damage: 0, critical_chance: 0, critical_damage: 0 }, belt: {}, boots: {}, braces: {}, chest: {}, glovers: {}, helm: {}, pants: {}, shoulders: {}, amulet: {}, ring_1: {}, ring_2: {}, weapon_1: {}, weapon_2: {} }; $.each(diff_equip, function(key, value) { if(value) { replacement[key] = temp[key]; } else { replacement[key] = based[key]; } }); } function totalAttribute(data, target) { var total = { main_attribute: 0, attack_speed: 0, critical_chance: 0, critical_damage: 0, min_damage: 0, max_damage: 0 }; $.each(data, function(key, value) { if(key != 'skill') $.each(value, function(key2, value2) { total[key2] += parseFloat(value2); }); }); $('#' + target + ' .total .main_attribute').val(total['main_attribute']); $('#' + target + ' .total .attack_speed').val(total['attack_speed']); $('#' + target + ' .total .critical_chance').val(total['critical_chance']); $('#' + target + ' .total .critical_damage').val(total['critical_damage']); $('#' + target + ' .total .min_damage').val(total['min_damage']); $('#' + target + ' .total .max_damage').val(total['max_damage']); } function calculateMinorDPS(target) { $.each($('#equip .' + target + ' > div'), function() { var key = $(this).attr('class'); if(key != 'weapon_1' && key != 'weapon_2') { var total = { main_attribute: parseFloat($('#' + target + ' .attribute .main_attribute').val()), critical_chance: parseFloat($('#' + target + ' .attribute .critical_chance').val()), critical_damage: parseFloat($('#' + target + ' .attribute .critical_damage').val()), attack_speed: parseFloat($('#' + target + ' .total .attack_speed').val()), min_damage: parseFloat($('#' + target + ' .total .min_damage').val()), max_damage: parseFloat($('#' + target + ' .total .max_damage').val()) }; $.each($('#equip .' + target + ' .' + key + ' input'), function() { total[$(this).attr('class')] -= parseFloat($(this).val()); }); var weapon_attack_per_second_1 = parseFloat($('#equip .' + target + ' .weapon_attack_per_second_1').val()); var weapon_min_damage_1 = parseFloat($('#equip .' + target + ' .weapon_min_damage_1').val());; var weapon_max_damage_1 = parseFloat($('#equip .' + target + ' .weapon_max_damage_1').val());; var weapon_attack_per_second_2 = parseFloat($('#equip .' + target + ' .weapon_attack_per_second_2').val());; var weapon_min_damage_2 = parseFloat($('#equip .' + target + ' .weapon_min_damage_2').val());; var weapon_max_damage_2 = parseFloat($('#equip .' + target + ' .weapon_max_damage_2').val());; var main_attribute = total['main_attribute']; var critical_chance = total['critical_chance']; var critical_damage = total['critical_damage']; var attack_speed = total['attack_speed']; var min_damage = total['min_damage']; var max_damage = total['max_damage']; var attack_per_second_1 = weapon_attack_per_second_1 * (attack_speed / 100 + 1); var attack_per_second_2 = weapon_attack_per_second_2 * (attack_speed / 100 + 1); if(attack_per_second_2 != 0) var average_aps = (attack_per_second_1 + attack_per_second_2) / 2; else var average_aps = attack_per_second_1; if(average_aps == 0) average_aps = 1; // Skill bonus damage var skill_damage = parseFloat($('#' + target + ' .skill .damage').val()); var dps = parseFloat($('#' + target + ' .attribute .damage_per_second').val()); // Damage per second var minor_dps = (weapon_min_damage_1 + weapon_max_damage_1 + weapon_min_damage_2 + weapon_max_damage_2) / 2; minor_dps += (min_damage + max_damage) / 2; minor_dps *= average_aps; minor_dps *= main_attribute / 100 + 1; minor_dps *= (critical_chance * critical_damage / 10000) + 1; minor_dps *= skill_damage / 100 + 1; minor_dps = dps - minor_dps; minor_dps = parseInt(minor_dps, 10); $('#equip .' + target + ' .' + key + ' .minor_dps').text(minor_dps + ' DPS'); } }); } function calculate(data, target) { var main_attribute = parseFloat($('#' + target + ' .total .main_attribute').val()); main_attribute += parseFloat(default_point['main_attribute']); var critical_chance = parseFloat($('#' + target + ' .total .critical_chance').val()); critical_chance += parseFloat(data['skill']['critical_chance']); critical_chance += default_point['critical_chance']; var critical_damage = parseFloat($('#' + target + ' .total .critical_damage').val()); critical_damage += parseFloat(data['skill']['critical_damage']); critical_damage += default_point['critical_damage']; var attack_speed = parseFloat($('#' + target + ' .total .attack_speed').val()); var min_damage = parseFloat($('#' + target + ' .total .min_damage').val()); var max_damage = parseFloat($('#' + target + ' .total .max_damage').val()); // Display attribute $('#' + target + ' .attribute .main_attribute').val(main_attribute); $('#' + target + ' .attribute .critical_chance').val(critical_chance); $('#' + target + ' .attribute .critical_damage').val(critical_damage); // Weapon data var weapon_attack_per_second_1 = 0; var weapon_min_damage_1 = 0; var weapon_max_damage_1 = 0; if(data['weapon_1']['weapon_attack_per_second_1'] != undefined) weapon_attack_per_second_1 = parseFloat(data['weapon_1']['weapon_attack_per_second_1']); if(data['weapon_1']['weapon_min_damage_1'] != undefined) weapon_min_damage_1 = parseFloat(data['weapon_1']['weapon_min_damage_1']); if(data['weapon_1']['weapon_max_damage_1'] != undefined) weapon_max_damage_1 = parseFloat(data['weapon_1']['weapon_max_damage_1']); var weapon_attack_per_second_2 = 0; var weapon_min_damage_2 = 0; var weapon_max_damage_2 = 0; if(data['weapon_2']['weapon_attack_per_second_2'] != undefined) weapon_attack_per_second_2 = parseFloat(data['weapon_2']['weapon_attack_per_second_2']); if(data['weapon_2']['weapon_min_damage_2'] != undefined) weapon_min_damage_2 = parseFloat(data['weapon_2']['weapon_min_damage_2']); if(data['weapon_2']['weapon_max_damage_2'] != undefined) weapon_max_damage_2 = parseFloat(data['weapon_2']['weapon_max_damage_2']); var attack_per_second_1 = weapon_attack_per_second_1 * (attack_speed / 100 + 1); var attack_per_second_2 = weapon_attack_per_second_2 * (attack_speed / 100 + 1); if(attack_per_second_2 != 0) var average_aps = (attack_per_second_1 + attack_per_second_2) / 2; else var average_aps = attack_per_second_1; if(average_aps == 0) average_aps = 1; // Display Aps $('#' + target + ' .attribute .attack_per_second').val(parseInt(average_aps * 100) / 100); // Skill bonus damage var skill_damage = parseFloat(data['skill']['damage']); // Damage per second var dps = (weapon_min_damage_1 + weapon_max_damage_1 + weapon_min_damage_2 + weapon_max_damage_2) / 2; dps += (min_damage + max_damage) / 2; dps *= average_aps; dps *= main_attribute / 100 + 1; dps *= (critical_chance * critical_damage / 10000) + 1; dps *= skill_damage / 100 + 1; dps = parseInt(dps * 100) / 100; // Normal damage range var min_normal_damage = (weapon_min_damage_1 + weapon_min_damage_2) / 2; min_normal_damage += min_damage / 2; min_normal_damage *= main_attribute / 100 + 1; min_normal_damage *= skill_damage / 100 + 1; min_normal_damage = parseInt(min_normal_damage * 100) / 100; var max_normal_damage = (weapon_max_damage_1 + weapon_max_damage_2) / 2; max_normal_damage += max_damage / 2; max_normal_damage *= main_attribute / 100 + 1; max_normal_damage *= skill_damage / 100 + 1; max_normal_damage = parseInt(max_normal_damage * 100) / 100; // Critical damage range var min_critical_damage = (weapon_min_damage_1 + weapon_min_damage_2) / 2; min_critical_damage += min_damage / 2; min_critical_damage *= main_attribute / 100 + 1; min_critical_damage *= critical_damage / 100 + 1; min_critical_damage *= skill_damage / 100 + 1; min_critical_damage = parseInt(min_critical_damage * 100) / 100; var max_critical_damage = (weapon_max_damage_1 + weapon_max_damage_2) / 2; max_critical_damage += max_damage / 2; max_critical_damage *= main_attribute / 100 + 1; max_critical_damage *= critical_damage / 100 + 1; max_critical_damage *= skill_damage / 100 + 1; max_critical_damage = parseInt(max_critical_damage * 100) / 100; // Display attribute $('#' + target + ' .attribute .damage_per_second').val(dps); $('#' + target + ' .attribute .normal_damage_range').val(min_normal_damage + ' - ' + max_normal_damage); $('#' + target + ' .attribute .critical_damage_range').val(min_critical_damage + ' - ' + max_critical_damage); } });
Fix cookie overflow bug
js/main.js
Fix cookie overflow bug
<ide><path>s/main.js <ide> 'use strict'; <ide> <ide> $(function() { <del> var character = getCookie('character'); <del> var order = 1; <add> var character = { <add> 1: getCookie('character1'), <add> 2: getCookie('character2'), <add> 3: getCookie('character3'), <add> 4: getCookie('character4'), <add> 5: getCookie('character5') <add> }; <add> var order = getCookie('order'); <ide> var based = { <ide> skill: { <ide> damage: 0, <ide> <ide> // Load Profile <ide> function loadProfile() { <del> if(character == null) { <del> character = { <del> order: 1, <del> 1: based, <del> 2: based, <del> 3: based, <del> 4: based, <del> 5: based <del> }; <del> } <add> if(order == null) <add> order = 1; <ide> else <del> character = JSON.parse(Base64.decode(character)); <add> order = parseInt(order, 10); <add> <add> $.each(character, function(key, value) { <add> if(character[key] == null) { <add> character[key] = { <add> skill: { <add> damage: 0, <add> critical_chance: 0, <add> critical_damage: 0 <add> }, <add> belt: {}, <add> boots: {}, <add> braces: {}, <add> chest: {}, <add> glovers: {}, <add> helm: {}, <add> pants: {}, <add> shoulders: {}, <add> amulet: {}, <add> ring_1: {}, <add> ring_2: {}, <add> weapon_1: {}, <add> weapon_2: {} <add> }; <add> } <add> else <add> character[key] = JSON.parse(Base64.decode(character[key])); <add> }); <ide> } <ide> <ide> // Svae Profile <ide> function saveProfile() { <del> character['order'] = order; <ide> character[order] = based; <ide> <del> setCookie('character', Base64.encode(JSON.stringify(character))); <add> setCookie('order', order); <add> setCookie('character' + order, Base64.encode(JSON.stringify(character[order]))); <ide> } <ide> <ide> // Reset <ide> }); <ide> } <ide> <del> function l(input) { <del> console.log(JSON.stringify(input)); <del> } <del> <ide> $(document).ready(function() { <ide> // Load Data <ide> loadProfile(); <ide> <ide> // Load <del> order = character['order']; <ide> based = character[order]; <ide> <ide> reset();
Java
epl-1.0
00b47bc44be03db1c994c800de177316ebf92173
0
Charling-Huang/birt,sguan-actuate/birt,rrimmana/birt-1,rrimmana/birt-1,rrimmana/birt-1,Charling-Huang/birt,sguan-actuate/birt,sguan-actuate/birt,Charling-Huang/birt,sguan-actuate/birt,Charling-Huang/birt,rrimmana/birt-1,sguan-actuate/birt,rrimmana/birt-1,Charling-Huang/birt
/******************************************************************************* * Copyright (c) 2007 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.debug.internal.ui.script.launcher; import org.eclipse.birt.report.debug.internal.core.vm.ReportVMClient; import org.eclipse.birt.report.debug.internal.script.model.ScriptDebugTarget; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IProcess; import org.eclipse.jdt.launching.IVMRunner; import org.eclipse.jdt.launching.VMRunnerConfiguration; class ReportDebuggerVMRunner implements IVMRunner { private ReportOSGiLaunchDelegate config; private IVMRunner delegate; private boolean runScript; ReportDebuggerVMRunner( IVMRunner delegate, boolean runScript, ReportOSGiLaunchDelegate config ) { this.delegate = delegate; this.runScript = runScript; this.config = config; } public void run( VMRunnerConfiguration configuration, ILaunch launch, IProgressMonitor monitor ) throws CoreException { delegate.run( configuration, launch, monitor ); IProcess[] ps = launch.getProcesses( ); if ( ps != null && ps.length > 0 ) { if ( runScript ) { if ( monitor == null ) { monitor = new NullProgressMonitor( ); } IProgressMonitor subMonitor = new SubProgressMonitor( monitor, 1 ); subMonitor.beginTask( "Launching VM...", 1 ); //$NON-NLS-1$ ReportVMClient vm = new ReportVMClient( ); ScriptDebugTarget target = new ScriptDebugTarget( launch, vm, null, ps[0], config.helper.requestPort, config.helper.eventPort, config.helper.tempFolder ); target.setFileName( config.helper.fileName ); subMonitor.worked( 1 ); subMonitor.done( ); } ReportLaunchHelper.handleProcessTermination( launch, ps[0], config.helper.fileName, config.helper.tempFolder ); } } }
UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportDebuggerVMRunner.java
/******************************************************************************* * Copyright (c) 2007 Actuate Corporation. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Actuate Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.birt.report.debug.internal.ui.script.launcher; import org.eclipse.birt.report.debug.internal.core.vm.ReportVMClient; import org.eclipse.birt.report.debug.internal.script.model.ScriptDebugTarget; import org.eclipse.core.runtime.CoreException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.NullProgressMonitor; import org.eclipse.core.runtime.SubProgressMonitor; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IProcess; import org.eclipse.jdt.launching.IVMRunner; import org.eclipse.jdt.launching.VMRunnerConfiguration; class ReportDebuggerVMRunner implements IVMRunner { private ReportOSGiLaunchDelegate config; private IVMRunner delegate; private boolean runScript; ReportDebuggerVMRunner( IVMRunner delegate, boolean runScript, ReportOSGiLaunchDelegate config ) { this.delegate = delegate; this.runScript = runScript; this.config = config; } public void run( VMRunnerConfiguration configuration, ILaunch launch, IProgressMonitor monitor ) throws CoreException { delegate.run( configuration, launch, monitor ); IProcess[] ps = launch.getProcesses( ); if ( runScript && ps != null && ps.length > 0 ) { if ( monitor == null ) { monitor = new NullProgressMonitor( ); } IProgressMonitor subMonitor = new SubProgressMonitor( monitor, 1 ); subMonitor.beginTask( "Launching VM...", 1 ); //$NON-NLS-1$ ReportVMClient vm = new ReportVMClient( ); ScriptDebugTarget target = new ScriptDebugTarget( launch, vm, null, ps[0], config.helper.requestPort, config.helper.eventPort, config.helper.tempFolder ); target.setFileName( config.helper.fileName ); subMonitor.worked( 1 ); subMonitor.done( ); ReportLaunchHelper.handleProcessTermination( launch, ps[0], config.helper.fileName, config.helper.tempFolder ); } } }
- Bugzilla Bug (s) Resolved: 217645 - Description: fix logic in OSGi report launcher
UI/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportDebuggerVMRunner.java
- Bugzilla Bug (s) Resolved: 217645 - Description: fix logic in OSGi report launcher
<ide><path>I/org.eclipse.birt.report.debug.ui/src/org/eclipse/birt/report/debug/internal/ui/script/launcher/ReportDebuggerVMRunner.java <ide> <ide> IProcess[] ps = launch.getProcesses( ); <ide> <del> if ( runScript && ps != null && ps.length > 0 ) <add> if ( ps != null && ps.length > 0 ) <ide> { <del> if ( monitor == null ) <add> if ( runScript ) <ide> { <del> monitor = new NullProgressMonitor( ); <add> if ( monitor == null ) <add> { <add> monitor = new NullProgressMonitor( ); <add> } <add> <add> IProgressMonitor subMonitor = new SubProgressMonitor( monitor, <add> 1 ); <add> subMonitor.beginTask( "Launching VM...", 1 ); //$NON-NLS-1$ <add> <add> ReportVMClient vm = new ReportVMClient( ); <add> ScriptDebugTarget target = new ScriptDebugTarget( launch, <add> vm, <add> null, <add> ps[0], <add> config.helper.requestPort, <add> config.helper.eventPort, <add> config.helper.tempFolder ); <add> target.setFileName( config.helper.fileName ); <add> <add> subMonitor.worked( 1 ); <add> subMonitor.done( ); <ide> } <del> <del> IProgressMonitor subMonitor = new SubProgressMonitor( monitor, 1 ); <del> subMonitor.beginTask( "Launching VM...", 1 ); //$NON-NLS-1$ <del> <del> ReportVMClient vm = new ReportVMClient( ); <del> ScriptDebugTarget target = new ScriptDebugTarget( launch, <del> vm, <del> null, <del> ps[0], <del> config.helper.requestPort, <del> config.helper.eventPort, <del> config.helper.tempFolder ); <del> target.setFileName( config.helper.fileName ); <del> <del> subMonitor.worked( 1 ); <del> subMonitor.done( ); <ide> <ide> ReportLaunchHelper.handleProcessTermination( launch, <ide> ps[0],
Java
apache-2.0
00dbfdedc47d68ac774af7acd84cff1762ae1728
0
spinnaker/rosco,spinnaker/rosco
package com.netflix.spinnaker.rosco.manifests; import com.netflix.spinnaker.kork.artifacts.model.Artifact; import com.netflix.spinnaker.kork.core.RetrySupport; import com.netflix.spinnaker.rosco.services.ClouddriverService; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Component; import retrofit.RetrofitError; import retrofit.client.Response; @Component @Slf4j public final class ArtifactDownloaderImpl implements ArtifactDownloader { private final ClouddriverService clouddriverService; private final RetrySupport retrySupport = new RetrySupport(); public ArtifactDownloaderImpl(ClouddriverService clouddriverService) { this.clouddriverService = clouddriverService; } public void downloadArtifact(Artifact artifact, Path targetFile) throws IOException { try (OutputStream outputStream = Files.newOutputStream(targetFile)) { Response response = retrySupport.retry(() -> clouddriverService.fetchArtifact(artifact), 5, 1000, true); if (response.getBody() != null) { try (InputStream inputStream = response.getBody().in()) { IOUtils.copy(inputStream, outputStream); } catch (IOException e) { throw new IOException( String.format( "Failed to read input stream of downloaded artifact: %s. Error: %s", artifact, e.getMessage())); } } } catch (RetrofitError e) { throw new IOException( String.format("Failed to download artifact: %s. Error: %s", artifact, e.getMessage())); } } }
rosco-manifests/src/main/java/com/netflix/spinnaker/rosco/manifests/ArtifactDownloaderImpl.java
package com.netflix.spinnaker.rosco.manifests; import com.netflix.spinnaker.kork.artifacts.model.Artifact; import com.netflix.spinnaker.kork.core.RetrySupport; import com.netflix.spinnaker.rosco.services.ClouddriverService; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.springframework.stereotype.Component; import retrofit.client.Response; @Component @Slf4j public final class ArtifactDownloaderImpl implements ArtifactDownloader { private final ClouddriverService clouddriverService; private final RetrySupport retrySupport = new RetrySupport(); public ArtifactDownloaderImpl(ClouddriverService clouddriverService) { this.clouddriverService = clouddriverService; } public void downloadArtifact(Artifact artifact, Path targetFile) throws IOException { try (OutputStream outputStream = Files.newOutputStream(targetFile)) { Response response = retrySupport.retry(() -> clouddriverService.fetchArtifact(artifact), 5, 1000, true); if (response.getBody() != null) { try (InputStream inputStream = response.getBody().in()) { IOUtils.copy(inputStream, outputStream); } } } } }
fix(artifact): improve error messaging for failed artifact downl… (#453)
rosco-manifests/src/main/java/com/netflix/spinnaker/rosco/manifests/ArtifactDownloaderImpl.java
fix(artifact): improve error messaging for failed artifact downl… (#453)
<ide><path>osco-manifests/src/main/java/com/netflix/spinnaker/rosco/manifests/ArtifactDownloaderImpl.java <ide> import lombok.extern.slf4j.Slf4j; <ide> import org.apache.commons.io.IOUtils; <ide> import org.springframework.stereotype.Component; <add>import retrofit.RetrofitError; <ide> import retrofit.client.Response; <ide> <ide> @Component <ide> if (response.getBody() != null) { <ide> try (InputStream inputStream = response.getBody().in()) { <ide> IOUtils.copy(inputStream, outputStream); <add> } catch (IOException e) { <add> throw new IOException( <add> String.format( <add> "Failed to read input stream of downloaded artifact: %s. Error: %s", <add> artifact, e.getMessage())); <ide> } <ide> } <add> } catch (RetrofitError e) { <add> throw new IOException( <add> String.format("Failed to download artifact: %s. Error: %s", artifact, e.getMessage())); <ide> } <ide> } <ide> }
JavaScript
agpl-3.0
c2f45747cc61eb9003af6b6a43a5f500138d21e1
0
mickael-kerjean/nuage,mickael-kerjean/nuage,mickael-kerjean/nuage,mickael-kerjean/nuage,mickael-kerjean/nuage,mickael-kerjean/nuage
import React, { useEffect } from "react"; import { Session } from "../model/"; import { Loader, ErrorPage } from "../components/"; import { cache } from "../helpers/"; @ErrorPage export class LogoutPage extends React.Component { constructor(props){ super(props); } componentDidMount(){ Session.logout().then((res) => { cache.destroy(); this.props.history.push("/"); }).catch((err) => this.props.error(err)); } render() { return ( <div> <Loader /> </div> ); } }
client/pages/logout.js
import React from 'react'; import { Session } from '../model/'; import { Loader, ErrorPage } from '../components/'; import { cache } from '../helpers/'; @ErrorPage export class LogoutPage extends React.Component { constructor(props){ super(props); } componentDidMount(){ Session.logout() .then((res) => { cache.destroy(); this.props.history.push('/login'); }) .catch((err) => this.props.error(err)); } render() { return ( <div> <Loader /> </div> ); } }
maintenance (logout): logout component upgrade
client/pages/logout.js
maintenance (logout): logout component upgrade
<ide><path>lient/pages/logout.js <del>import React from 'react'; <add>import React, { useEffect } from "react"; <ide> <del>import { Session } from '../model/'; <del>import { Loader, ErrorPage } from '../components/'; <del>import { cache } from '../helpers/'; <add>import { Session } from "../model/"; <add>import { Loader, ErrorPage } from "../components/"; <add>import { cache } from "../helpers/"; <ide> <ide> @ErrorPage <ide> export class LogoutPage extends React.Component { <ide> } <ide> <ide> componentDidMount(){ <del> Session.logout() <del> .then((res) => { <del> cache.destroy(); <del> this.props.history.push('/login'); <del> }) <del> .catch((err) => this.props.error(err)); <add> Session.logout().then((res) => { <add> cache.destroy(); <add> this.props.history.push("/"); <add> }).catch((err) => this.props.error(err)); <ide> } <add> <ide> render() { <ide> return ( <ide> <div> <Loader /> </div>
Java
apache-2.0
4f93013d5757f6216aee6dbeb0d596051288a617
0
nordpos-mobi/online-retail
/** * Copyright (c) 2012-2015 Nord Trading Network. * * 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 mobi.nordpos.retail.action; import java.math.BigDecimal; import java.net.UnknownHostException; import java.sql.SQLException; import java.util.Date; import mobi.nordpos.dao.model.ClosedCash; import mobi.nordpos.dao.model.Receipt; import mobi.nordpos.dao.model.Ticket; import mobi.nordpos.dao.model.Ticket.TicketType; import mobi.nordpos.dao.model.TicketNumber; import mobi.nordpos.dao.model.User; import mobi.nordpos.dao.ormlite.ClosedCashPersist; import mobi.nordpos.dao.ormlite.ReceiptPersist; import mobi.nordpos.dao.ormlite.TicketNumberPersist; import mobi.nordpos.dao.ormlite.UserPersist; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.validation.SimpleError; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidationErrors; import net.sourceforge.stripes.validation.ValidationMethod; /** * @author Andrey Svininykh <[email protected]> */ public class OrderPaymentActionBean extends OrderBaseActionBean { private static final String PAYMENT_VIEW = "/WEB-INF/jsp/order_payment.jsp"; private static final String DEFAULT_USER_ID = "3"; @Validate(on = {"post"}, required = true, expression = "${(paymentType == 'cash' && paymentAmount >= total) || (paymentType == 'magcard' && paymentAmount == total) }") private BigDecimal paymentAmount; @Validate(on = {"post"}, required = true, expression = "${paymentType == 'cash' || paymentType == 'magcard'}") private String paymentType; private ClosedCash openCash; public Resolution view() { return new ForwardResolution(PAYMENT_VIEW); } public Resolution post() { ReceiptPersist receiptPersist = new ReceiptPersist(); UserPersist userPersist = new UserPersist(); TicketNumberPersist ticketNumberPersist = new TicketNumberPersist(); try { receiptPersist.init(getDataBaseConnection()); userPersist.init(getDataBaseConnection()); ticketNumberPersist.init(getDataBaseConnection()); Receipt receipt = new Receipt(); receipt.setClosedCash(openCash); receipt.setDate(new Date()); receipt = receiptPersist.add(receipt); Ticket ticket = new Ticket(); ticket.setId(receipt.getId()); ticket.setType(TicketType.SELL.getTicketType()); User user = userPersist.read(DEFAULT_USER_ID); ticket.setUser(user); TicketNumber number = ticketNumberPersist.readList().get(0); if (getDataBaseConnection().getDatabaseType().getDatabaseName().equals("Derby Client/Server")) { if (ticketNumberPersist.delete(number)) { number = ticketNumberPersist.add(new TicketNumber()); } } else { if (ticketNumberPersist.change(number)) { number = ticketNumberPersist.readList().get(0); } } ticket.setNumber(number.getId()); sharedTicketPersist.init(getDataBaseConnection()); sharedTicketPersist.delete(getContext().getOrder().getId()); getContext().setOrder(null); } catch (SQLException ex) { getContext().getValidationErrors().addGlobalError( new SimpleError(ex.getMessage())); return getContext().getSourcePageResolution(); } return new ForwardResolution(WelcomeActionBean.class); } public BigDecimal getPaymentAmount() { return paymentAmount; } public void setPaymentAmount(BigDecimal paymentAmount) { this.paymentAmount = paymentAmount; } public String getPaymentType() { return paymentType; } public void setPaymentType(String paymentType) { this.paymentType = paymentType; } public BigDecimal getTotal() { return getContext().getOrder().getTotalValue(); } @ValidationMethod(on = "post") public void validateClosedCashIsOpen(ValidationErrors errors) throws UnknownHostException { String hostName = java.net.InetAddress.getLocalHost().getHostName(); ClosedCashPersist closedCashPersist = new ClosedCashPersist(); try { closedCashPersist.init(getDataBaseConnection()); openCash = closedCashPersist.readOpen(hostName); if (openCash == null) { openCash = new ClosedCash(); openCash.setHost(hostName); openCash.setHostSequence(1); openCash.setDateStart(new Date()); openCash = closedCashPersist.add(openCash); } } catch (SQLException ex) { getContext().getValidationErrors().addGlobalError( new SimpleError(ex.getMessage())); } } // public Ticket saveTicket(OpenTicket openTicket) throws SQLException { // try { // connection = new JdbcConnectionSource(getDataBaseURL(), getDataBaseUser(), getDataBasePassword()); // ReceiptDAO receiptDao = new ReceiptPersist(connection); // TicketDAO ticketDao = new TicketPersist(connection); // TicketNumberDAO ticketNumberDao = new TicketNumberPersist(connection); // // if (!openTicket.getTicketLineList().isEmpty()) { // Receipt receipt = receiptDao.createNew(getOpenCash()); // Ticket ticket = ticketDao.createNew(new Ticket( // receipt.getId(), // TicketType.SELL.getTicketType(), // ticketNumberDao.generate(), // receipt, // openTicket.getUser(), // openTicket.getFiscalNumber())); // ticket.setTicketLineCollection(openTicket.getTicketLineList()); // // ForeignCollection<TicketLine> ticketLineCollection = ticket.getTicketLineCollection(); // CloseableIterator<TicketLine> ticketLineIterator = ticketLineCollection.closeableIterator(); // // ForeignCollection<TaxLine> taxLineCollection = receipt.getTaxLineCollection(); // // try { // while (ticketLineIterator.hasNext()) { // TicketLine line = ticketLineIterator.next(); // Tax selectTax = line.getTax(); // CloseableIterator<TaxLine> taxLineIterator = taxLineCollection.closeableIterator(); // TaxLine newTaxLine = new TaxLine( // receipt, // selectTax, // line.getSubTotal().doubleValue(), // line.getTaxAmountSubTotal().doubleValue()); // // boolean f = true; // try { // while (taxLineIterator.hasNext()) { // TaxLine taxLine = taxLineIterator.next(); // if (taxLine.getTax().getId().equals(selectTax.getId())) { // taxLine.setBase(taxLine.getBase() + line.getSubTotal().doubleValue()); // taxLine.setAmount(taxLine.getAmount() + line.getTaxAmountSubTotal().doubleValue()); // taxLineCollection.update(taxLine); // f = false; // break; // } // } // } finally { // taxLineIterator.close(); // } // // if (f) { // taxLineCollection.add(newTaxLine); // } // } // } finally { // ticketLineIterator.close(); // } // // ForeignCollection<Payment> paymentCollection = receipt.getPaymentCollection(); // BigDecimal total = openTicket.getTaxTotal(); // paymentCollection.add(new Payment(receipt, paymentType, payAmount)); // if (paymentType.equals(PaymentType.valueOf("CASH").getPaymentType()) && payAmount > total.doubleValue()) { // paymentCollection.add(new Payment(receipt, PaymentType.valueOf("CHANGE").getPaymentType(), BigDecimal.valueOf(payAmount).subtract(total).doubleValue())); // } // // getContext().setOpenTicket(new OpenTicket(getContext().getUser())); // // return ticket; // // } else { // throw new UnsupportedOperationException("Not supported yet."); // } // } finally { // if (connection != null) { // connection.close(); // } // } // } }
src/main/java/mobi/nordpos/retail/action/OrderPaymentActionBean.java
/** * Copyright (c) 2012-2015 Nord Trading Network. * * 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 mobi.nordpos.retail.action; import java.math.BigDecimal; import java.net.UnknownHostException; import java.sql.SQLException; import java.util.Date; import java.util.UUID; import mobi.nordpos.dao.model.ClosedCash; import mobi.nordpos.dao.model.Receipt; import mobi.nordpos.dao.ormlite.ClosedCashPersist; import net.sourceforge.stripes.action.ForwardResolution; import net.sourceforge.stripes.action.Resolution; import net.sourceforge.stripes.action.SimpleMessage; import net.sourceforge.stripes.validation.SimpleError; import net.sourceforge.stripes.validation.Validate; import net.sourceforge.stripes.validation.ValidationErrors; import net.sourceforge.stripes.validation.ValidationMethod; /** * @author Andrey Svininykh <[email protected]> */ public class OrderPaymentActionBean extends OrderBaseActionBean { private static final String PAYMENT_VIEW = "/WEB-INF/jsp/order_payment.jsp"; @Validate(on = {"post"}, required = true, expression = "${(paymentType == 'cash' && paymentAmount >= total) || (paymentType == 'magcard' && paymentAmount == total) }") private BigDecimal paymentAmount; @Validate(on = {"post"}, required = true, expression = "${paymentType == 'cash' || paymentType == 'magcard'}") private String paymentType; private UUID openCashId; public Resolution view() { return new ForwardResolution(PAYMENT_VIEW); } public Resolution post() { try { sharedTicketPersist.init(getDataBaseConnection()); sharedTicketPersist.delete(getContext().getOrder().getId()); getContext().setOrder(null); } catch (SQLException ex) { getContext().getValidationErrors().addGlobalError( new SimpleError(ex.getMessage())); return getContext().getSourcePageResolution(); } return new ForwardResolution(WelcomeActionBean.class); } public BigDecimal getPaymentAmount() { return paymentAmount; } public void setPaymentAmount(BigDecimal paymentAmount) { this.paymentAmount = paymentAmount; } public String getPaymentType() { return paymentType; } public void setPaymentType(String paymentType) { this.paymentType = paymentType; } public BigDecimal getTotal() { return getContext().getOrder().getTotalValue(); } @ValidationMethod(on = "post") public void validateClosedCashIsOpen(ValidationErrors errors) throws UnknownHostException { String hostName = java.net.InetAddress.getLocalHost().getHostName(); ClosedCashPersist closedCashPersist = new ClosedCashPersist(); try { closedCashPersist.init(getDataBaseConnection()); openCashId = closedCashPersist.readOpen(hostName).getId(); if (openCashId == null) { ClosedCash closedCash = new ClosedCash(); closedCash.setHost(hostName); closedCash.setHostSequence(1); closedCash.setDateStart(new Date()); openCashId = closedCashPersist.add(closedCash).getId(); } } catch (SQLException ex) { getContext().getValidationErrors().addGlobalError( new SimpleError(ex.getMessage())); } } // public Ticket saveTicket(OpenTicket openTicket) throws SQLException { // try { // connection = new JdbcConnectionSource(getDataBaseURL(), getDataBaseUser(), getDataBasePassword()); // ReceiptDAO receiptDao = new ReceiptPersist(connection); // TicketDAO ticketDao = new TicketPersist(connection); // TicketNumberDAO ticketNumberDao = new TicketNumberPersist(connection); // // if (!openTicket.getTicketLineList().isEmpty()) { // Receipt receipt = receiptDao.createNew(getOpenCash()); // Ticket ticket = ticketDao.createNew(new Ticket( // receipt.getId(), // TicketType.SELL.getTicketType(), // ticketNumberDao.generate(), // receipt, // openTicket.getUser(), // openTicket.getFiscalNumber())); // ticket.setTicketLineCollection(openTicket.getTicketLineList()); // // ForeignCollection<TicketLine> ticketLineCollection = ticket.getTicketLineCollection(); // CloseableIterator<TicketLine> ticketLineIterator = ticketLineCollection.closeableIterator(); // // ForeignCollection<TaxLine> taxLineCollection = receipt.getTaxLineCollection(); // // try { // while (ticketLineIterator.hasNext()) { // TicketLine line = ticketLineIterator.next(); // Tax selectTax = line.getTax(); // CloseableIterator<TaxLine> taxLineIterator = taxLineCollection.closeableIterator(); // TaxLine newTaxLine = new TaxLine( // receipt, // selectTax, // line.getSubTotal().doubleValue(), // line.getTaxAmountSubTotal().doubleValue()); // // boolean f = true; // try { // while (taxLineIterator.hasNext()) { // TaxLine taxLine = taxLineIterator.next(); // if (taxLine.getTax().getId().equals(selectTax.getId())) { // taxLine.setBase(taxLine.getBase() + line.getSubTotal().doubleValue()); // taxLine.setAmount(taxLine.getAmount() + line.getTaxAmountSubTotal().doubleValue()); // taxLineCollection.update(taxLine); // f = false; // break; // } // } // } finally { // taxLineIterator.close(); // } // // if (f) { // taxLineCollection.add(newTaxLine); // } // } // } finally { // ticketLineIterator.close(); // } // // ForeignCollection<Payment> paymentCollection = receipt.getPaymentCollection(); // BigDecimal total = openTicket.getTaxTotal(); // paymentCollection.add(new Payment(receipt, paymentType, payAmount)); // if (paymentType.equals(PaymentType.valueOf("CASH").getPaymentType()) && payAmount > total.doubleValue()) { // paymentCollection.add(new Payment(receipt, PaymentType.valueOf("CHANGE").getPaymentType(), BigDecimal.valueOf(payAmount).subtract(total).doubleValue())); // } // // getContext().setOpenTicket(new OpenTicket(getContext().getUser())); // // return ticket; // // } else { // throw new UnsupportedOperationException("Not supported yet."); // } // } finally { // if (connection != null) { // connection.close(); // } // } // } }
Minot: Save receipt.
src/main/java/mobi/nordpos/retail/action/OrderPaymentActionBean.java
Minot: Save receipt.
<ide><path>rc/main/java/mobi/nordpos/retail/action/OrderPaymentActionBean.java <ide> import java.net.UnknownHostException; <ide> import java.sql.SQLException; <ide> import java.util.Date; <del>import java.util.UUID; <ide> import mobi.nordpos.dao.model.ClosedCash; <ide> import mobi.nordpos.dao.model.Receipt; <add>import mobi.nordpos.dao.model.Ticket; <add>import mobi.nordpos.dao.model.Ticket.TicketType; <add>import mobi.nordpos.dao.model.TicketNumber; <add>import mobi.nordpos.dao.model.User; <ide> import mobi.nordpos.dao.ormlite.ClosedCashPersist; <add>import mobi.nordpos.dao.ormlite.ReceiptPersist; <add>import mobi.nordpos.dao.ormlite.TicketNumberPersist; <add>import mobi.nordpos.dao.ormlite.UserPersist; <ide> import net.sourceforge.stripes.action.ForwardResolution; <ide> import net.sourceforge.stripes.action.Resolution; <del>import net.sourceforge.stripes.action.SimpleMessage; <ide> import net.sourceforge.stripes.validation.SimpleError; <ide> import net.sourceforge.stripes.validation.Validate; <ide> import net.sourceforge.stripes.validation.ValidationErrors; <ide> public class OrderPaymentActionBean extends OrderBaseActionBean { <ide> <ide> private static final String PAYMENT_VIEW = "/WEB-INF/jsp/order_payment.jsp"; <add> <add> private static final String DEFAULT_USER_ID = "3"; <ide> <ide> @Validate(on = {"post"}, required = true, expression = "${(paymentType == 'cash' && paymentAmount >= total) || (paymentType == 'magcard' && paymentAmount == total) }") <ide> private BigDecimal paymentAmount; <ide> @Validate(on = {"post"}, required = true, expression = "${paymentType == 'cash' || paymentType == 'magcard'}") <ide> private String paymentType; <ide> <del> private UUID openCashId; <add> private ClosedCash openCash; <ide> <ide> public Resolution view() { <ide> return new ForwardResolution(PAYMENT_VIEW); <ide> } <ide> <ide> public Resolution post() { <add> ReceiptPersist receiptPersist = new ReceiptPersist(); <add> UserPersist userPersist = new UserPersist(); <add> TicketNumberPersist ticketNumberPersist = new TicketNumberPersist(); <add> <ide> try { <add> receiptPersist.init(getDataBaseConnection()); <add> userPersist.init(getDataBaseConnection()); <add> ticketNumberPersist.init(getDataBaseConnection()); <add> <add> Receipt receipt = new Receipt(); <add> receipt.setClosedCash(openCash); <add> receipt.setDate(new Date()); <add> <add> receipt = receiptPersist.add(receipt); <add> <add> Ticket ticket = new Ticket(); <add> ticket.setId(receipt.getId()); <add> ticket.setType(TicketType.SELL.getTicketType()); <add> <add> User user = userPersist.read(DEFAULT_USER_ID); <add> ticket.setUser(user); <add> <add> TicketNumber number = ticketNumberPersist.readList().get(0); <add> if (getDataBaseConnection().getDatabaseType().getDatabaseName().equals("Derby Client/Server")) { <add> if (ticketNumberPersist.delete(number)) { <add> number = ticketNumberPersist.add(new TicketNumber()); <add> } <add> } else { <add> if (ticketNumberPersist.change(number)) { <add> number = ticketNumberPersist.readList().get(0); <add> } <add> } <add> ticket.setNumber(number.getId()); <add> <ide> sharedTicketPersist.init(getDataBaseConnection()); <ide> sharedTicketPersist.delete(getContext().getOrder().getId()); <ide> getContext().setOrder(null); <ide> ClosedCashPersist closedCashPersist = new ClosedCashPersist(); <ide> try { <ide> closedCashPersist.init(getDataBaseConnection()); <del> openCashId = closedCashPersist.readOpen(hostName).getId(); <del> if (openCashId == null) { <del> ClosedCash closedCash = new ClosedCash(); <del> closedCash.setHost(hostName); <del> closedCash.setHostSequence(1); <del> closedCash.setDateStart(new Date()); <del> openCashId = closedCashPersist.add(closedCash).getId(); <add> openCash = closedCashPersist.readOpen(hostName); <add> if (openCash == null) { <add> openCash = new ClosedCash(); <add> openCash.setHost(hostName); <add> openCash.setHostSequence(1); <add> openCash.setDateStart(new Date()); <add> openCash = closedCashPersist.add(openCash); <ide> } <ide> } catch (SQLException ex) { <ide> getContext().getValidationErrors().addGlobalError(
Java
apache-2.0
187bbf9ba66ab88176b4d917f85a0cad60dac2ad
0
dubex/concourse,dubex/concourse,dubex/concourse,cinchapi/concourse,cinchapi/concourse,cinchapi/concourse,dubex/concourse,cinchapi/concourse,dubex/concourse,cinchapi/concourse,cinchapi/concourse,dubex/concourse
/* * Copyright (c) 2013-2016 Cinchapi 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 com.cinchapi.concourse.server.cli; import java.nio.file.Files; import java.nio.file.Paths; import java.text.DecimalFormat; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.thrift.TException; import com.beust.jcommander.Parameter; import com.cinchapi.concourse.server.concurrent.Threads; import com.cinchapi.concourse.server.io.FileSystem; import com.cinchapi.concourse.server.management.ConcourseManagementService; import com.google.common.base.Preconditions; import com.google.common.base.Strings; /** * A management CLI to add/remove/upgrade/etc plugins. * * @author Jeff Nelson */ public class ManagePluginsCli extends ManagementCli { /** * An enum that represents broad code paths for the CLIs operations. * * @author Jeff Nelson */ private static enum CodePath { INSTALL, LIST_BUNDLES, UNINSTALL_BUNDLE, NONE; /** * Given a collection of {@code options}, figure out the correct * {@link CodePath code path} based on precedence rules. * * @param options the {@link PluginOptions} that were parsed * @return the correct {@link CodePath} */ public static CodePath getCodePath(PluginOptions options) { if(options.listBundles) { return LIST_BUNDLES; } else if(!Strings.isNullOrEmpty(options.install)) { return INSTALL; } else if(!Strings.isNullOrEmpty(options.uninstallBundle)) { return UNINSTALL_BUNDLE; } else { return NONE; } } } /** * Run the program... * * @param args */ public static void main(String... args) { ManagePluginsCli cli = new ManagePluginsCli(args); cli.run(); } /** * Construct a new instance. * * @param args */ public ManagePluginsCli(String[] args) { super(new PluginOptions(), args); } /** * Render a progress bar that shows something is {@code percent} done. * @param percent the percent done * @return the progress bar to print */ private static String renderPercentDone(double percent) { Preconditions.checkArgument(percent >= 0 && percent <= 100); DecimalFormat format= new DecimalFormat("##0.00"); StringBuilder sb = new StringBuilder(); sb.append(format.format(percent)).append("% "); sb.append("["); for (int i = 0; i < percent; ++i) { sb.append("="); } sb.append(">"); for (int i = (int) Math.ceil(percent); i < 100; ++i) { sb.append(" "); } sb.append("]"); return sb.toString(); } @Override protected void doTask(ConcourseManagementService.Client client) { PluginOptions opts = (PluginOptions) this.options; CodePath codePath = CodePath.getCodePath(opts); switch (codePath) { case INSTALL: String path = FileSystem.expandPath(opts.install, getLaunchDirectory()); if(Files.exists(Paths.get(path))) { try { AtomicBoolean done = new AtomicBoolean(false); Thread tracker = new Thread(() -> { double percent = 0; Threads.sleep(1000); while (!done.get()) { System.out.print("\r" + renderPercentDone(percent)); percent = percent + ((100.0 - percent) / 32.0); Threads.sleep(1000); } }); tracker.setDaemon(true); tracker.start(); client.installPluginBundle(path, token); done.set(true); System.out.println("\r" + renderPercentDone(100)); } catch (TException e) { die(e.getMessage()); } System.out.println("Successfully installed " + path); } else { throw new UnsupportedOperationException( com.cinchapi.concourse.util.Strings .format("Cannot download plugin bundle '{}'. Please " + "manually download the plugin and " + "provide its local path to the " + "installer", opts.install)); } break; case UNINSTALL_BUNDLE: break; case LIST_BUNDLES: break; case NONE: default: parser.usage(); } } /** * Special options for the plugin cli. * * @author Jeff Nelson */ protected static class PluginOptions extends Options { @Parameter(names = { "-i", "--install", "-install" }, description = "The name or path to a plugin bundle to install") public String install; @Parameter(names = { "-x", "--uninstall-bundle" }, description = "The name of the plugin bundle to uninstall") public String uninstallBundle; @Parameter(names = { "-l", "--list-bundles" }, description = "list all the available plugins") public boolean listBundles; } }
concourse-server/src/main/java/com/cinchapi/concourse/server/cli/ManagePluginsCli.java
/* * Copyright (c) 2013-2016 Cinchapi 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 com.cinchapi.concourse.server.cli; import java.nio.file.Files; import java.nio.file.Paths; import org.apache.thrift.TException; import com.beust.jcommander.Parameter; import com.cinchapi.concourse.server.io.FileSystem; import com.cinchapi.concourse.server.management.ConcourseManagementService; import com.google.common.base.Strings; /** * A management CLI to add/remove/upgrade/etc plugins. * * @author Jeff Nelson */ public class ManagePluginsCli extends ManagementCli { /** * An enum that represents broad code paths for the CLIs operations. * * @author Jeff Nelson */ private static enum CodePath { INSTALL, LIST_BUNDLES, UNINSTALL_BUNDLE, NONE; /** * Given a collection of {@code options}, figure out the correct * {@link CodePath code path} based on precedence rules. * * @param options the {@link PluginOptions} that were parsed * @return the correct {@link CodePath} */ public static CodePath getCodePath(PluginOptions options) { if(options.listBundles) { return LIST_BUNDLES; } else if(!Strings.isNullOrEmpty(options.install)) { return INSTALL; } else if(!Strings.isNullOrEmpty(options.uninstallBundle)) { return UNINSTALL_BUNDLE; } else { return NONE; } } } /** * Run the program... * * @param args */ public static void main(String... args) { ManagePluginsCli cli = new ManagePluginsCli(args); cli.run(); } /** * Construct a new instance. * * @param args */ public ManagePluginsCli(String[] args) { super(new PluginOptions(), args); } @Override protected void doTask(ConcourseManagementService.Client client) { PluginOptions opts = (PluginOptions) this.options; CodePath codePath = CodePath.getCodePath(opts); switch (codePath) { case INSTALL: String path = FileSystem.expandPath(opts.install, getLaunchDirectory()); if(Files.exists(Paths.get(path))) { try { client.installPluginBundle(path, token); } catch (TException e) { die(e.getMessage()); } System.out.println("Successfully installed " + path); } else { throw new UnsupportedOperationException( com.cinchapi.concourse.util.Strings.format( "Cannot download plugin bundle '{}'. Please " + "manually download the plugin and " + "provide its local path to the " + "installer", opts.install)); } break; case UNINSTALL_BUNDLE: break; case LIST_BUNDLES: break; case NONE: default: parser.usage(); } } /** * Special options for the plugin cli. * * @author Jeff Nelson */ protected static class PluginOptions extends Options { @Parameter(names = { "-i", "--install", "-install" }, description = "The name or path to a plugin bundle to install") public String install; @Parameter(names = { "-x", "--uninstall-bundle" }, description = "The name of the plugin bundle to uninstall") public String uninstallBundle; @Parameter(names = { "-l", "--list-bundles" }, description = "list all the available plugins") public boolean listBundles; } }
add progress bar for plugin install
concourse-server/src/main/java/com/cinchapi/concourse/server/cli/ManagePluginsCli.java
add progress bar for plugin install
<ide><path>oncourse-server/src/main/java/com/cinchapi/concourse/server/cli/ManagePluginsCli.java <ide> <ide> import java.nio.file.Files; <ide> import java.nio.file.Paths; <add>import java.text.DecimalFormat; <add>import java.util.concurrent.CountDownLatch; <add>import java.util.concurrent.atomic.AtomicBoolean; <ide> <ide> import org.apache.thrift.TException; <ide> <ide> import com.beust.jcommander.Parameter; <add>import com.cinchapi.concourse.server.concurrent.Threads; <ide> import com.cinchapi.concourse.server.io.FileSystem; <ide> import com.cinchapi.concourse.server.management.ConcourseManagementService; <add>import com.google.common.base.Preconditions; <ide> import com.google.common.base.Strings; <ide> <ide> /** <ide> super(new PluginOptions(), args); <ide> } <ide> <add> /** <add> * Render a progress bar that shows something is {@code percent} done. <add> * @param percent the percent done <add> * @return the progress bar to print <add> */ <add> private static String renderPercentDone(double percent) { <add> Preconditions.checkArgument(percent >= 0 && percent <= 100); <add> DecimalFormat format= new DecimalFormat("##0.00"); <add> StringBuilder sb = new StringBuilder(); <add> sb.append(format.format(percent)).append("% "); <add> sb.append("["); <add> for (int i = 0; i < percent; ++i) { <add> sb.append("="); <add> } <add> sb.append(">"); <add> for (int i = (int) Math.ceil(percent); i < 100; ++i) { <add> sb.append(" "); <add> } <add> sb.append("]"); <add> return sb.toString(); <add> } <add> <ide> @Override <ide> protected void doTask(ConcourseManagementService.Client client) { <ide> PluginOptions opts = (PluginOptions) this.options; <ide> getLaunchDirectory()); <ide> if(Files.exists(Paths.get(path))) { <ide> try { <add> AtomicBoolean done = new AtomicBoolean(false); <add> Thread tracker = new Thread(() -> { <add> double percent = 0; <add> Threads.sleep(1000); <add> while (!done.get()) { <add> System.out.print("\r" + renderPercentDone(percent)); <add> percent = percent + ((100.0 - percent) / 32.0); <add> Threads.sleep(1000); <add> } <add> }); <add> tracker.setDaemon(true); <add> tracker.start(); <ide> client.installPluginBundle(path, token); <add> done.set(true); <add> System.out.println("\r" + renderPercentDone(100)); <ide> } <ide> catch (TException e) { <ide> die(e.getMessage()); <ide> } <ide> else { <ide> throw new UnsupportedOperationException( <del> com.cinchapi.concourse.util.Strings.format( <del> "Cannot download plugin bundle '{}'. Please " <add> com.cinchapi.concourse.util.Strings <add> .format("Cannot download plugin bundle '{}'. Please " <ide> + "manually download the plugin and " <ide> + "provide its local path to the " <ide> + "installer", opts.install)); <ide> */ <ide> protected static class PluginOptions extends Options { <ide> <del> @Parameter(names = { "-i", "--install", "-install" }, description = "The name or path to a plugin bundle to install") <add> @Parameter(names = { "-i", "--install", <add> "-install" }, description = "The name or path to a plugin bundle to install") <ide> public String install; <ide> <del> @Parameter(names = { "-x", "--uninstall-bundle" }, description = "The name of the plugin bundle to uninstall") <add> @Parameter(names = { "-x", <add> "--uninstall-bundle" }, description = "The name of the plugin bundle to uninstall") <ide> public String uninstallBundle; <ide> <del> @Parameter(names = { "-l", "--list-bundles" }, description = "list all the available plugins") <add> @Parameter(names = { "-l", <add> "--list-bundles" }, description = "list all the available plugins") <ide> public boolean listBundles; <ide> } <ide>
JavaScript
mit
d1d271faeefc7845c70660bce91214af6e38ef97
0
telehash/e3x-js
var NodeCrypto = require("crypto"); var sjcl = require("sjcl"); var subtle = require("subtle") , pkcsPad1 = new Buffer([48, 130]) , pkcsPad2 = new Buffer([2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130]) function pkcs8_pad(privateBytes){ var off1 = new Buffer([Math.floor(privateBytes.length / 256),((privateBytes.length + 22) % 256) ]) var off2 = new Buffer([Math.floor(privateBytes.length / 256), (privateBytes.length % 256)]) return Buffer.concat([pkcsPad1, off1, pkcsPad2, off2, privateBytes]); } function pkcs8_unpad(privateBytes){ return privateBytes.slice(pkcsPad1.length + pkcsPad2.length + 4); } function Bufferize(arraybuffer){ return new Buffer(new Uint8Array(arraybuffer)) } exports.id = '2a'; // env-specific crypto methods var forge; var cecc; exports.crypt = function(ecc,f) { cecc = ecc; forge = f; } var rsa_alg = { name: "RSA-OAEP" , hash: {name: "SHA-256"} , modulusLength:2048 , publicExponent : new Uint8Array([0x01,0x00,0x01]) }; exports._generate = function(){ var usage = ["encrypt","decrypt"]; var extractable = true; return subtle.generateKey(rsa_alg, extractable, usage) .then(function(pair){ return Promise.all([ subtle.exportKey("pkcs8",pair.privateKey) , subtle.exportKey("spki",pair.publicKey) ]); }).then(function(jwks){ return { key: Bufferize(jwks[1]) , secret : Bufferize(jwks[0]) }; }); } exports._loadkey = function(id, key, secret){ var alg = {}, importer; function privateHandler(privates){ var oaep = privates[0] , ssa = privates[1]; id.sign = function cs2a_sign(buf){ return subtle.sign({name: "RSASSA-PKCS1-v1_5"}, ssa, buf) .then(Bufferize).catch(function(e){console.log("sign err",e)}); } id.decrypt = function cs2a_decrypt(buf){ return subtle.decrypt({name: "RSA-OAEP",hash:{name:"SHA-1"}}, oaep, buf) .then(Bufferize).catch(function(e){console.log("decrypt err",e.stack)}); } } function publicHandler(publics){ var oaep = publics[0] , ssa = publics[1]; id.encrypt = function cs2a_encrypt(buf){ return subtle.encrypt({name: "RSA-OAEP"}, oaep, buf) .then(Bufferize).catch(function(e){console.log("encrypt err",e)}); } id.verify = function cs2a_verify(a,b){ return subtle.verify({name: "RSASSA-PKCS1-v1_5"}, ssa, b, a) .catch(function(e){ console.log("verify err",e) }) } return id; } function secret_import(secret){ return Promise.all([ subtle.importKey("pkcs8", secret, {name: "RSA-OAEP", hash: {name: "SHA-1"}}, false, ["decrypt"]) , subtle.importKey("pkcs8", secret, {name: "RSASSA-PKCS1-v1_5", hash: {name: "SHA-256"}}, false, ["sign"])]); } function public_import(){ return Promise.all([ subtle.importKey("spki", key, {name: "RSA-OAEP", hash: {name: "SHA-1"}}, false, ["encrypt"]) , subtle.importKey("spki", key, {name: "RSASSA-PKCS1-v1_5", hash: {name: "SHA-256"}}, false, ["verify"])]); } secret = (secret) ? pkcs8_pad(secret) : null; secret = (secret) ? secret_import(secret).then(privateHandler) : Promise.resolve(); return secret.then(public_import).then(publicHandler); } exports.generate = function(cb) { var keys = forge.rsa.generateKeyPair({bits: 2048, e: 0x10001}); if(!keys) return cb("failed to generate rsa keys"); var key = forge.asn1.toDer(forge.pki.publicKeyToAsn1(keys.publicKey)).bytes(); var secret = forge.asn1.toDer(forge.pki.privateKeyToAsn1(keys.privateKey)).bytes(); cb(null, {key:new Buffer(key, 'binary'), secret:new Buffer(secret, 'binary')}); } exports.loadkey = function(id, key, secret) { var pk = forge.pki.publicKeyFromAsn1(forge.asn1.fromDer(key.toString("binary"))); id.encrypt = function(buf){ return new Buffer(pk.encrypt(buf.toString("binary"), "RSA-OAEP"), "binary"); }; id.verify = function(a,b){ var md = forge.md.sha256.create(); md.update(a.toString("binary")); var bytes = md.digest().bytes() return pk.verify(bytes, b.toString("binary")); }; if(secret) { var sk = forge.pki.privateKeyFromAsn1(forge.asn1.fromDer(secret.toString("binary"))); id.sign = function(buf){ var md = forge.md.sha256.create(); md.update(buf.toString("binary")); return new Buffer(sk.sign(md),"binary"); }; id.decrypt = function(buf){ ////console.log("l") return new Buffer(sk.decrypt(buf.toString("binary"), "RSA-OAEP"),"binary"); }; } return undefined; } exports._Local = function(pair){ if (!(pair && pair.key && pair.secret)) return Promise.reject(new Error("must supply valid keypair")) var self = this; self.key = {}; function aes_unpack(body){ var keyBytes = body.slice(0,256) return self.key.decrypt(keyBytes) .then(function(keys){ if(!keys || keys.length != (65+32)) throw new Error("failed to decrypt the aes keys") return { name : "AES-GCM", tagLength : 128, iv : body.slice(256,256 + 12), additionalData : body.slice(0,256), raw : keys.slice(65, 65 + 32), _keys : keys, body : body.slice(256 + 12) }; }); } function aes_decrypt(alg){ return subtle.importKey("raw",alg.raw, {name: "AES-GCM"},false,["encrypt","decrypt"]) .then(function(key){ return subtle.decrypt(alg, key, alg.body) }) .then(function(body){ var ret = body.slice(0, body.length - 256); ret._sig = body.slice(body.length - 256); ret._keys = alg._keys; return ret; }) } /* // rsa decrypt the keys return self.key.decrypt(b.slice(0,256)) .then(function(keys){ console.log("keys",keys.length) if(!keys || keys.length != (65+32)) return false; var body = b; var alg = { name: "AES-GCM" , tagLength: 128 , iv : body.slice(256,256+12) , additionalData: body.slice(0,256) }; console.log("decrypt keys") return subtle.importKey("raw",keys.slice(65,65+32), {name: "AES-GCM"},false,["encrypt","decrypt"]) .then(function(key){ return subtle.decrypt(alg, key, body.slice(256+12)) }) .then(function(body){ console.log("decrypt", body) var b = new Buffer(new Uint8Array(body)) console.log(b) var ret = b.slice(0,b.length-256); ret._keys = keys; ret._sig = b.slice(ret.length); return ret; }) }); */ self.decrypt = function cs2a_local_decrypt(body){ if(!Buffer.isBuffer(body)) return false; if(body.length < 256+12+256+16) return false; var b = body return aes_unpack(body).then(aes_decrypt); } function return_self(){ console.log("RETURN SELF") return self; } return exports._loadkey(self.key,pair.key, pair.secret) .then(return_self); } exports.Local = function(pair) { var self = this; self.key = {} try{ self.err = exports.loadkey(self.key,pair.key,pair.secret); }catch(E){ self.err = E; } // decrypt message body and return, the inner self.decrypt = function(body){ if(!Buffer.isBuffer(body)) return false; if(body.length < 256+12+256+16) return false; // rsa decrypt the keys var keys = self.key.decrypt(body.slice(0,256)); if(!keys || keys.length != (65+32)) return false; // aes decrypt the inner var keyhex = keys.slice(65,65+32).toString('hex'); var ivhex = body.slice(256,256+12).toString('hex'); var aadhex = body.slice(0,256).toString('hex'); var cbodyhex = body.slice(256+12).toString('hex'); var key = new sjcl.cipher.aes(sjcl.codec.hex.toBits(keyhex)); var iv = sjcl.codec.hex.toBits(ivhex); var aad = sjcl.codec.hex.toBits(aadhex); var cbody = sjcl.codec.hex.toBits(cbodyhex); var cipher = sjcl.mode.gcm.decrypt(key, cbody, iv, aad, 128); var body = new Buffer(sjcl.codec.hex.fromBits(cipher), 'hex'); // return buf of just the inner, add decrypted sig/keys var ret = body.slice(0,body.length-256); ret._keys = keys; ret._sig = body.slice(ret.length); return ret; }; } function subtle_remote(remote_public){ var self = this; self.key = {}; return exports._loadkey(self.key, remote_public) .then(function(){ return subtle.generateKey({name : "ECDH", namedCurve: "P-256"},true, ["deriveBits"]); }) .then(function (ecdhkeys){ self.ephemeral = ecdhkeys; return subtle.exportKey("spki", ecdhkeys.publicKey) }) .then(function (eccpub){ return self.key.encrypt(Buffer.concat([eccpub.slice(eccpub.length - 65), self.secret])); }) .then(function (keyBytes){ self.keys = keyBytes; return subtle.importKey("raw", self.secret,{name:"AES-GCM",tagLength:128}, false,["encrypt","decrypt"]) }); } function cs2a_remote(aeskey){ this.token = NodeCrypto.createHash('sha256').update(this.keys.slice(0,16)).digest().slice(0,16); var iv = NodeCrypto.randomBytes(12) , self = this; this.verify = function(local, body){ // decrypt it first var cached; return local.decrypt(body) .then(function(inner){ var toVerify = Buffer.concat([body.slice(0,256+12),inner]) cached = inner._keys; return self.key.verify( toVerify, inner._sig) }) .then(function(verified){ if (verified) self.cached = cached; return verified; }); }; this.encrypt = function(local, inner){ var seq = iv.readUInt32LE(0); iv.writeUInt32LE(++seq,0); // generate the signature return local.key.sign(Buffer.concat([self.keys,iv,inner])) .then(function(sig){ var body = Buffer.concat([inner, sig]) return subtle.encrypt({name: "AES-GCM", tagLength:128,iv:iv, additionalData : self.keys}, aeskey, body); }) .then(function(encrypted){ return Buffer.concat([self.keys,iv,encrypted]); }); }; return this; } exports._Remote = function(key) { this.secret = NodeCrypto.randomBytes(32); return subtle_remote.bind(this)(key).then(cs2a_remote.bind(this)); } exports.Remote = function(key) { var self = this; self.key = {}; try{ self.err = exports.loadkey(self.key,key); var curve = cecc.ECCurves.secp256r1 curve.legacy = true; self.ephemeral = new cecc.ECKey(curve); self.secret = NodeCrypto.randomBytes(32); self.iv = NodeCrypto.randomBytes(12); self.keys = self.key.encrypt(Buffer.concat([self.ephemeral.PublicKey,self.secret])); self.token = NodeCrypto.createHash('sha256').update(self.keys.slice(0,16)).digest().slice(0,16); }catch(E){ self.err = E; } if(self.err) //console.log("ERR",self.err,key.toString("hex")) // verifies the authenticity of an incoming message body self.verify = function(local, body){ if(!Buffer.isBuffer(body)) return false; // decrypt it first var inner = local.decrypt(body); if(!inner) return false; // verify the rsa signature if(!self.key.verify(Buffer.concat([body.slice(0,256+12),inner]), inner._sig)) return false; // cache the decrypted keys self.cached = inner._keys; return true; }; self.encrypt = function(local, inner){ if(!Buffer.isBuffer(inner)) return false; // increment the IV var seq = self.iv.readUInt32LE(0); seq++; self.iv.writeUInt32LE(seq,0); // generate the signature var sig = local.key.sign(Buffer.concat([self.keys,self.iv,inner])); // aes gcm encrypt the inner+sig var aad = self.keys; var body = Buffer.concat([inner,sig]); var key = new sjcl.cipher.aes(sjcl.codec.hex.toBits(self.secret.toString('hex'))); var iv = sjcl.codec.hex.toBits(self.iv.toString('hex')); var cipher = sjcl.mode.gcm.encrypt(key, sjcl.codec.hex.toBits(body.toString('hex')), iv, sjcl.codec.hex.toBits(aad.toString('hex')), 128); var cbody = new Buffer(sjcl.codec.hex.fromBits(cipher), 'hex'); // all done! return Buffer.concat([self.keys,self.iv,cbody]); }; } var spkiECCPad = new Buffer("3056301006042b81047006082a8648ce3d030107034200","hex") function subtle_ephemeral(remote, keys){ var aesBytes = keys.slice(65) , eccBytes = keys.slice(0, 65) , eccSPKI = Buffer.concat([spkiECCPad,eccBytes]); return subtle.importKey("spki", eccSPKI, {name:"ECDH",namedCurve:"P-256"},true,[]) .then(function(key){ return subtle.deriveBits({name:"ECDH", namedCurve:"P-256", public: key}, remote.ephemeral.privateKey,256) }) .then(function(ecdhe){ var encBytes = Buffer.concat([ecdhe, remote.secret,keys.slice(65)]) , decBytes = Buffer.concat([ecdhe, keys.slice(65),remote.secret]); return Promise.all([ subtle.digest({name:"SHA-256"}, encBytes) , subtle.digest({name:"SHA-256"}, decBytes) ]); }) .then(function(secrets){ var encBytes = secrets[0] , decBytes = secrets[1]; return Promise.all([ subtle.importKey("raw", encBytes,{name:"AES-GCM"},false, ["encrypt"]) , subtle.importKey("raw", decBytes,{name:"AES-GCM"},false, ["decrypt"]) ]); }) .then(function(cryptoKeys){ return { encKey : cryptoKeys[0], decKey : cryptoKeys[1] }; }) } function cs2a_ephemeral(keys){ var encKey = keys.encKey , decKey = keys.decKey , iv = NodeCrypto.randomBytes(12); this.encrypt = function cs2a_ephemeral_encrypt(inner){ // incriment the iv var seq = iv.readUInt32LE(0); iv.writeUInt32LE(++seq,0); return subtle.encrypt({name: "AES-GCM", iv:iv, additionalData: new Buffer(0), tagLength: 128}, encKey, inner) .then(function(cbody){ //attach the iv return Buffer.concat([iv, cbody]); }); }; this.decrypt = function cs2a_ephemeral_decrypt(outer){ return subtle.decrypt({ name: "AES-GCM" , iv:outer.slice(0,12) , additionalData: new Buffer(0) , tagLength: 128 } , decKey , outer.slice(12)); } return this; } exports._Ephemeral = function(remote, outer, inner){ var keys = remote.cached || (inner._keys); this.token = NodeCrypto.createHash('sha256').update(outer.slice(0,16)).digest().slice(0,16); return subtle_ephemeral(remote, keys).then(cs2a_ephemeral.bind(this)); } exports.Ephemeral = function(remote, outer, inner) { var self = this; try { // get the ecc key from cached or decrypted var keys = remote.cached || (inner && inner._keys); // do the ecdh thing var curve = cecc.ECCurves.secp256r1 curve.legacy = true; var ecc = new cecc.ECKey(curve, keys.slice(0,65), true); var ecdhe = remote.ephemeral.deriveSharedSecret(ecc); //////console.log("ECDHE", ecdhe, ecdhe.toString("hex")) // use the other two secrets too var secret = keys.slice(65); var hex = NodeCrypto.createHash("sha256") .update(ecdhe) .update(remote.secret) .update(secret) .digest("hex"); self.encKey = new sjcl.cipher.aes(sjcl.codec.hex.toBits(hex)); var hex = NodeCrypto.createHash("sha256") .update(ecdhe) .update(secret) .update(remote.secret) .digest("hex"); self.decKey = new sjcl.cipher.aes(sjcl.codec.hex.toBits(hex)); self.token = NodeCrypto.createHash('sha256').update(outer.slice(0,16)).digest().slice(0,16); self.iv = NodeCrypto.randomBytes(12); }catch(E){ self.err = E; } self.decrypt = function(outer){ try{ var ivhex = sjcl.codec.hex.toBits(outer.slice(0,12).toString("hex")); var cipher = sjcl.mode.gcm.decrypt(self.decKey, sjcl.codec.hex.toBits(outer.slice(12).toString("hex")), ivhex, [], 128); var inner = new Buffer(sjcl.codec.hex.fromBits(cipher),"hex"); }catch(E){ self.err = E; } return inner; }; self.encrypt = function(inner){ // increment the IV var seq = self.iv.readUInt32LE(0); seq++; self.iv.writeUInt32LE(seq,0); // now encrypt the packet var cipher = sjcl.mode.gcm.encrypt(self.encKey, sjcl.codec.hex.toBits(inner.toString("hex")), sjcl.codec.hex.toBits(self.iv.toString("hex")), [], 128); var cbody = new Buffer(sjcl.codec.hex.fromBits(cipher),"hex"); return Buffer.concat([self.iv,cbody]); }; }
ciphers/2a/cs2a.js
var NodeCrypto = require("crypto"); var sjcl = require("sjcl"); var subtle = require("subtle") , pkcsPad1 = new Buffer([48, 130]) , pkcsPad2 = new Buffer([2, 1, 0, 48, 13, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 1, 5, 0, 4, 130]) function pkcs8_pad(privateBytes){ var off1 = new Buffer([Math.floor(privateBytes.length / 256),((privateBytes.length + 22) % 256) ]) var off2 = new Buffer([Math.floor(privateBytes.length / 256), (privateBytes.length % 256)]) return Buffer.concat([pkcsPad1, off1, pkcsPad2, off2, privateBytes]); } function pkcs8_unpad(privateBytes){ return privateBytes.slice(pkcsPad1.length + pkcsPad2.length + 4); } function Bufferize(arraybuffer){ return new Buffer(new Uint8Array(arraybuffer)) } exports.id = '2a'; // env-specific crypto methods var forge; var cecc; exports.crypt = function(ecc,f) { cecc = ecc; forge = f; } var rsa_alg = { name: "RSA-OAEP" , hash: {name: "SHA-256"} , modulusLength:2048 , publicExponent : new Uint8Array([0x01,0x00,0x01]) }; exports._generate = function(){ var usage = ["encrypt","decrypt"]; var extractable = true; return subtle.generateKey(rsa_alg, extractable, usage) .then(function(pair){ return Promise.all([ subtle.exportKey("pkcs8",pair.privateKey) , subtle.exportKey("spki",pair.publicKey) ]); }).then(function(jwks){ return { key: Bufferize(jwks[1]) , secret : Bufferize(jwks[0]) }; }); } exports._loadkey = function(id, key, secret){ var alg = {}, importer; function privateHandler(privates){ var oaep = privates[0] , ssa = privates[1]; id.sign = function cs2a_sign(buf){ return subtle.sign({name: "RSASSA-PKCS1-v1_5"}, ssa, buf) .then(Bufferize).catch(function(e){console.log("sign err",e)}); } id.decrypt = function cs2a_decrypt(buf){ return subtle.decrypt({name: "RSA-OAEP",hash:{name:"SHA-1"}}, oaep, buf) .then(Bufferize).catch(function(e){console.log("decrypt err",e.stack)}); } } function publicHandler(publics){ var oaep = publics[0] , ssa = publics[1]; id.encrypt = function cs2a_encrypt(buf){ return subtle.encrypt({name: "RSA-OAEP"}, oaep, buf) .then(Bufferize).catch(function(e){console.log("encrypt err",e)}); } id.verify = function cs2a_verify(a,b){ return subtle.verify({name: "RSASSA-PKCS1-v1_5"}, ssa, b, a) .catch(function(e){ console.log("verify err",e) }) } return id; } function secret_import(secret){ return Promise.all([ subtle.importKey("pkcs8", secret, {name: "RSA-OAEP", hash: {name: "SHA-1"}}, false, ["decrypt"]) , subtle.importKey("pkcs8", secret, {name: "RSASSA-PKCS1-v1_5", hash: {name: "SHA-256"}}, false, ["sign"])]); } function public_import(){ return Promise.all([ subtle.importKey("spki", key, {name: "RSA-OAEP", hash: {name: "SHA-1"}}, false, ["encrypt"]) , subtle.importKey("spki", key, {name: "RSASSA-PKCS1-v1_5", hash: {name: "SHA-256"}}, false, ["verify"])]); } secret = (secret) ? pkcs8_pad(secret) : null; secret = (secret) ? secret_import(secret).then(privateHandler) : Promise.resolve(); return secret.then(public_import).then(publicHandler); } exports.generate = function(cb) { var keys = forge.rsa.generateKeyPair({bits: 2048, e: 0x10001}); if(!keys) return cb("failed to generate rsa keys"); var key = forge.asn1.toDer(forge.pki.publicKeyToAsn1(keys.publicKey)).bytes(); var secret = forge.asn1.toDer(forge.pki.privateKeyToAsn1(keys.privateKey)).bytes(); cb(null, {key:new Buffer(key, 'binary'), secret:new Buffer(secret, 'binary')}); } exports.loadkey = function(id, key, secret) { var pk = forge.pki.publicKeyFromAsn1(forge.asn1.fromDer(key.toString("binary"))); id.encrypt = function(buf){ return new Buffer(pk.encrypt(buf.toString("binary"), "RSA-OAEP"), "binary"); }; id.verify = function(a,b){ var md = forge.md.sha256.create(); md.update(a.toString("binary")); var bytes = md.digest().bytes() return pk.verify(bytes, b.toString("binary")); }; if(secret) { var sk = forge.pki.privateKeyFromAsn1(forge.asn1.fromDer(secret.toString("binary"))); id.sign = function(buf){ var md = forge.md.sha256.create(); md.update(buf.toString("binary")); return new Buffer(sk.sign(md),"binary"); }; id.decrypt = function(buf){ ////console.log("l") return new Buffer(sk.decrypt(buf.toString("binary"), "RSA-OAEP"),"binary"); }; } return undefined; } exports._Local = function(pair){ if (!(pair && pair.key && pair.secret)) return Promise.reject(new Error("must supply valid keypair")) var self = this; self.key = {}; function aes_unpack(body){ var keyBytes = body.slice(0,256) return self.key.decrypt(keyBytes) .then(function(keys){ if(!keys || keys.length != (65+32)) throw new Error("failed to decrypt the aes keys") return { name : "AES-GCM", tagLength : 128, iv : body.slice(256,256 + 12), additionalData : body.slice(0,256), raw : keys.slice(65, 65 + 32), _keys : keys, body : body.slice(256 + 12) }; }); } function aes_decrypt(alg){ return subtle.importKey("raw",alg.raw, {name: "AES-GCM"},false,["encrypt","decrypt"]) .then(function(key){ return subtle.decrypt(alg, key, alg.body) }) .then(function(body){ var ret = body.slice(0, body.length - 256); ret._sig = body.slice(body.length - 256); ret._keys = alg._keys; return ret; }) } /* // rsa decrypt the keys return self.key.decrypt(b.slice(0,256)) .then(function(keys){ console.log("keys",keys.length) if(!keys || keys.length != (65+32)) return false; var body = b; var alg = { name: "AES-GCM" , tagLength: 128 , iv : body.slice(256,256+12) , additionalData: body.slice(0,256) }; console.log("decrypt keys") return subtle.importKey("raw",keys.slice(65,65+32), {name: "AES-GCM"},false,["encrypt","decrypt"]) .then(function(key){ return subtle.decrypt(alg, key, body.slice(256+12)) }) .then(function(body){ console.log("decrypt", body) var b = new Buffer(new Uint8Array(body)) console.log(b) var ret = b.slice(0,b.length-256); ret._keys = keys; ret._sig = b.slice(ret.length); return ret; }) }); */ self.decrypt = function cs2a_local_decrypt(body){ if(!Buffer.isBuffer(body)) return false; if(body.length < 256+12+256+16) return false; var b = body return aes_unpack(body).then(aes_decrypt); } function return_self(){ console.log("RETURN SELF") return self; } return exports._loadkey(self.key,pair.key, pair.secret) .then(return_self); } exports.Local = function(pair) { var self = this; self.key = {} try{ self.err = exports.loadkey(self.key,pair.key,pair.secret); }catch(E){ self.err = E; } // decrypt message body and return, the inner self.decrypt = function(body){ if(!Buffer.isBuffer(body)) return false; if(body.length < 256+12+256+16) return false; // rsa decrypt the keys var keys = self.key.decrypt(body.slice(0,256)); if(!keys || keys.length != (65+32)) return false; // aes decrypt the inner var keyhex = keys.slice(65,65+32).toString('hex'); var ivhex = body.slice(256,256+12).toString('hex'); var aadhex = body.slice(0,256).toString('hex'); var cbodyhex = body.slice(256+12).toString('hex'); var key = new sjcl.cipher.aes(sjcl.codec.hex.toBits(keyhex)); var iv = sjcl.codec.hex.toBits(ivhex); var aad = sjcl.codec.hex.toBits(aadhex); var cbody = sjcl.codec.hex.toBits(cbodyhex); var cipher = sjcl.mode.gcm.decrypt(key, cbody, iv, aad, 128); var body = new Buffer(sjcl.codec.hex.fromBits(cipher), 'hex'); // return buf of just the inner, add decrypted sig/keys var ret = body.slice(0,body.length-256); ret._keys = keys; ret._sig = body.slice(ret.length); return ret; }; } exports._Remote = function(key) { var self = this; self.key = {} //console.log("EPHEMERAL", self.ephemeral) var alg = { name: "AES-GCM" , tagLength : 128 , length : 256 , iv : self.iv } var aesKey; //window.Buffer = Buffer; return subtle.generateKey( { name : "ECDH", namedCurve: "P-256", //can be "P-256", "P-384", or "P-521" }, true, //whether the key is extractable (i.e. can be used in exportKey) ["deriveBits"] //can be any combination of "deriveKey" and "deriveBits" ).then(function(key){ console.log('GENERATEKEY',key) self.ephemeral = { PrivateKey : key.privateKey }; return subtle.exportKey("spki", key.publicKey) }).then(function(pub){ var PublicKey = new Buffer(new Uint8Array(pub)) PublicKey = PublicKey.slice(PublicKey.length - 65) self.ephemeral.PublicKey = PublicKey; return "subtle" }) .catch(function(er){ console.log("CECC", er) var curve = cecc.ECCurves.secp256r1 curve.legacy = true; self.ephemeral = new cecc.ECKey(curve); //console.log("SELF.ephe",self.ephemeral) return "JS" }).then(function(){ self.secret = NodeCrypto.randomBytes(32) self.iv = NodeCrypto.randomBytes((12)) return subtle.importKey("raw", self.secret,alg, false,["encrypt","decrypt"] ) }).then(function(aeskey) // verifies the authenticity of an incoming message body { aesKey = aeskey return exports._loadkey(self.key,key) }).then(function(key){ var keys = Buffer.concat([self.ephemeral.PublicKey,self.secret]) //console.log("EPHEMERAL + SECRET", keys.length) return self.key.encrypt(keys).then(function(keys){ self.keys = new Buffer(new Uint8Array(keys)); alg.additionalData = self.keys; self.token = NodeCrypto.createHash('sha256').update(self.keys.slice(0,16)).digest().slice(0,16); //console.log("_Remote loadkey") self.verify = function(local, body){ //console.log(local,body,"VERIFY begin") if(!Buffer.isBuffer(body)) return false; // decrypt it first return local.decrypt(new Buffer(body)) .then(function(inner){ //console.log("decrypted body",inner) if(!inner) return false; //console.log(inner, inner._sig) // verify the rsa signature return key.verify(Buffer.concat([body.slice(0,256+12),inner]), inner._sig) .then(function(verified){ //console.log("verifieds?", verified) if (verified) self.cached = inner._keys; return verified; }) }); }; self.encrypt = function(local, inner){ if(!Buffer.isBuffer(inner)) return false; // increment the IV var seq = self.iv.readUInt32LE(0); seq++; self.iv.writeUInt32LE(seq,0); //console.log('self.iv', self.iv) alg.iv = self.iv; // generate the signature return local.key.sign(Buffer.concat([self.keys,self.iv,inner])) .then(function(sig){ // aes gcm encrypt the inner+sig var body = Buffer.concat([inner, new Buffer(new Uint8Array(sig))]) return subtle.encrypt(alg,aesKey, body) .then(function(crypted){ var cbody = new Buffer(new Uint8Array(crypted)) //console.log("crypted", cbody) return Buffer.concat([self.keys,self.iv,cbody]); }); // all done! }); }; return self; }); }); } exports.Remote = function(key) { var self = this; self.key = {}; try{ self.err = exports.loadkey(self.key,key); var curve = cecc.ECCurves.secp256r1 curve.legacy = true; self.ephemeral = new cecc.ECKey(curve); self.secret = NodeCrypto.randomBytes(32); self.iv = NodeCrypto.randomBytes(12); self.keys = self.key.encrypt(Buffer.concat([self.ephemeral.PublicKey,self.secret])); self.token = NodeCrypto.createHash('sha256').update(self.keys.slice(0,16)).digest().slice(0,16); }catch(E){ self.err = E; } if(self.err) //console.log("ERR",self.err,key.toString("hex")) // verifies the authenticity of an incoming message body self.verify = function(local, body){ if(!Buffer.isBuffer(body)) return false; // decrypt it first var inner = local.decrypt(body); if(!inner) return false; // verify the rsa signature if(!self.key.verify(Buffer.concat([body.slice(0,256+12),inner]), inner._sig)) return false; // cache the decrypted keys self.cached = inner._keys; return true; }; self.encrypt = function(local, inner){ if(!Buffer.isBuffer(inner)) return false; // increment the IV var seq = self.iv.readUInt32LE(0); seq++; self.iv.writeUInt32LE(seq,0); // generate the signature var sig = local.key.sign(Buffer.concat([self.keys,self.iv,inner])); // aes gcm encrypt the inner+sig var aad = self.keys; var body = Buffer.concat([inner,sig]); var key = new sjcl.cipher.aes(sjcl.codec.hex.toBits(self.secret.toString('hex'))); var iv = sjcl.codec.hex.toBits(self.iv.toString('hex')); var cipher = sjcl.mode.gcm.encrypt(key, sjcl.codec.hex.toBits(body.toString('hex')), iv, sjcl.codec.hex.toBits(aad.toString('hex')), 128); var cbody = new Buffer(sjcl.codec.hex.fromBits(cipher), 'hex'); // all done! return Buffer.concat([self.keys,self.iv,cbody]); }; } var spkiECCPad = new Buffer("3056301006042b81047006082a8648ce3d030107034200","hex") function subtle_ephemeral(remote, keys){ var aesBytes = keys.slice(65) , eccBytes = keys.slice(0, 65) , eccSPKI = Buffer.concat([spkiECCPad,eccBytes]) return subtle.importKey("spki", eccSPKI, {name:"ECDH",namedCurve:"P-256"},true,[]) .then(function(key){ return subtle.deriveBits({name:"ECDH", namedCurve:"P-256", public: key}, remote.ephemeral.PrivateKey,256) }) .then(function(ecdhe){ var encBytes = Buffer.concat([ecdhe, remote.secret,keys.slice(65)]) , decBytes = Buffer.concat([ecdhe, keys.slice(65),remote.secret]); return Promise.all([ subtle.digest({name:"SHA-256"}, encBytes) , subtle.digest({name:"SHA-256"}, decBytes) ]); }) .then(function(secrets){ var encBytes = secrets[0] , decBytes = secrets[1]; return Promise.all([ subtle.importKey("raw", encBytes,{name:"AES-GCM"},false, ["encrypt"]) , subtle.importKey("raw", decBytes,{name:"AES-GCM"},false, ["decrypt"]) ]); }) .then(function(cryptoKeys){ return { encKey : cryptoKeys[0], decKey : cryptoKeys[1] }; }) } function cs2a_ephemeral(keys){ var encKey = keys.encKey , decKey = keys.decKey , iv = NodeCrypto.randomBytes(12); this.encrypt = function cs2a_ephemeral_encrypt(inner){ // incriment the iv var seq = iv.readUInt32LE(0); iv.writeUInt32LE(++seq,0); return subtle.encrypt({name: "AES-GCM", iv:iv, additionalData: new Buffer(0), tagLength: 128}, encKey, inner) .then(function(cbody){ //attach the iv return Buffer.concat([iv, cbody]); }); }; this.decrypt = function cs2a_ephemeral_decrypt(outer){ return subtle.decrypt({ name: "AES-GCM" , iv:outer.slice(0,12) , additionalData: new Buffer(0) , tagLength: 128 } , decKey , outer.slice(12)); } return this; } exports._Ephemeral = function(remote, outer, inner){ var keys = remote.cached || (inner._keys); this.token = NodeCrypto.createHash('sha256').update(outer.slice(0,16)).digest().slice(0,16); this.iv = NodeCrypto.randomBytes(12); return subtle_ephemeral(remote, keys).then(cs2a_ephemeral.bind(this)); //console.log(spkiECCPad,keys.slice(0,65)); var ecdhe; console.log("!!!!!!!!", keys, remote.secret ) var eccSPKI = Buffer.concat([spkiECCPad,keys.slice(0,65)]) console.log("??????", eccSPKI) return subtle.importKey("spki", eccSPKI, {name:"ECDH",namedCurve:"P-256"},true,[]) .then(function(key){ console.log("PRIVATE KEY?",key, remote.ephemeral.PrivateKey) return subtle.deriveBits({name:"ECDH", namedCurve:"P-256", public: key}, remote.ephemeral.PrivateKey,256) }) .then(function(Ecdhe){ ecdhe = Ecdhe; self._enc = [ecdhe, remote.secret,keys.slice(65)] console.log("ECDH", ecdhe.toString("hex")) return subtle.digest({name:"SHA-256"}, Buffer.concat([ecdhe, remote.secret,keys.slice(65)])) }) .then(function(hash){ console.log("Digest", hash.toString("hex")) self._encBytes = hash.toString("hex") return subtle.importKey("raw",hash,{name:"AES-GCM"},false, ["encrypt"]) }) .then(function(encKey){ self.encKey = encKey return true }) .then(function(){ self._dec = [ecdhe, keys.slice(65),remote.secret] return subtle.digest({name:"SHA-256"}, Buffer.concat([ecdhe, keys.slice(65),remote.secret])) }) .then(function(hash){ console.log("decKey", hash.toString("hex")) self._decBytes = hash.toString("hex") return subtle.importKey("raw",hash,{name:"AES-GCM"},false, ["decrypt"]) }) .then(function(decKey){ self.decrypt = function(outer){ console.log("decrypt called",outer, self.decKey) return subtle.decrypt( { name: "AES-GCM", iv: outer.slice(0,12), additionalData: new Buffer(0), tagLength: 128}, self.decKey, outer.slice(12)) //The tagLength you used to encrypt }; self.encrypt = function(inner){ var seq = self.iv.readUInt32LE(0); seq++; self.iv.writeUInt32LE(seq,0); return subtle.encrypt({ name: "AES-GCM", iv: self.iv, additionalData: new Buffer(0), tagLength: 128}, self.encKey, inner) .then(function(cbody){ var packed = Buffer.concat([self.iv, cbody]) console.log("encrypted", packed, self.iv, cbody) return packed; }) }; return self; }) } exports.Ephemeral = function(remote, outer, inner) { var self = this; try { // get the ecc key from cached or decrypted var keys = remote.cached || (inner && inner._keys); // do the ecdh thing var curve = cecc.ECCurves.secp256r1 curve.legacy = true; var ecc = new cecc.ECKey(curve, keys.slice(0,65), true); var ecdhe = remote.ephemeral.deriveSharedSecret(ecc); //////console.log("ECDHE", ecdhe, ecdhe.toString("hex")) // use the other two secrets too var secret = keys.slice(65); var hex = NodeCrypto.createHash("sha256") .update(ecdhe) .update(remote.secret) .update(secret) .digest("hex"); self.encKey = new sjcl.cipher.aes(sjcl.codec.hex.toBits(hex)); var hex = NodeCrypto.createHash("sha256") .update(ecdhe) .update(secret) .update(remote.secret) .digest("hex"); self.decKey = new sjcl.cipher.aes(sjcl.codec.hex.toBits(hex)); self.token = NodeCrypto.createHash('sha256').update(outer.slice(0,16)).digest().slice(0,16); self.iv = NodeCrypto.randomBytes(12); }catch(E){ self.err = E; } self.decrypt = function(outer){ try{ var ivhex = sjcl.codec.hex.toBits(outer.slice(0,12).toString("hex")); var cipher = sjcl.mode.gcm.decrypt(self.decKey, sjcl.codec.hex.toBits(outer.slice(12).toString("hex")), ivhex, [], 128); var inner = new Buffer(sjcl.codec.hex.fromBits(cipher),"hex"); }catch(E){ self.err = E; } return inner; }; self.encrypt = function(inner){ // increment the IV var seq = self.iv.readUInt32LE(0); seq++; self.iv.writeUInt32LE(seq,0); // now encrypt the packet var cipher = sjcl.mode.gcm.encrypt(self.encKey, sjcl.codec.hex.toBits(inner.toString("hex")), sjcl.codec.hex.toBits(self.iv.toString("hex")), [], 128); var cbody = new Buffer(sjcl.codec.hex.fromBits(cipher),"hex"); return Buffer.concat([self.iv,cbody]); }; }
refactor remote
ciphers/2a/cs2a.js
refactor remote
<ide><path>iphers/2a/cs2a.js <ide> return ret; <ide> }; <ide> } <add> <add>function subtle_remote(remote_public){ <add> var self = this; <add> self.key = {}; <add> <add> return exports._loadkey(self.key, remote_public) <add> .then(function(){ <add> return subtle.generateKey({name : "ECDH", namedCurve: "P-256"},true, ["deriveBits"]); <add> }) <add> .then(function (ecdhkeys){ <add> self.ephemeral = ecdhkeys; <add> return subtle.exportKey("spki", ecdhkeys.publicKey) <add> <add> }) <add> .then(function (eccpub){ <add> return self.key.encrypt(Buffer.concat([eccpub.slice(eccpub.length - 65), self.secret])); <add> }) <add> .then(function (keyBytes){ <add> self.keys = keyBytes; <add> return subtle.importKey("raw", self.secret,{name:"AES-GCM",tagLength:128}, false,["encrypt","decrypt"]) <add> }); <add>} <add> <add>function cs2a_remote(aeskey){ <add> this.token = NodeCrypto.createHash('sha256').update(this.keys.slice(0,16)).digest().slice(0,16); <add> <add> var iv = NodeCrypto.randomBytes(12) <add> , self = this; <add> <add> this.verify = function(local, body){ <add> // decrypt it first <add> var cached; <add> return local.decrypt(body) <add> .then(function(inner){ <add> var toVerify = Buffer.concat([body.slice(0,256+12),inner]) <add> cached = inner._keys; <add> return self.key.verify( toVerify, inner._sig) <add> }) <add> .then(function(verified){ <add> if (verified) <add> self.cached = cached; <add> return verified; <add> }); <add> <add> }; <add> <add> this.encrypt = function(local, inner){ <add> var seq = iv.readUInt32LE(0); <add> iv.writeUInt32LE(++seq,0); <add> <add> // generate the signature <add> return local.key.sign(Buffer.concat([self.keys,iv,inner])) <add> .then(function(sig){ <add> var body = Buffer.concat([inner, sig]) <add> return subtle.encrypt({name: "AES-GCM", tagLength:128,iv:iv, additionalData : self.keys}, aeskey, body); <add> }) <add> .then(function(encrypted){ <add> return Buffer.concat([self.keys,iv,encrypted]); <add> }); <add> }; <add> return this; <add> <add>} <ide> exports._Remote = function(key) <ide> { <del> var self = this; <del> self.key = {} <del> //console.log("EPHEMERAL", self.ephemeral) <del> var alg = { <del> name: "AES-GCM" <del> , tagLength : 128 <del> , length : 256 <del> , iv : self.iv <del> } <del> var aesKey; <del> //window.Buffer = Buffer; <del> <del> return subtle.generateKey( <del> { <del> name : "ECDH", <del> namedCurve: "P-256", //can be "P-256", "P-384", or "P-521" <del> }, <del> true, //whether the key is extractable (i.e. can be used in exportKey) <del> ["deriveBits"] //can be any combination of "deriveKey" and "deriveBits" <del> ).then(function(key){ <del> console.log('GENERATEKEY',key) <del> self.ephemeral = { <del> PrivateKey : key.privateKey <del> }; <del> return subtle.exportKey("spki", key.publicKey) <del> }).then(function(pub){ <del> <del> var PublicKey = new Buffer(new Uint8Array(pub)) <del> PublicKey = PublicKey.slice(PublicKey.length - 65) <del> self.ephemeral.PublicKey = PublicKey; <del> return "subtle" <del> }) <del> .catch(function(er){ <del> console.log("CECC", er) <del> var curve = cecc.ECCurves.secp256r1 <del> curve.legacy = true; <del> self.ephemeral = new cecc.ECKey(curve); <del> //console.log("SELF.ephe",self.ephemeral) <del> return "JS" <del> }).then(function(){ <del> <del> self.secret = NodeCrypto.randomBytes(32) <del> self.iv = NodeCrypto.randomBytes((12)) <del> return subtle.importKey("raw", self.secret,alg, false,["encrypt","decrypt"] ) <del> }).then(function(aeskey) <del> // verifies the authenticity of an incoming message body <del> { <del> aesKey = aeskey <del> return exports._loadkey(self.key,key) <del> }).then(function(key){ <del> var keys = Buffer.concat([self.ephemeral.PublicKey,self.secret]) <del> //console.log("EPHEMERAL + SECRET", keys.length) <del> return self.key.encrypt(keys).then(function(keys){ <del> self.keys = new Buffer(new Uint8Array(keys)); <del> alg.additionalData = self.keys; <del> self.token = NodeCrypto.createHash('sha256').update(self.keys.slice(0,16)).digest().slice(0,16); <del> //console.log("_Remote loadkey") <del> <del> self.verify = function(local, body){ <del> //console.log(local,body,"VERIFY begin") <del> if(!Buffer.isBuffer(body)) return false; <del> <del> // decrypt it first <del> return local.decrypt(new Buffer(body)) <del> .then(function(inner){ <del> //console.log("decrypted body",inner) <del> if(!inner) return false; <del> <del> //console.log(inner, inner._sig) <del> <del> // verify the rsa signature <del> return key.verify(Buffer.concat([body.slice(0,256+12),inner]), inner._sig) <del> .then(function(verified){ <del> //console.log("verifieds?", verified) <del> if (verified) <del> self.cached = inner._keys; <del> return verified; <del> }) <del> }); <del> <del> }; <del> <del> self.encrypt = function(local, inner){ <del> if(!Buffer.isBuffer(inner)) return false; <del> <del> // increment the IV <del> var seq = self.iv.readUInt32LE(0); <del> seq++; <del> self.iv.writeUInt32LE(seq,0); <del> //console.log('self.iv', self.iv) <del> alg.iv = self.iv; <del> <del> // generate the signature <del> return local.key.sign(Buffer.concat([self.keys,self.iv,inner])) <del> .then(function(sig){ <del> <del> // aes gcm encrypt the inner+sig <del> var body = Buffer.concat([inner, new Buffer(new Uint8Array(sig))]) <del> return subtle.encrypt(alg,aesKey, body) <del> .then(function(crypted){ <del> var cbody = new Buffer(new Uint8Array(crypted)) <del> <del> //console.log("crypted", cbody) <del> return Buffer.concat([self.keys,self.iv,cbody]); <del> }); <del> // all done! <del> <del> }); <del> <del> <del> <del> }; <del> return self; <del> }); <del> }); <del> <del> <del> <add> this.secret = NodeCrypto.randomBytes(32); <add> <add> return subtle_remote.bind(this)(key).then(cs2a_remote.bind(this)); <ide> } <ide> <ide> exports.Remote = function(key) <ide> function subtle_ephemeral(remote, keys){ <ide> var aesBytes = keys.slice(65) <ide> , eccBytes = keys.slice(0, 65) <del> , eccSPKI = Buffer.concat([spkiECCPad,eccBytes]) <del> <add> , eccSPKI = Buffer.concat([spkiECCPad,eccBytes]); <ide> <ide> return subtle.importKey("spki", eccSPKI, {name:"ECDH",namedCurve:"P-256"},true,[]) <ide> .then(function(key){ <del> <del> return subtle.deriveBits({name:"ECDH", namedCurve:"P-256", public: key}, remote.ephemeral.PrivateKey,256) <add> return subtle.deriveBits({name:"ECDH", namedCurve:"P-256", public: key}, remote.ephemeral.privateKey,256) <ide> }) <ide> .then(function(ecdhe){ <ide> var encBytes = Buffer.concat([ecdhe, remote.secret,keys.slice(65)]) <ide> this.encrypt = function cs2a_ephemeral_encrypt(inner){ <ide> // incriment the iv <ide> var seq = iv.readUInt32LE(0); <del> <ide> iv.writeUInt32LE(++seq,0); <ide> <ide> return subtle.encrypt({name: "AES-GCM", iv:iv, additionalData: new Buffer(0), tagLength: 128}, encKey, inner) <ide> <ide> exports._Ephemeral = function(remote, outer, inner){ <ide> var keys = remote.cached || (inner._keys); <del> <ide> this.token = NodeCrypto.createHash('sha256').update(outer.slice(0,16)).digest().slice(0,16); <del> this.iv = NodeCrypto.randomBytes(12); <ide> <ide> return subtle_ephemeral(remote, keys).then(cs2a_ephemeral.bind(this)); <del> <del> <del> //console.log(spkiECCPad,keys.slice(0,65)); <del> var ecdhe; <del> console.log("!!!!!!!!", keys, remote.secret ) <del> var eccSPKI = Buffer.concat([spkiECCPad,keys.slice(0,65)]) <del> console.log("??????", eccSPKI) <del> return subtle.importKey("spki", eccSPKI, {name:"ECDH",namedCurve:"P-256"},true,[]) <del> .then(function(key){ <del> console.log("PRIVATE KEY?",key, remote.ephemeral.PrivateKey) <del> return subtle.deriveBits({name:"ECDH", namedCurve:"P-256", public: key}, remote.ephemeral.PrivateKey,256) <del> }) <del> .then(function(Ecdhe){ <del> ecdhe = Ecdhe; <del> self._enc = [ecdhe, remote.secret,keys.slice(65)] <del> console.log("ECDH", ecdhe.toString("hex")) <del> return subtle.digest({name:"SHA-256"}, Buffer.concat([ecdhe, remote.secret,keys.slice(65)])) <del> }) <del> .then(function(hash){ <del> console.log("Digest", hash.toString("hex")) <del> self._encBytes = hash.toString("hex") <del> return subtle.importKey("raw",hash,{name:"AES-GCM"},false, ["encrypt"]) <del> }) <del> .then(function(encKey){ <del> self.encKey = encKey <del> return true <del> }) <del> .then(function(){ <del> self._dec = [ecdhe, keys.slice(65),remote.secret] <del> return subtle.digest({name:"SHA-256"}, Buffer.concat([ecdhe, keys.slice(65),remote.secret])) <del> }) <del> .then(function(hash){ <del> console.log("decKey", hash.toString("hex")) <del> self._decBytes = hash.toString("hex") <del> return subtle.importKey("raw",hash,{name:"AES-GCM"},false, ["decrypt"]) <del> }) <del> .then(function(decKey){ <del> <del> self.decrypt = function(outer){ <del> console.log("decrypt called",outer, self.decKey) <del> return subtle.decrypt( { name: "AES-GCM", iv: outer.slice(0,12), additionalData: new Buffer(0), tagLength: 128}, self.decKey, outer.slice(12)) //The tagLength you used to encrypt <del> }; <del> <del> self.encrypt = function(inner){ <del> var seq = self.iv.readUInt32LE(0); <del> seq++; <del> self.iv.writeUInt32LE(seq,0); <del> <del> return subtle.encrypt({ name: "AES-GCM", iv: self.iv, additionalData: new Buffer(0), tagLength: 128}, self.encKey, inner) <del> .then(function(cbody){ <del> var packed = Buffer.concat([self.iv, cbody]) <del> <del> console.log("encrypted", packed, self.iv, cbody) <del> return packed; <del> }) <del> <del> }; <del> return self; <del> }) <del> <del> <ide> } <ide> <ide> exports.Ephemeral = function(remote, outer, inner)
Java
lgpl-2.1
566bfd508fe0a1e5f9b1cbbc957d1ecd72004dc0
0
schernolyas/hibernate-ogm,emmanuelbernard/hibernate-ogm,mp911de/hibernate-ogm,gunnarmorling/hibernate-ogm,uugaa/hibernate-ogm,DavideD/hibernate-ogm-cassandra,ZJaffee/hibernate-ogm,jhalliday/hibernate-ogm,DavideD/hibernate-ogm-contrib,ZJaffee/hibernate-ogm,DavideD/hibernate-ogm,Sanne/hibernate-ogm,hferentschik/hibernate-ogm,DavideD/hibernate-ogm,hibernate/hibernate-ogm,gunnarmorling/hibernate-ogm,tempbottle/hibernate-ogm,gunnarmorling/hibernate-ogm,uugaa/hibernate-ogm,jhalliday/hibernate-ogm,DavideD/hibernate-ogm,jhalliday/hibernate-ogm,schernolyas/hibernate-ogm,DavideD/hibernate-ogm-cassandra,Sanne/hibernate-ogm,tempbottle/hibernate-ogm,mp911de/hibernate-ogm,ZJaffee/hibernate-ogm,mp911de/hibernate-ogm,Sanne/hibernate-ogm,hibernate/hibernate-ogm,DavideD/hibernate-ogm,tempbottle/hibernate-ogm,hibernate/hibernate-ogm,DavideD/hibernate-ogm-contrib,DavideD/hibernate-ogm-cassandra,hibernate/hibernate-ogm,schernolyas/hibernate-ogm,Sanne/hibernate-ogm,uugaa/hibernate-ogm,DavideD/hibernate-ogm-contrib
/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ogm.datastore.spi; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.hibernate.ogm.datastore.spi.TupleOperationType.*; /** * Represents a Tuple (think of it as a row) * * A tuple accepts a TupleShapshot which is a read-only state * of the tuple at creation time. * * A tuple collects changes applied to it. These changes are represented by a * list of TupleOperation. It is intended that GridDialects retrieve to these actions and * reproduce them to the datastore. The list of changes is computed based off the snapshot. * * @author Emmanuel Bernard <[email protected]> */ public class Tuple { private final Map<String, TupleOperation> currentState = new HashMap<String, TupleOperation>(); private final TupleSnapshot snapshot; public Tuple(TupleSnapshot snapshot) { this.snapshot = snapshot; } public Object get(String column) { TupleOperation result = currentState.get( column ); if ( result == null ) { return snapshot.get( column ); } else if ( result.getType() == PUT_NULL || result.getType() == REMOVE ) { return null; } else { return result.getValue(); } } public void put(String column, Object value) { if ( value == null ) { currentState.put( column, new TupleOperation( column, null, PUT_NULL ) ); } currentState.put( column, new TupleOperation( column, value, PUT ) ); } public void remove(String column) { currentState.put( column, new TupleOperation( column, null, REMOVE ) ); } /** * Return the list of actions on the tuple. * Inherently deduplicated operations */ public Set<TupleOperation> getOperations() { return new HashSet<TupleOperation>( currentState.values() ); } public TupleSnapshot getSnapshot() { return snapshot; } public Set<String> getColumnNames() { Set<String> columnNames = new HashSet<String>( snapshot.getColumnNames() ); for ( TupleOperation op : currentState.values() ) { switch ( op.getType() ) { case PUT : case PUT_NULL : columnNames.add( op.getColumn() ); break; case REMOVE: columnNames.remove( op.getColumn() ); break; } } return columnNames; } }
hibernate-ogm-core/src/main/java/org/hibernate/ogm/datastore/spi/Tuple.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * JBoss, Home of Professional Open Source * Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors * as indicated by the @authors tag. All rights reserved. * See the copyright.txt in the distribution for a * full listing of individual contributors. * * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * 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, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. */ package org.hibernate.ogm.datastore.spi; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import static org.hibernate.ogm.datastore.spi.TupleOperationType.*; /** * Represents a Tuple (think of it as a row) * * A tuple accepts a TupleShapshot which is a read-only state * of the tuple at creation time. * * A tuple collects changes applied to it. These changes are represented by a * list of TupleOperation. It is intended that GridDialects retrieve to these actions and * reproduce them to the datastore. The list of changes is computed based off the snapshot. * * @author Emmanuel Bernard <[email protected]> */ public class Tuple { private final Map<String, TupleOperation> currentState = new HashMap<String, TupleOperation>(); private final TupleSnapshot snapshot; public Tuple(TupleSnapshot snapshot) { this.snapshot = snapshot; } public Object get(String column) { TupleOperation result = currentState.get( column ); if ( result == null ) { return snapshot.get( column ); } else if ( result.getType() == PUT_NULL || result.getType() == REMOVE ) { return result; } else { return result.getValue(); } } public void put(String column, Object value) { if ( value == null ) { currentState.put( column, new TupleOperation( column, null, PUT_NULL ) ); } currentState.put( column, new TupleOperation( column, value, PUT ) ); } public void remove(String column) { currentState.put( column, new TupleOperation( column, null, REMOVE ) ); } /** * Return the list of actions on the tuple. * Inherently deduplicated operations */ public Set<TupleOperation> getOperations() { return new HashSet<TupleOperation>( currentState.values() ); } public TupleSnapshot getSnapshot() { return snapshot; } public Set<String> getColumnNames() { Set<String> columnNames = new HashSet<String>( snapshot.getColumnNames() ); for ( TupleOperation op : currentState.values() ) { switch ( op.getType() ) { case PUT : case PUT_NULL : columnNames.add( op.getColumn() ); break; case REMOVE: columnNames.remove( op.getColumn() ); break; } } return columnNames; } }
OGM-69 get on a REMOVE or PUT_NULL operations should return null
hibernate-ogm-core/src/main/java/org/hibernate/ogm/datastore/spi/Tuple.java
OGM-69 get on a REMOVE or PUT_NULL operations should return null
<ide><path>ibernate-ogm-core/src/main/java/org/hibernate/ogm/datastore/spi/Tuple.java <ide> return snapshot.get( column ); <ide> } <ide> else if ( result.getType() == PUT_NULL || result.getType() == REMOVE ) { <del> return result; <add> return null; <ide> } <ide> else { <ide> return result.getValue();
Java
apache-2.0
c9d9271aafcad0805d3d3087964ae1abb75feae5
0
kzganesan/libgdx,collinsmith/libgdx,mumer92/libgdx,djom20/libgdx,alex-dorokhov/libgdx,haedri/libgdx-1,sarkanyi/libgdx,anserran/libgdx,czyzby/libgdx,gf11speed/libgdx,samskivert/libgdx,ttencate/libgdx,Xhanim/libgdx,mumer92/libgdx,basherone/libgdxcn,zhimaijoy/libgdx,MetSystem/libgdx,JFixby/libgdx,alex-dorokhov/libgdx,junkdog/libgdx,mumer92/libgdx,alex-dorokhov/libgdx,JDReutt/libgdx,libgdx/libgdx,youprofit/libgdx,titovmaxim/libgdx,kagehak/libgdx,revo09/libgdx,Arcnor/libgdx,codepoke/libgdx,MadcowD/libgdx,gf11speed/libgdx,basherone/libgdxcn,flaiker/libgdx,hyvas/libgdx,srwonka/libGdx,junkdog/libgdx,ninoalma/libgdx,sinistersnare/libgdx,SidneyXu/libgdx,antag99/libgdx,xpenatan/libgdx-LWJGL3,js78/libgdx,gouessej/libgdx,js78/libgdx,tell10glu/libgdx,sinistersnare/libgdx,SidneyXu/libgdx,tommycli/libgdx,hyvas/libgdx,JDReutt/libgdx,Heart2009/libgdx,MovingBlocks/libgdx,ya7lelkom/libgdx,BlueRiverInteractive/libgdx,noelsison2/libgdx,ricardorigodon/libgdx,copystudy/libgdx,nrallakis/libgdx,petugez/libgdx,andyvand/libgdx,JDReutt/libgdx,firefly2442/libgdx,Dzamir/libgdx,lordjone/libgdx,sarkanyi/libgdx,realitix/libgdx,noelsison2/libgdx,flaiker/libgdx,fiesensee/libgdx,Zomby2D/libgdx,alex-dorokhov/libgdx,titovmaxim/libgdx,copystudy/libgdx,gouessej/libgdx,gf11speed/libgdx,azakhary/libgdx,Gliby/libgdx,JDReutt/libgdx,Badazdz/libgdx,SidneyXu/libgdx,collinsmith/libgdx,hyvas/libgdx,snovak/libgdx,PedroRomanoBarbosa/libgdx,toa5/libgdx,ya7lelkom/libgdx,djom20/libgdx,noelsison2/libgdx,titovmaxim/libgdx,UnluckyNinja/libgdx,josephknight/libgdx,Thotep/libgdx,nudelchef/libgdx,TheAks999/libgdx,TheAks999/libgdx,curtiszimmerman/libgdx,kagehak/libgdx,BlueRiverInteractive/libgdx,gdos/libgdx,ttencate/libgdx,toloudis/libgdx,GreenLightning/libgdx,xranby/libgdx,alex-dorokhov/libgdx,Badazdz/libgdx,bgroenks96/libgdx,collinsmith/libgdx,saltares/libgdx,UnluckyNinja/libgdx,kzganesan/libgdx,lordjone/libgdx,srwonka/libGdx,nave966/libgdx,anserran/libgdx,sjosegarcia/libgdx,zommuter/libgdx,srwonka/libGdx,Senth/libgdx,lordjone/libgdx,copystudy/libgdx,curtiszimmerman/libgdx,FredGithub/libgdx,sinistersnare/libgdx,fwolff/libgdx,gf11speed/libgdx,nooone/libgdx,stinsonga/libgdx,tommycli/libgdx,anserran/libgdx,Wisienkas/libgdx,billgame/libgdx,Wisienkas/libgdx,NathanSweet/libgdx,Zomby2D/libgdx,fwolff/libgdx,ricardorigodon/libgdx,js78/libgdx,1yvT0s/libgdx,toa5/libgdx,bgroenks96/libgdx,toa5/libgdx,sjosegarcia/libgdx,ThiagoGarciaAlves/libgdx,antag99/libgdx,ryoenji/libgdx,Deftwun/libgdx,ztv/libgdx,katiepino/libgdx,1yvT0s/libgdx,kagehak/libgdx,1yvT0s/libgdx,Heart2009/libgdx,junkdog/libgdx,MovingBlocks/libgdx,firefly2442/libgdx,del-sol/libgdx,djom20/libgdx,bgroenks96/libgdx,alireza-hosseini/libgdx,alex-dorokhov/libgdx,designcrumble/libgdx,noelsison2/libgdx,tommycli/libgdx,srwonka/libGdx,fwolff/libgdx,alireza-hosseini/libgdx,cypherdare/libgdx,ya7lelkom/libgdx,czyzby/libgdx,Dzamir/libgdx,TheAks999/libgdx,MadcowD/libgdx,saqsun/libgdx,petugez/libgdx,gdos/libgdx,1yvT0s/libgdx,djom20/libgdx,nelsonsilva/libgdx,xoppa/libgdx,Senth/libgdx,FyiurAmron/libgdx,nrallakis/libgdx,designcrumble/libgdx,toloudis/libgdx,del-sol/libgdx,copystudy/libgdx,billgame/libgdx,petugez/libgdx,revo09/libgdx,yangweigbh/libgdx,haedri/libgdx-1,tommycli/libgdx,petugez/libgdx,katiepino/libgdx,davebaol/libgdx,alex-dorokhov/libgdx,Xhanim/libgdx,ninoalma/libgdx,sarkanyi/libgdx,youprofit/libgdx,alireza-hosseini/libgdx,nooone/libgdx,Heart2009/libgdx,Zomby2D/libgdx,nrallakis/libgdx,kagehak/libgdx,zhimaijoy/libgdx,codepoke/libgdx,toloudis/libgdx,codepoke/libgdx,KrisLee/libgdx,sinistersnare/libgdx,haedri/libgdx-1,shiweihappy/libgdx,jsjolund/libgdx,BlueRiverInteractive/libgdx,youprofit/libgdx,ThiagoGarciaAlves/libgdx,hyvas/libgdx,ya7lelkom/libgdx,youprofit/libgdx,nrallakis/libgdx,ThiagoGarciaAlves/libgdx,309746069/libgdx,Wisienkas/libgdx,junkdog/libgdx,Arcnor/libgdx,309746069/libgdx,FyiurAmron/libgdx,Heart2009/libgdx,MikkelTAndersen/libgdx,ryoenji/libgdx,ricardorigodon/libgdx,hyvas/libgdx,tommyettinger/libgdx,PedroRomanoBarbosa/libgdx,xoppa/libgdx,KrisLee/libgdx,flaiker/libgdx,MadcowD/libgdx,basherone/libgdxcn,codepoke/libgdx,KrisLee/libgdx,andyvand/libgdx,josephknight/libgdx,libgdx/libgdx,nooone/libgdx,jsjolund/libgdx,haedri/libgdx-1,kotcrab/libgdx,davebaol/libgdx,del-sol/libgdx,andyvand/libgdx,gouessej/libgdx,revo09/libgdx,firefly2442/libgdx,alireza-hosseini/libgdx,stinsonga/libgdx,Arcnor/libgdx,samskivert/libgdx,ztv/libgdx,SidneyXu/libgdx,gouessej/libgdx,davebaol/libgdx,tell10glu/libgdx,Gliby/libgdx,antag99/libgdx,flaiker/libgdx,josephknight/libgdx,ya7lelkom/libgdx,Gliby/libgdx,xranby/libgdx,MikkelTAndersen/libgdx,ryoenji/libgdx,antag99/libgdx,1yvT0s/libgdx,nave966/libgdx,ryoenji/libgdx,toa5/libgdx,titovmaxim/libgdx,luischavez/libgdx,luischavez/libgdx,saqsun/libgdx,petugez/libgdx,andyvand/libgdx,thepullman/libgdx,xranby/libgdx,Zonglin-Li6565/libgdx,andyvand/libgdx,UnluckyNinja/libgdx,FyiurAmron/libgdx,ttencate/libgdx,MovingBlocks/libgdx,realitix/libgdx,toa5/libgdx,JDReutt/libgdx,designcrumble/libgdx,thepullman/libgdx,bsmr-java/libgdx,haedri/libgdx-1,EsikAntony/libgdx,tommycli/libgdx,realitix/libgdx,jasonwee/libgdx,yangweigbh/libgdx,nrallakis/libgdx,stickyd/libgdx,ricardorigodon/libgdx,309746069/libgdx,collinsmith/libgdx,UnluckyNinja/libgdx,Xhanim/libgdx,tell10glu/libgdx,lordjone/libgdx,bladecoder/libgdx,designcrumble/libgdx,josephknight/libgdx,saltares/libgdx,jsjolund/libgdx,revo09/libgdx,jasonwee/libgdx,MetSystem/libgdx,toa5/libgdx,KrisLee/libgdx,Heart2009/libgdx,luischavez/libgdx,GreenLightning/libgdx,junkdog/libgdx,xpenatan/libgdx-LWJGL3,kzganesan/libgdx,codepoke/libgdx,flaiker/libgdx,ricardorigodon/libgdx,curtiszimmerman/libgdx,billgame/libgdx,fwolff/libgdx,xoppa/libgdx,ztv/libgdx,katiepino/libgdx,luischavez/libgdx,ThiagoGarciaAlves/libgdx,toloudis/libgdx,tommyettinger/libgdx,youprofit/libgdx,codepoke/libgdx,tell10glu/libgdx,alireza-hosseini/libgdx,sjosegarcia/libgdx,GreenLightning/libgdx,gdos/libgdx,Deftwun/libgdx,fiesensee/libgdx,jberberick/libgdx,alireza-hosseini/libgdx,NathanSweet/libgdx,nrallakis/libgdx,kagehak/libgdx,sarkanyi/libgdx,nelsonsilva/libgdx,del-sol/libgdx,sarkanyi/libgdx,czyzby/libgdx,Gliby/libgdx,Thotep/libgdx,nelsonsilva/libgdx,tommycli/libgdx,ttencate/libgdx,jasonwee/libgdx,MadcowD/libgdx,bgroenks96/libgdx,katiepino/libgdx,KrisLee/libgdx,Zonglin-Li6565/libgdx,ttencate/libgdx,MikkelTAndersen/libgdx,BlueRiverInteractive/libgdx,saqsun/libgdx,anserran/libgdx,Gliby/libgdx,flaiker/libgdx,PedroRomanoBarbosa/libgdx,kotcrab/libgdx,shiweihappy/libgdx,BlueRiverInteractive/libgdx,realitix/libgdx,MadcowD/libgdx,jberberick/libgdx,Deftwun/libgdx,srwonka/libGdx,collinsmith/libgdx,xpenatan/libgdx-LWJGL3,curtiszimmerman/libgdx,srwonka/libGdx,GreenLightning/libgdx,PedroRomanoBarbosa/libgdx,ztv/libgdx,SidneyXu/libgdx,shiweihappy/libgdx,fiesensee/libgdx,ninoalma/libgdx,samskivert/libgdx,realitix/libgdx,del-sol/libgdx,xoppa/libgdx,TheAks999/libgdx,JDReutt/libgdx,bladecoder/libgdx,ryoenji/libgdx,bsmr-java/libgdx,libgdx/libgdx,djom20/libgdx,Thotep/libgdx,basherone/libgdxcn,antag99/libgdx,saltares/libgdx,bladecoder/libgdx,NathanSweet/libgdx,MetSystem/libgdx,gf11speed/libgdx,MetSystem/libgdx,saltares/libgdx,Deftwun/libgdx,Zomby2D/libgdx,mumer92/libgdx,FredGithub/libgdx,ya7lelkom/libgdx,Heart2009/libgdx,petugez/libgdx,antag99/libgdx,kagehak/libgdx,Arcnor/libgdx,Gliby/libgdx,mumer92/libgdx,UnluckyNinja/libgdx,billgame/libgdx,shiweihappy/libgdx,ricardorigodon/libgdx,bsmr-java/libgdx,bsmr-java/libgdx,titovmaxim/libgdx,Badazdz/libgdx,ricardorigodon/libgdx,MovingBlocks/libgdx,sjosegarcia/libgdx,sjosegarcia/libgdx,EsikAntony/libgdx,anserran/libgdx,EsikAntony/libgdx,MikkelTAndersen/libgdx,Senth/libgdx,ryoenji/libgdx,nrallakis/libgdx,srwonka/libGdx,toloudis/libgdx,snovak/libgdx,stinsonga/libgdx,Dzamir/libgdx,Badazdz/libgdx,PedroRomanoBarbosa/libgdx,lordjone/libgdx,noelsison2/libgdx,MovingBlocks/libgdx,FredGithub/libgdx,revo09/libgdx,UnluckyNinja/libgdx,zommuter/libgdx,curtiszimmerman/libgdx,kotcrab/libgdx,jsjolund/libgdx,nave966/libgdx,Senth/libgdx,samskivert/libgdx,yangweigbh/libgdx,FyiurAmron/libgdx,stickyd/libgdx,Heart2009/libgdx,fiesensee/libgdx,youprofit/libgdx,309746069/libgdx,kotcrab/libgdx,MetSystem/libgdx,nave966/libgdx,Dzamir/libgdx,ttencate/libgdx,bgroenks96/libgdx,toloudis/libgdx,noelsison2/libgdx,junkdog/libgdx,azakhary/libgdx,nave966/libgdx,gf11speed/libgdx,thepullman/libgdx,noelsison2/libgdx,kzganesan/libgdx,BlueRiverInteractive/libgdx,firefly2442/libgdx,kzganesan/libgdx,xoppa/libgdx,TheAks999/libgdx,1yvT0s/libgdx,xranby/libgdx,thepullman/libgdx,FredGithub/libgdx,katiepino/libgdx,cypherdare/libgdx,Zonglin-Li6565/libgdx,ttencate/libgdx,titovmaxim/libgdx,zommuter/libgdx,ninoalma/libgdx,ricardorigodon/libgdx,mumer92/libgdx,billgame/libgdx,xranby/libgdx,BlueRiverInteractive/libgdx,tommyettinger/libgdx,josephknight/libgdx,xranby/libgdx,snovak/libgdx,titovmaxim/libgdx,katiepino/libgdx,del-sol/libgdx,zhimaijoy/libgdx,Zonglin-Li6565/libgdx,Wisienkas/libgdx,gf11speed/libgdx,Deftwun/libgdx,JFixby/libgdx,jberberick/libgdx,junkdog/libgdx,js78/libgdx,davebaol/libgdx,del-sol/libgdx,tell10glu/libgdx,bsmr-java/libgdx,haedri/libgdx-1,zhimaijoy/libgdx,shiweihappy/libgdx,ya7lelkom/libgdx,mumer92/libgdx,ThiagoGarciaAlves/libgdx,jsjolund/libgdx,FredGithub/libgdx,toloudis/libgdx,billgame/libgdx,nrallakis/libgdx,fiesensee/libgdx,copystudy/libgdx,PedroRomanoBarbosa/libgdx,FyiurAmron/libgdx,anserran/libgdx,luischavez/libgdx,kotcrab/libgdx,anserran/libgdx,fwolff/libgdx,josephknight/libgdx,kzganesan/libgdx,nudelchef/libgdx,xoppa/libgdx,Gliby/libgdx,josephknight/libgdx,mumer92/libgdx,thepullman/libgdx,xranby/libgdx,stickyd/libgdx,sjosegarcia/libgdx,curtiszimmerman/libgdx,KrisLee/libgdx,MetSystem/libgdx,revo09/libgdx,yangweigbh/libgdx,sarkanyi/libgdx,saqsun/libgdx,jberberick/libgdx,ThiagoGarciaAlves/libgdx,yangweigbh/libgdx,js78/libgdx,js78/libgdx,snovak/libgdx,JFixby/libgdx,cypherdare/libgdx,bsmr-java/libgdx,samskivert/libgdx,Badazdz/libgdx,cypherdare/libgdx,Badazdz/libgdx,gouessej/libgdx,alex-dorokhov/libgdx,junkdog/libgdx,Zonglin-Li6565/libgdx,jberberick/libgdx,Wisienkas/libgdx,GreenLightning/libgdx,sinistersnare/libgdx,bgroenks96/libgdx,curtiszimmerman/libgdx,Senth/libgdx,js78/libgdx,basherone/libgdxcn,designcrumble/libgdx,jberberick/libgdx,ya7lelkom/libgdx,alireza-hosseini/libgdx,ztv/libgdx,Wisienkas/libgdx,MikkelTAndersen/libgdx,js78/libgdx,saltares/libgdx,fwolff/libgdx,fiesensee/libgdx,azakhary/libgdx,fiesensee/libgdx,saqsun/libgdx,bsmr-java/libgdx,hyvas/libgdx,ztv/libgdx,alireza-hosseini/libgdx,snovak/libgdx,ninoalma/libgdx,xpenatan/libgdx-LWJGL3,snovak/libgdx,luischavez/libgdx,MadcowD/libgdx,bsmr-java/libgdx,czyzby/libgdx,shiweihappy/libgdx,gdos/libgdx,nudelchef/libgdx,katiepino/libgdx,czyzby/libgdx,MikkelTAndersen/libgdx,andyvand/libgdx,MetSystem/libgdx,andyvand/libgdx,basherone/libgdxcn,tell10glu/libgdx,azakhary/libgdx,designcrumble/libgdx,xoppa/libgdx,gouessej/libgdx,thepullman/libgdx,Heart2009/libgdx,nooone/libgdx,curtiszimmerman/libgdx,Thotep/libgdx,toa5/libgdx,Xhanim/libgdx,nave966/libgdx,Thotep/libgdx,saqsun/libgdx,snovak/libgdx,Dzamir/libgdx,jsjolund/libgdx,EsikAntony/libgdx,bladecoder/libgdx,haedri/libgdx-1,jsjolund/libgdx,MovingBlocks/libgdx,MetSystem/libgdx,realitix/libgdx,shiweihappy/libgdx,davebaol/libgdx,designcrumble/libgdx,TheAks999/libgdx,ryoenji/libgdx,josephknight/libgdx,stickyd/libgdx,bladecoder/libgdx,antag99/libgdx,stinsonga/libgdx,shiweihappy/libgdx,xoppa/libgdx,1yvT0s/libgdx,nave966/libgdx,nudelchef/libgdx,309746069/libgdx,collinsmith/libgdx,bgroenks96/libgdx,xpenatan/libgdx-LWJGL3,yangweigbh/libgdx,MikkelTAndersen/libgdx,lordjone/libgdx,PedroRomanoBarbosa/libgdx,SidneyXu/libgdx,revo09/libgdx,srwonka/libGdx,kotcrab/libgdx,Deftwun/libgdx,haedri/libgdx-1,azakhary/libgdx,Dzamir/libgdx,ztv/libgdx,xpenatan/libgdx-LWJGL3,jasonwee/libgdx,UnluckyNinja/libgdx,xranby/libgdx,jberberick/libgdx,ninoalma/libgdx,JFixby/libgdx,MovingBlocks/libgdx,revo09/libgdx,copystudy/libgdx,bgroenks96/libgdx,gdos/libgdx,JFixby/libgdx,FyiurAmron/libgdx,firefly2442/libgdx,jasonwee/libgdx,samskivert/libgdx,stickyd/libgdx,cypherdare/libgdx,Badazdz/libgdx,saltares/libgdx,ninoalma/libgdx,Zonglin-Li6565/libgdx,zommuter/libgdx,Gliby/libgdx,designcrumble/libgdx,djom20/libgdx,fiesensee/libgdx,petugez/libgdx,Zonglin-Li6565/libgdx,toa5/libgdx,NathanSweet/libgdx,BlueRiverInteractive/libgdx,KrisLee/libgdx,petugez/libgdx,zhimaijoy/libgdx,antag99/libgdx,firefly2442/libgdx,del-sol/libgdx,jsjolund/libgdx,saltares/libgdx,Zonglin-Li6565/libgdx,tell10glu/libgdx,Thotep/libgdx,Badazdz/libgdx,samskivert/libgdx,EsikAntony/libgdx,ThiagoGarciaAlves/libgdx,309746069/libgdx,nudelchef/libgdx,jberberick/libgdx,djom20/libgdx,nooone/libgdx,GreenLightning/libgdx,nelsonsilva/libgdx,tommycli/libgdx,Deftwun/libgdx,codepoke/libgdx,NathanSweet/libgdx,sjosegarcia/libgdx,zhimaijoy/libgdx,stickyd/libgdx,kagehak/libgdx,kzganesan/libgdx,GreenLightning/libgdx,hyvas/libgdx,JFixby/libgdx,fwolff/libgdx,PedroRomanoBarbosa/libgdx,flaiker/libgdx,Xhanim/libgdx,czyzby/libgdx,noelsison2/libgdx,309746069/libgdx,Wisienkas/libgdx,djom20/libgdx,tommyettinger/libgdx,GreenLightning/libgdx,Arcnor/libgdx,fwolff/libgdx,ttencate/libgdx,FredGithub/libgdx,lordjone/libgdx,Senth/libgdx,ninoalma/libgdx,luischavez/libgdx,gouessej/libgdx,snovak/libgdx,EsikAntony/libgdx,gouessej/libgdx,Thotep/libgdx,Dzamir/libgdx,thepullman/libgdx,stickyd/libgdx,billgame/libgdx,libgdx/libgdx,309746069/libgdx,Thotep/libgdx,SidneyXu/libgdx,copystudy/libgdx,zhimaijoy/libgdx,nudelchef/libgdx,JFixby/libgdx,JFixby/libgdx,gdos/libgdx,Zomby2D/libgdx,zhimaijoy/libgdx,gdos/libgdx,yangweigbh/libgdx,luischavez/libgdx,sarkanyi/libgdx,ztv/libgdx,azakhary/libgdx,thepullman/libgdx,kotcrab/libgdx,Xhanim/libgdx,youprofit/libgdx,andyvand/libgdx,czyzby/libgdx,tommycli/libgdx,nudelchef/libgdx,stickyd/libgdx,sjosegarcia/libgdx,samskivert/libgdx,czyzby/libgdx,sinistersnare/libgdx,SidneyXu/libgdx,xpenatan/libgdx-LWJGL3,zommuter/libgdx,Senth/libgdx,FyiurAmron/libgdx,Senth/libgdx,UnluckyNinja/libgdx,gdos/libgdx,hyvas/libgdx,nooone/libgdx,jasonwee/libgdx,stinsonga/libgdx,lordjone/libgdx,yangweigbh/libgdx,TheAks999/libgdx,realitix/libgdx,jasonwee/libgdx,Xhanim/libgdx,Wisienkas/libgdx,jasonwee/libgdx,copystudy/libgdx,JDReutt/libgdx,JDReutt/libgdx,toloudis/libgdx,codepoke/libgdx,ThiagoGarciaAlves/libgdx,flaiker/libgdx,zommuter/libgdx,MadcowD/libgdx,EsikAntony/libgdx,MadcowD/libgdx,realitix/libgdx,firefly2442/libgdx,nave966/libgdx,zommuter/libgdx,FyiurAmron/libgdx,kagehak/libgdx,FredGithub/libgdx,sarkanyi/libgdx,libgdx/libgdx,youprofit/libgdx,EsikAntony/libgdx,tell10glu/libgdx,davebaol/libgdx,firefly2442/libgdx,Deftwun/libgdx,Arcnor/libgdx,nelsonsilva/libgdx,xpenatan/libgdx-LWJGL3,TheAks999/libgdx,saltares/libgdx,zommuter/libgdx,billgame/libgdx,saqsun/libgdx,kotcrab/libgdx,titovmaxim/libgdx,collinsmith/libgdx,Xhanim/libgdx,tommyettinger/libgdx,katiepino/libgdx,1yvT0s/libgdx,gf11speed/libgdx,Dzamir/libgdx,KrisLee/libgdx,saqsun/libgdx,MovingBlocks/libgdx,nelsonsilva/libgdx,collinsmith/libgdx,nudelchef/libgdx,MikkelTAndersen/libgdx,anserran/libgdx,FredGithub/libgdx
package com.badlogic.gdx.graphics.g3d.utils; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.model.MeshPart; import com.badlogic.gdx.graphics.g3d.utils.MeshPartBuilder.VertexInfo; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.FloatArray; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.Poolable; import com.badlogic.gdx.utils.ShortArray; /** Class to construct a mesh, optionally splitting it into one or more mesh parts. * Before you can call any other method you must call {@link #begin(VertexAttributes)} or {@link #begin(VertexAttributes, int)}. * To use mesh parts you must call {@link #part(String, int)} before you start building the part. * The MeshPart itself is only valid after the call to {@link #end()}. * @author Xoppa */ public class MeshBuilder implements MeshPartBuilder { private final VertexInfo vertTmp1 = new VertexInfo(); private final VertexInfo vertTmp2 = new VertexInfo(); private final VertexInfo vertTmp3 = new VertexInfo(); private final VertexInfo vertTmp4 = new VertexInfo(); private final VertexInfo vertTmp5 = new VertexInfo(); private final VertexInfo vertTmp6 = new VertexInfo(); private final VertexInfo vertTmp7 = new VertexInfo(); private final VertexInfo vertTmp8 = new VertexInfo(); private final Matrix4 matTmp1 = new Matrix4(); private final Vector3 tempV1 = new Vector3(); private final Vector3 tempV2 = new Vector3(); private final Vector3 tempV3 = new Vector3(); private final Vector3 tempV4 = new Vector3(); private final Vector3 tempV5 = new Vector3(); private final Vector3 tempV6 = new Vector3(); private final Vector3 tempV7 = new Vector3(); private final Vector3 tempV8 = new Vector3(); /** The vertex attributes of the resulting mesh */ private VertexAttributes attributes; /** The vertices to construct, no size checking is done */ private FloatArray vertices = new FloatArray(); /** The indices to construct, no size checking is done */ private ShortArray indices = new ShortArray(); /** The size (in number of floats) of each vertex */ private int stride; /** The current vertex index, used for indexing */ private short vindex; /** The offset in the indices array when begin() was called, used to define a meshpart. */ private int istart; /** The offset within an vertex to position */ private int posOffset; /** The size (in number of floats) of the position attribute */ private int posSize; /** The offset within an vertex to normal, or -1 if not available */ private int norOffset; /** The offset within an vertex to color, or -1 if not available */ private int colOffset; /** The size (in number of floats) of the color attribute */ private int colSize; /** The offset within an vertex to packed color, or -1 if not available */ private int cpOffset; /** The offset within an vertex to texture coordinates, or -1 if not available */ private int uvOffset; /** The meshpart currently being created */ private MeshPart part; /** The parts created between begin and end */ private Array<MeshPart> parts = new Array<MeshPart>(); /** The color used if no vertex color is specified. */ private final Color color = new Color(); /** Whether to apply the default color. */ private boolean colorSet; /** The current primitiveType */ private int primitiveType; // FIXME makes this configurable private float uMin = 0, uMax = 1, vMin = 0, vMax = 1; private float[] vertex; /** @param usage bitwise mask of the {@link com.badlogic.gdx.graphics.VertexAttributes.Usage}, * only Position, Color, Normal and TextureCoordinates is supported. */ public static VertexAttributes createAttributes(long usage) { final Array<VertexAttribute> attrs = new Array<VertexAttribute>(); if ((usage & Usage.Position) == Usage.Position) attrs.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); if ((usage & Usage.Color) == Usage.Color) attrs.add(new VertexAttribute(Usage.Color, 4, ShaderProgram.COLOR_ATTRIBUTE)); if ((usage & Usage.Normal) == Usage.Normal) attrs.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); if ((usage & Usage.TextureCoordinates) == Usage.TextureCoordinates) attrs.add(new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE+"0")); final VertexAttribute attributes[] = new VertexAttribute[attrs.size]; for (int i = 0; i < attributes.length; i++) attributes[i] = attrs.get(i); return new VertexAttributes(attributes); } /** Begin building a mesh. Call {@link #part(String, int)} to start a {@link MeshPart}. * @param attributes bitwise mask of the {@link com.badlogic.gdx.graphics.VertexAttributes.Usage}, * only Position, Color, Normal and TextureCoordinates is supported. */ public void begin(final long attributes) { begin(createAttributes(attributes), 0); } /** Begin building a mesh. Call {@link #part(String, int)} to start a {@link MeshPart}. */ public void begin(final VertexAttributes attributes) { begin(attributes, 0); } /** Begin building a mesh. * @param attributes bitwise mask of the {@link com.badlogic.gdx.graphics.VertexAttributes.Usage}, * only Position, Color, Normal and TextureCoordinates is supported. */ public void begin(final long attributes, int primitiveType) { begin(createAttributes(attributes), primitiveType); } /** Begin building a mesh */ public void begin(final VertexAttributes attributes, int primitiveType) { if (this.attributes != null) throw new RuntimeException("Call end() first"); this.attributes = attributes; this.vertices.clear(); this.indices.clear(); this.parts.clear(); this.vindex = 0; this.istart = 0; this.part = null; this.stride = attributes.vertexSize / 4; this.vertex = new float[stride]; VertexAttribute a = attributes.findByUsage(Usage.Position); if (a == null) throw new GdxRuntimeException("Cannot build mesh without position attribute"); posOffset = a.offset / 4; posSize = a.numComponents; a = attributes.findByUsage(Usage.Normal); norOffset = a == null ? -1 : a.offset / 4; a = attributes.findByUsage(Usage.Color); colOffset = a == null ? -1 : a.offset / 4; colSize = a == null ? 0 : a.numComponents; a = attributes.findByUsage(Usage.ColorPacked); cpOffset = a == null ? -1 : a.offset / 4; a = attributes.findByUsage(Usage.TextureCoordinates); uvOffset = a == null ? -1 : a.offset / 4; setColor(null); this.primitiveType = primitiveType; } private void endpart() { if (part != null) { part.indexOffset = istart; part.numVertices = indices.size - istart; istart = indices.size; part = null; } } /** Starts a new MeshPart. The mesh part is not usable until end() is called */ public MeshPart part(final String id, int primitiveType) { if (this.attributes == null) throw new RuntimeException("Call begin() first"); endpart(); part = new MeshPart(); part.id = id; this.primitiveType = part.primitiveType = primitiveType; parts.add(part); setColor(null); return part; } /** End building the mesh and returns the mesh */ public Mesh end() { if (this.attributes == null) throw new RuntimeException("Call begin() first"); endpart(); final Mesh mesh = new Mesh(true, vertices.size, indices.size, attributes); mesh.setVertices(vertices.items, 0, vertices.size); mesh.setIndices(indices.items, 0, indices.size); for (MeshPart p : parts) p.mesh = mesh; parts.clear(); attributes = null; vertices.clear(); indices.clear(); return mesh; } @Override public VertexAttributes getAttributes() { return attributes; } @Override public MeshPart getMeshPart() { return part; } private final static Pool<Vector3> vectorPool = new Pool<Vector3>() { @Override protected Vector3 newObject () { return new Vector3(); } }; private final static Array<Vector3> vectorArray = new Array<Vector3>(); private Vector3 tmp(float x, float y, float z) { final Vector3 result = vectorPool.obtain().set(x, y, z); vectorArray.add(result); return result; } private Vector3 tmp(Vector3 copyFrom) { return tmp(copyFrom.x, copyFrom.y, copyFrom.z); } private void cleanup() { vectorPool.freeAll(vectorArray); vectorArray.clear(); } @Override public void setColor(float r, float g, float b, float a) { color.set(r, g, b, a); colorSet = true; } @Override public void setColor(final Color color) { if ((colorSet = color != null)==true) this.color.set(color); } @Override public void setUVRange(float u1, float v1, float u2, float v2) { uMin = u1; vMin = v1; uMax = u2; vMax = v2; } /** Increases the size of the backing vertices array to accommodate the specified number of additional vertices. * Useful before adding many vertices to avoid multiple backing array resizes. * @param numVertices The number of vertices you are about to add */ public void ensureVertices(int numVertices) { vertices.ensureCapacity(vertex.length * numVertices); } /** Increases the size of the backing indices array to accommodate the specified number of additional indices. * Useful before adding many indices to avoid multiple backing array resizes. * @param numIndices The number of indices you are about to add */ public void ensureIndices(int numIndices) { indices.ensureCapacity(numIndices); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and indices. Useful before adding many vertices and indices to avoid multiple backing array resizes. * @param numVertices The number of vertices you are about to add * @param numIndices The number of indices you are about to add */ public void ensureCapacity(int numVertices, int numIndices) { ensureVertices(numVertices); ensureIndices(numIndices); } /** Increases the size of the backing indices array to accommodate the specified number of additional triangles. * Useful before adding many triangles to avoid multiple backing array resizes. * @param numTriangles The number of triangles you are about to add */ public void ensureTriangleIndices(int numTriangles) { if (primitiveType == GL10.GL_LINES) ensureIndices(6 * numTriangles); else // GL_TRIANGLES || GL_POINTS ensureIndices(3 * numTriangles); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and triangles. Useful before adding many triangles to avoid multiple backing array resizes. * @param numVertices The number of vertices you are about to add * @param numTriangles The number of triangles you are about to add */ public void ensureTriangles(int numVertices, int numTriangles) { ensureVertices(numVertices); ensureTriangleIndices(numTriangles); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and triangles. Useful before adding many triangles to avoid multiple backing array resizes. * Assumes each triangles adds 3 vertices. * @param numTriangles The number of triangles you are about to add */ public void ensureTriangles(int numTriangles) { ensureTriangles(3 * numTriangles, numTriangles); } /** Increases the size of the backing indices array to accommodate the specified number of additional rectangles. * Useful before adding many rectangles to avoid multiple backing array resizes. * @param numRectangles The number of rectangles you are about to add */ public void ensureRectangleIndices(int numRectangles) { if (primitiveType == GL10.GL_POINTS) ensureIndices(4 * numRectangles); else if (primitiveType == GL10.GL_LINES) ensureIndices(8 * numRectangles); else // GL_TRIANGLES ensureIndices(6 * numRectangles); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and rectangles. Useful before adding many rectangles to avoid multiple backing array resizes. * @param numVertices The number of vertices you are about to add * @param numRectangles The number of rectangles you are about to add */ public void ensureRectangles(int numVertices, int numRectangles) { ensureVertices(numVertices); ensureRectangleIndices(numRectangles); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and rectangles. Useful before adding many rectangles to avoid multiple backing array resizes. * Assumes each rectangles adds 4 vertices * @param numRectangles The number of rectangles you are about to add */ public void ensureRectangles(int numRectangles) { ensureRectangles(4 * numRectangles, numRectangles); } @Override public short vertex(Vector3 pos, Vector3 nor, Color col, Vector2 uv) { if (vindex >= Short.MAX_VALUE) throw new GdxRuntimeException("Too many vertices used"); if (col == null && colorSet) col = color; if (pos != null) { vertex[posOffset ] = pos.x; if (posSize > 1) vertex[posOffset+1] = pos.y; if (posSize > 2) vertex[posOffset+2] = pos.z; } if (nor != null && norOffset >= 0) { vertex[norOffset ] = nor.x; vertex[norOffset+1] = nor.y; vertex[norOffset+2] = nor.z; } if (col != null) { if (colOffset >= 0) { vertex[colOffset ] = col.r; vertex[colOffset+1] = col.g; vertex[colOffset+2] = col.b; if (colSize > 3) vertex[colOffset+3] = col.a; } else if (cpOffset > 0) vertex[cpOffset] = col.toFloatBits(); // FIXME cache packed color? } if (uv != null && uvOffset >= 0) { vertex[uvOffset ] = uv.x; vertex[uvOffset+1] = uv.y; } vertices.addAll(vertex); return (short)(vindex++); } @Override public short lastIndex() { return (short)(vindex-1); } @Override public short vertex(final float... values) { vertices.addAll(values); vindex += values.length / stride; return (short)(vindex-1); } @Override public short vertex(final VertexInfo info) { return vertex(info.hasPosition ? info.position : null, info.hasNormal ? info.normal : null, info.hasColor ? info.color : null, info.hasUV ? info.uv : null); } @Override public void index(final short value) { indices.add(value); } @Override public void index(final short value1, final short value2) { ensureIndices(2); indices.add(value1); indices.add(value2); } @Override public void index(final short value1, final short value2, final short value3) { ensureIndices(3); indices.add(value1); indices.add(value2); indices.add(value3); } @Override public void index(final short value1, final short value2, final short value3, final short value4) { ensureIndices(4); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); } @Override public void index(short value1, short value2, short value3, short value4, short value5, short value6) { ensureIndices(6); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); indices.add(value5); indices.add(value6); } @Override public void index(short value1, short value2, short value3, short value4, short value5, short value6, short value7, short value8) { ensureIndices(8); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); indices.add(value5); indices.add(value6); indices.add(value7); indices.add(value8); } @Override public void line(short index1, short index2) { if (primitiveType != GL10.GL_LINES) throw new GdxRuntimeException("Incorrect primitive type"); index(index1, index2); } @Override public void line(VertexInfo p1, VertexInfo p2) { ensureVertices(2); line(vertex(p1), vertex(p2)); } @Override public void line(Vector3 p1, Vector3 p2) { line(vertTmp1.set(p1, null, null, null), vertTmp2.set(p2, null, null, null)); } @Override public void line(float x1, float y1, float z1, float x2, float y2, float z2) { line(vertTmp1.set(null, null, null, null).setPos(x1, y1, z1), vertTmp2.set(null, null, null, null).setPos(x2, y2, z2)); } @Override public void line(Vector3 p1, Color c1, Vector3 p2, Color c2) { line(vertTmp1.set(p1, null, c1, null), vertTmp2.set(p2, null, c2, null)); } @Override public void triangle(short index1, short index2, short index3) { if (primitiveType == GL10.GL_TRIANGLES || primitiveType == GL10.GL_POINTS) { index(index1, index2, index3); } else if (primitiveType == GL10.GL_LINES) { index(index1, index2, index2, index3, index3, index1); } else throw new GdxRuntimeException("Incorrect primitive type"); } @Override public void triangle(VertexInfo p1, VertexInfo p2, VertexInfo p3) { ensureVertices(3); triangle(vertex(p1), vertex(p2), vertex(p3)); } @Override public void triangle(Vector3 p1, Vector3 p2, Vector3 p3) { triangle(vertTmp1.set(p1, null, null, null), vertTmp2.set(p2, null, null, null), vertTmp3.set(p3, null, null, null)); } @Override public void triangle(Vector3 p1, Color c1, Vector3 p2, Color c2, Vector3 p3, Color c3) { triangle(vertTmp1.set(p1, null, c1, null), vertTmp2.set(p2, null, c2, null), vertTmp3.set(p3, null, c3, null)); } @Override public void rect(short corner00, short corner10, short corner11, short corner01) { if (primitiveType == GL10.GL_TRIANGLES) { index(corner00, corner10, corner11, corner11, corner01, corner00); } else if (primitiveType == GL10.GL_LINES) { index(corner00, corner10, corner10, corner11, corner11, corner01, corner01, corner00); } else if (primitiveType == GL10.GL_POINTS) { index(corner00, corner10, corner11, corner01); } else throw new GdxRuntimeException("Incorrect primitive type"); } @Override public void rect(VertexInfo corner00, VertexInfo corner10, VertexInfo corner11, VertexInfo corner01) { ensureVertices(4); rect(vertex(corner00), vertex(corner10), vertex(corner11), vertex(corner01)); } @Override public void rect(Vector3 corner00, Vector3 corner10, Vector3 corner11, Vector3 corner01, Vector3 normal) { rect(vertTmp1.set(corner00, normal, null, null).setUV(uMin,vMin), vertTmp2.set(corner10, normal, null, null).setUV(uMax,vMin), vertTmp3.set(corner11, normal, null, null).setUV(uMax,vMax), vertTmp4.set(corner01, normal, null, null).setUV(uMin,vMax)); } @Override public void rect(float x00, float y00, float z00, float x10, float y10, float z10, float x11, float y11, float z11, float x01, float y01, float z01, float normalX, float normalY, float normalZ) { rect(vertTmp1.set(null, null, null, null).setPos(x00,y00,z00).setNor(normalX,normalY,normalZ).setUV(uMin,vMin), vertTmp2.set(null, null, null, null).setPos(x10,y10,z10).setNor(normalX,normalY,normalZ).setUV(uMax,vMin), vertTmp3.set(null, null, null, null).setPos(x11,y11,z11).setNor(normalX,normalY,normalZ).setUV(uMax,vMax), vertTmp4.set(null, null, null, null).setPos(x01,y01,z01).setNor(normalX,normalY,normalZ).setUV(uMin,vMax)); } @Override public void patch(VertexInfo corner00, VertexInfo corner10, VertexInfo corner11, VertexInfo corner01, int divisionsU, int divisionsV) { ensureRectangles((divisionsV + 1) * (divisionsU + 1), divisionsV * divisionsU); for (int u = 0; u <= divisionsU; u++) { final float alphaU = (float)u / (float)divisionsU; vertTmp5.set(corner00).lerp(corner10, alphaU); vertTmp6.set(corner01).lerp(corner11, alphaU); for (int v = 0; v <= divisionsV; v++) { final short idx = vertex(vertTmp7.set(vertTmp5).lerp(vertTmp6, (float)v / (float)divisionsV)); if (u > 0 && v > 0) rect((short)(idx-divisionsV-2), (short)(idx-1), idx, (short)(idx-divisionsV-1)); } } } @Override public void patch(Vector3 corner00, Vector3 corner10, Vector3 corner11, Vector3 corner01, Vector3 normal, int divisionsU, int divisionsV) { patch(vertTmp1.set(corner00, normal, null, null).setUV(uMin,vMin), vertTmp2.set(corner10, normal, null, null).setUV(uMax,vMin), vertTmp3.set(corner11, normal, null, null).setUV(uMax,vMax), vertTmp4.set(corner01, normal, null, null).setUV(uMin,vMax), divisionsU, divisionsV); } public void patch(float x00, float y00, float z00, float x10, float y10, float z10, float x11, float y11, float z11, float x01, float y01, float z01, float normalX, float normalY, float normalZ, int divisionsU, int divisionsV) { patch(vertTmp1.set(null).setPos(x00, y00, z00).setNor(normalX, normalY, normalZ).setUV(uMin,vMin), vertTmp2.set(null).setPos(x10, y10, z10).setNor(normalX, normalY, normalZ).setUV(uMax,vMin), vertTmp3.set(null).setPos(x11, y11, z11).setNor(normalX, normalY, normalZ).setUV(uMax,vMax), vertTmp4.set(null).setPos(x01, y01, z01).setNor(normalX, normalY, normalZ).setUV(uMin,vMax), divisionsU, divisionsV); } @Override public void box(VertexInfo corner000, VertexInfo corner010, VertexInfo corner100, VertexInfo corner110, VertexInfo corner001, VertexInfo corner011, VertexInfo corner101, VertexInfo corner111) { ensureVertices(8); final short i000 = vertex(corner000); final short i100 = vertex(corner100); final short i110 = vertex(corner110); final short i010 = vertex(corner010); final short i001 = vertex(corner001); final short i101 = vertex(corner101); final short i111 = vertex(corner111); final short i011 = vertex(corner011); if (primitiveType == GL10.GL_LINES) { ensureIndices(24); rect(i000, i100, i110, i010); rect(i101, i001, i011, i111); index(i000, i001, i010, i011, i110, i111, i100, i101); } else if (primitiveType != GL10.GL_POINTS) { ensureRectangleIndices(2); rect(i000, i100, i110, i010); rect(i101, i001, i011, i111); } else { // GL10.GL_TRIANGLES ensureRectangleIndices(6); rect(i000, i100, i110, i010); rect(i101, i001, i011, i111); rect(i000, i010, i011, i001); rect(i101, i111, i110, i100); rect(i101, i100, i000, i001); rect(i110, i111, i011, i010); } } @Override public void box(Vector3 corner000, Vector3 corner010, Vector3 corner100, Vector3 corner110, Vector3 corner001, Vector3 corner011, Vector3 corner101, Vector3 corner111) { if (norOffset < 0 && uvOffset < 0) { box(vertTmp1.set(corner000, null, null, null), vertTmp2.set(corner010, null, null, null), vertTmp3.set(corner100, null, null, null), vertTmp4.set(corner110, null, null, null), vertTmp5.set(corner001, null, null, null), vertTmp6.set(corner011, null, null, null), vertTmp7.set(corner101, null, null, null), vertTmp8.set(corner111, null, null, null)); } else { ensureRectangles(6); Vector3 nor = tempV1.set(corner000).lerp(corner110, 0.5f).sub(tempV2.set(corner001).lerp(corner111, 0.5f)).nor(); rect(corner000, corner010, corner110, corner100, nor); rect(corner011, corner001, corner101, corner111, nor.scl(-1)); nor = tempV1.set(corner000).lerp(corner101, 0.5f).sub(tempV2.set(corner010).lerp(corner111, 0.5f)).nor(); rect(corner001, corner000, corner100, corner101, nor); rect(corner010, corner011, corner111, corner110, nor.scl(-1)); nor = tempV1.set(corner000).lerp(corner011, 0.5f).sub(tempV2.set(corner100).lerp(corner111, 0.5f)).nor(); rect(corner001, corner011, corner010, corner000, nor); rect(corner100, corner110, corner111, corner101, nor.scl(-1)); } } @Override public void box(Matrix4 transform) { box(tmp(-0.5f,-0.5f,-0.5f).mul(transform),tmp(-0.5f,0.5f,-0.5f).mul(transform),tmp(0.5f,-0.5f,-0.5f).mul(transform),tmp(0.5f,0.5f,-0.5f).mul(transform), tmp(-0.5f,-0.5f,0.5f).mul(transform),tmp(-0.5f,0.5f,0.5f).mul(transform),tmp(0.5f,-0.5f,0.5f).mul(transform),tmp(0.5f,0.5f,0.5f).mul(transform)); cleanup(); } @Override public void box(float width, float height, float depth) { box(matTmp1.setToScaling(width, height, depth)); } @Override public void box(float x, float y, float z, float width, float height, float depth) { box(matTmp1.setToScaling(width, height, depth).trn(x, y, z)); } @Override public void circle(float width, float height, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, int divisions) { circle(width, height, centerX, centerY, centerZ, normalX, normalY, normalZ, divisions, 0, 360); } @Override public void circle(float width, float height, final Vector3 center, final Vector3 normal, int divisions) { circle(width, height, center.x, center.y, center.z, normal.x, normal.y, normal.z, divisions); } @Override public void circle(float width, float height, final Vector3 center, final Vector3 normal, final Vector3 tangent, final Vector3 binormal, int divisions) { circle(width, height, center.x, center.y, center.z, normal.x, normal.y, normal.z, tangent.x, tangent.y, tangent.z, binormal.x, binormal.y, binormal.z, divisions); } @Override public void circle(float width, float height, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, int divisions) { circle(width, height, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ, divisions, 0, 360); } @Override public void circle(float width, float height, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, int divisions, float angleFrom, float angleTo) { tempV1.set(normalX, normalY, normalZ).crs(0, 0, 1); tempV2.set(normalX, normalY, normalZ).crs(0, 1, 0); if (tempV2.len2() > tempV1.len2()) tempV1.set(tempV2); tempV2.set(tempV1.nor()).crs(normalX, normalY, normalZ).nor(); circle(width, height, centerX, centerY, centerZ, normalX, normalY, normalZ, tempV1.x, tempV1.y, tempV1.z, tempV2.x, tempV2.y, tempV2.z, divisions, angleFrom, angleTo); } @Override public void circle(float width, float height, final Vector3 center, final Vector3 normal, int divisions, float angleFrom, float angleTo) { circle(width, height, center.x, center.y, center.z, normal.x, normal.y, normal.z, divisions, angleFrom, angleTo); } @Override public void circle(float width, float height, final Vector3 center, final Vector3 normal, final Vector3 tangent, final Vector3 binormal, int divisions, float angleFrom, float angleTo) { circle(width, height, center.x, center.y, center.z, normal.x, normal.y, normal.z, tangent.x, tangent.y, tangent.z, binormal.x, binormal.y, binormal.z, divisions, angleFrom, angleTo); } @Override public void circle(float width, float height, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, int divisions, float angleFrom, float angleTo) { ellipse(width, height, 0, 0, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ, divisions, angleFrom, angleTo); } @Override public void ellipse(float width, float height, float innerWidth, float innerHeight, Vector3 center, Vector3 normal, int divisions) { ellipse(width, height, innerWidth, innerHeight, center.x, center.y, center.z, normal.x, normal.y, normal.z, divisions, 0, 360); } @Override public void ellipse(float width, float height, float innerWidth, float innerHeight, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, int divisions) { ellipse(width, height, innerWidth, innerHeight, centerX, centerY, centerZ, normalX, normalY, normalZ, divisions, 0, 360); } @Override public void ellipse(float width, float height, float innerWidth, float innerHeight, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, int divisions, float angleFrom, float angleTo) { tempV1.set(normalX, normalY, normalZ).crs(0, 0, 1); tempV2.set(normalX, normalY, normalZ).crs(0, 1, 0); if (tempV2.len2() > tempV1.len2()) tempV1.set(tempV2); tempV2.set(tempV1.nor()).crs(normalX, normalY, normalZ).nor(); ellipse(width, height, innerWidth, innerHeight, centerX, centerY, centerZ, normalX, normalY, normalZ, tempV1.x, tempV1.y, tempV1.z, tempV2.x, tempV2.y, tempV2.z, divisions, angleFrom, angleTo); } @Override public void ellipse(float width, float height, float innerWidth, float innerHeight, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, int divisions, float angleFrom, float angleTo) { if(innerWidth <= 0 || innerHeight <= 0) { ensureTriangles(divisions + 2, divisions); } else if (innerWidth == width && innerHeight == height){ ensureVertices(divisions + 1); ensureIndices(divisions + 1); if(primitiveType != GL10.GL_LINES) throw new GdxRuntimeException("Incorrect primitive type : expect GL_LINES because innerWidth == width && innerHeight == height"); } else { ensureRectangles((divisions + 1)*2, divisions + 1); } final float ao = MathUtils.degreesToRadians * angleFrom; final float step = (MathUtils.degreesToRadians * (angleTo - angleFrom)) / divisions; final Vector3 sxEx = tempV1.set(tangentX, tangentY, tangentZ).scl(width * 0.5f); final Vector3 syEx = tempV2.set(binormalX, binormalY, binormalZ).scl(height * 0.5f); final Vector3 sxIn = tempV3.set(tangentX, tangentY, tangentZ).scl(innerWidth * 0.5f); final Vector3 syIn = tempV4.set(binormalX, binormalY, binormalZ).scl(innerHeight * 0.5f); VertexInfo currIn = vertTmp3.set(null, null, null, null); currIn.hasUV = true; currIn.uv.set(.5f, .5f); currIn.hasPosition = currIn.hasNormal = true; currIn.position.set(centerX, centerY, centerZ); currIn.normal.set(normalX, normalY, normalZ); VertexInfo currEx = vertTmp4.set(null, null, null, null); currEx.hasUV = true; currEx.uv.set(.5f, .5f); currEx.hasPosition = currEx.hasNormal = true; currEx.position.set(centerX, centerY, centerZ); currEx.normal.set(normalX, normalY, normalZ); final short center = vertex(currEx); float angle = 0f; for (int i = 0; i <= divisions; i++) { angle = ao + step * i; final float x = MathUtils.cos(angle); final float y = MathUtils.sin(angle); currEx.position.set(centerX, centerY, centerZ).add(sxEx.x*x+syEx.x*y, sxEx.y*x+syEx.y*y, sxEx.z*x+syEx.z*y); currEx.uv.set(.5f + .5f * x, .5f + .5f * y); vertex(currEx); if(innerWidth <= 0 || innerHeight <= 0) { if (i != 0) triangle((short)(vindex - 1), (short)(vindex - 2), center); } else if (innerWidth == width && innerHeight == height){ if (i != 0) line((short)(vindex - 1), (short)(vindex - 2)); } else { currIn.position.set(centerX, centerY, centerZ).add(sxIn.x*x+syIn.x*y, sxIn.y*x+syIn.y*y, sxIn.z*x+syIn.z*y); currIn.uv.set(.5f + .5f * x, .5f + .5f * y); vertex(currIn); if( i != 0) rect((short)(vindex - 1), (short)(vindex - 2),(short)(vindex - 4), (short)(vindex - 3)); } } } @Override public void cylinder(float width, float height, float depth, int divisions) { cylinder(width, height, depth, divisions, 0, 360); } @Override public void cylinder(float width, float height, float depth, int divisions, float angleFrom, float angleTo) { cylinder(width, height, depth, divisions, angleFrom, angleTo, true); } /** Add a cylinder */ public void cylinder(float width, float height, float depth, int divisions, float angleFrom, float angleTo, boolean close) { // FIXME create better cylinder method (- axis on which to create the cylinder (matrix?)) final float hw = width * 0.5f; final float hh = height * 0.5f; final float hd = depth * 0.5f; final float ao = MathUtils.degreesToRadians * angleFrom; final float step = (MathUtils.degreesToRadians * (angleTo - angleFrom)) / divisions; final float us = 1f / divisions; float u = 0f; float angle = 0f; VertexInfo curr1 = vertTmp3.set(null, null, null, null); curr1.hasUV = curr1.hasPosition = curr1.hasNormal = true; VertexInfo curr2 = vertTmp4.set(null, null, null, null); curr2.hasUV = curr2.hasPosition = curr2.hasNormal = true; ensureRectangles(2 * (divisions + 1), divisions); for (int i = 0; i <= divisions; i++) { angle = ao + step * i; u = 1f - us * i; curr1.position.set(MathUtils.cos(angle) * hw, 0f, MathUtils.sin(angle) * hd); curr1.normal.set(curr1.position).nor(); curr1.position.y = -hh; curr1.uv.set(u, 1); curr2.position.set(curr1.position); curr2.normal.set(curr1.normal); curr2.position.y = hh; curr2.uv.set(u, 0); vertex(curr1); vertex(curr2); if (i != 0) rect((short)(vindex-3), (short)(vindex-1), (short)(vindex-2), (short)(vindex-4)); // FIXME don't duplicate lines and points } if (close) { circle(width, depth, 0, hh, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, divisions, angleFrom, angleTo); circle(width, depth, 0, -hh, 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, divisions, 180f-angleTo, 180f-angleFrom); } } @Override public void cone(float width, float height, float depth, int divisions) { cone(width, height, depth, divisions, 0, 360); } @Override public void cone(float width, float height, float depth, int divisions, float angleFrom, float angleTo) { // FIXME create better cylinder method (- axis on which to create the cone (matrix?)) ensureTriangles(divisions + 2, divisions); final float hw = width * 0.5f; final float hh = height * 0.5f; final float hd = depth * 0.5f; final float ao = MathUtils.degreesToRadians * angleFrom; final float step = (MathUtils.degreesToRadians * (angleTo - angleFrom)) / divisions; final float us = 1f / divisions; float u = 0f; float angle = 0f; VertexInfo curr1 = vertTmp3.set(null, null, null, null); curr1.hasUV = curr1.hasPosition = curr1.hasNormal = true; VertexInfo curr2 = vertTmp4.set(null, null, null, null).setPos(0,hh,0).setNor(0,1,0).setUV(0.5f, 0); final int base = vertex(curr2); for (int i = 0; i <= divisions; i++) { angle = ao + step * i; u = 1f - us * i; curr1.position.set(MathUtils.cos(angle) * hw, 0f, MathUtils.sin(angle) * hd); curr1.normal.set(curr1.position).nor(); curr1.position.y = -hh; curr1.uv.set(u, 1); vertex(curr1); if (i == 0) continue; triangle((short)base, (short)(vindex-1), (short)(vindex-2)); // FIXME don't duplicate lines and points } circle(width, depth, 0, -hh, 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, divisions, 180f-angleTo, 180f-angleFrom); } @Override public void sphere(float width, float height, float depth, int divisionsU, int divisionsV) { sphere(width, height, depth, divisionsU, divisionsV, 0, 360, 0, 180); } @Override public void sphere(final Matrix4 transform, float width, float height, float depth, int divisionsU, int divisionsV) { sphere(transform, width, height, depth, divisionsU, divisionsV, 0, 360, 0, 180); } @Override public void sphere(float width, float height, float depth, int divisionsU, int divisionsV, float angleUFrom, float angleUTo, float angleVFrom, float angleVTo) { sphere(matTmp1.idt(), width, height, depth, divisionsU, divisionsV, angleUFrom, angleUTo, angleVFrom, angleVTo); } @Override public void sphere(final Matrix4 transform, float width, float height, float depth, int divisionsU, int divisionsV, float angleUFrom, float angleUTo, float angleVFrom, float angleVTo) { // FIXME create better sphere method (- only one vertex for each pole, - position) final float hw = width * 0.5f; final float hh = height * 0.5f; final float hd = depth * 0.5f; final float auo = MathUtils.degreesToRadians * angleUFrom; final float stepU = (MathUtils.degreesToRadians * (angleUTo - angleUFrom)) / divisionsU; final float avo = MathUtils.degreesToRadians * angleVFrom; final float stepV = (MathUtils.degreesToRadians * (angleVTo - angleVFrom)) / divisionsV; final float us = 1f / divisionsU; final float vs = 1f / divisionsV; float u = 0f; float v = 0f; float angleU = 0f; float angleV = 0f; VertexInfo curr1 = vertTmp3.set(null, null, null, null); curr1.hasUV = curr1.hasPosition = curr1.hasNormal = true; ensureRectangles((divisionsV + 1) * (divisionsU + 1), divisionsV * divisionsU); for (int iv = 0; iv <= divisionsV; iv++) { angleV = avo + stepV * iv; v = vs * iv; final float t = MathUtils.sin(angleV); final float h = MathUtils.cos(angleV) * hh; for (int iu = 0; iu <= divisionsU; iu++) { angleU = auo + stepU * iu; u = 1f - us * iu; curr1.position.set(MathUtils.cos(angleU) * hw * t, h, MathUtils.sin(angleU) * hd * t).mul(transform); curr1.normal.set(curr1.position).nor(); curr1.uv.set(u, v); vertex(curr1); if ((iv > 0) && (iu > 0)) // FIXME don't duplicate lines and points rect((short)(vindex-1), (short)(vindex-2), (short)(vindex-(divisionsU+3)), (short)(vindex-(divisionsU+2))); } } } @Override public void capsule(float radius, float height, int divisions) { if (height < 2f * radius) throw new GdxRuntimeException("Height must be at least twice the radius"); final float d = 2f * radius; cylinder(d, height - d, d, divisions, 0, 360, false); sphere(matTmp1.setToTranslation(0, .5f*(height-d), 0), d, d, d, divisions, divisions, 0, 360, 0, 90); sphere(matTmp1.setToTranslation(0, -.5f*(height-d), 0), d, d, d, divisions, divisions, 0, 360, 90, 180); } }
gdx/src/com/badlogic/gdx/graphics/g3d/utils/MeshBuilder.java
package com.badlogic.gdx.graphics.g3d.utils; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.graphics.Color; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.VertexAttribute; import com.badlogic.gdx.graphics.VertexAttributes; import com.badlogic.gdx.graphics.VertexAttributes.Usage; import com.badlogic.gdx.graphics.g3d.Model; import com.badlogic.gdx.graphics.g3d.model.MeshPart; import com.badlogic.gdx.graphics.g3d.utils.MeshPartBuilder.VertexInfo; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.math.MathUtils; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector2; import com.badlogic.gdx.math.Vector3; import com.badlogic.gdx.utils.Array; import com.badlogic.gdx.utils.FloatArray; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.Pool; import com.badlogic.gdx.utils.Pool.Poolable; import com.badlogic.gdx.utils.ShortArray; /** Class to construct a mesh, optionally splitting it into one or more mesh parts. * Before you can call any other method you must call {@link #begin(VertexAttributes)} or {@link #begin(VertexAttributes, int)}. * To use mesh parts you must call {@link #part(String, int)} before you start building the part. * The MeshPart itself is only valid after the call to {@link #end()}. * @author Xoppa */ public class MeshBuilder implements MeshPartBuilder { private final VertexInfo vertTmp1 = new VertexInfo(); private final VertexInfo vertTmp2 = new VertexInfo(); private final VertexInfo vertTmp3 = new VertexInfo(); private final VertexInfo vertTmp4 = new VertexInfo(); private final VertexInfo vertTmp5 = new VertexInfo(); private final VertexInfo vertTmp6 = new VertexInfo(); private final VertexInfo vertTmp7 = new VertexInfo(); private final VertexInfo vertTmp8 = new VertexInfo(); private final Matrix4 matTmp1 = new Matrix4(); private final Vector3 tempV1 = new Vector3(); private final Vector3 tempV2 = new Vector3(); private final Vector3 tempV3 = new Vector3(); private final Vector3 tempV4 = new Vector3(); private final Vector3 tempV5 = new Vector3(); private final Vector3 tempV6 = new Vector3(); private final Vector3 tempV7 = new Vector3(); private final Vector3 tempV8 = new Vector3(); /** The vertex attributes of the resulting mesh */ private VertexAttributes attributes; /** The vertices to construct, no size checking is done */ private FloatArray vertices = new FloatArray(); /** The indices to construct, no size checking is done */ private ShortArray indices = new ShortArray(); /** The size (in number of floats) of each vertex */ private int stride; /** The current vertex index, used for indexing */ private short vindex; /** The offset in the indices array when begin() was called, used to define a meshpart. */ private int istart; /** The offset within an vertex to position */ private int posOffset; /** The size (in number of floats) of the position attribute */ private int posSize; /** The offset within an vertex to normal, or -1 if not available */ private int norOffset; /** The offset within an vertex to color, or -1 if not available */ private int colOffset; /** The size (in number of floats) of the color attribute */ private int colSize; /** The offset within an vertex to packed color, or -1 if not available */ private int cpOffset; /** The offset within an vertex to texture coordinates, or -1 if not available */ private int uvOffset; /** The meshpart currently being created */ private MeshPart part; /** The parts created between begin and end */ private Array<MeshPart> parts = new Array<MeshPart>(); /** The color used if no vertex color is specified. */ private final Color color = new Color(); /** Whether to apply the default color. */ private boolean colorSet; /** The current primitiveType */ private int primitiveType; // FIXME makes this configurable private float uMin = 0, uMax = 1, vMin = 0, vMax = 1; private float[] vertex; /** @param usage bitwise mask of the {@link com.badlogic.gdx.graphics.VertexAttributes.Usage}, * only Position, Color, Normal and TextureCoordinates is supported. */ public static VertexAttributes createAttributes(long usage) { final Array<VertexAttribute> attrs = new Array<VertexAttribute>(); if ((usage & Usage.Position) == Usage.Position) attrs.add(new VertexAttribute(Usage.Position, 3, ShaderProgram.POSITION_ATTRIBUTE)); if ((usage & Usage.Color) == Usage.Color) attrs.add(new VertexAttribute(Usage.Color, 4, ShaderProgram.COLOR_ATTRIBUTE)); if ((usage & Usage.Normal) == Usage.Normal) attrs.add(new VertexAttribute(Usage.Normal, 3, ShaderProgram.NORMAL_ATTRIBUTE)); if ((usage & Usage.TextureCoordinates) == Usage.TextureCoordinates) attrs.add(new VertexAttribute(Usage.TextureCoordinates, 2, ShaderProgram.TEXCOORD_ATTRIBUTE+"0")); final VertexAttribute attributes[] = new VertexAttribute[attrs.size]; for (int i = 0; i < attributes.length; i++) attributes[i] = attrs.get(i); return new VertexAttributes(attributes); } /** Begin building a mesh. Call {@link #part(String, int)} to start a {@link MeshPart}. * @param attributes bitwise mask of the {@link com.badlogic.gdx.graphics.VertexAttributes.Usage}, * only Position, Color, Normal and TextureCoordinates is supported. */ public void begin(final long attributes) { begin(createAttributes(attributes), 0); } /** Begin building a mesh. Call {@link #part(String, int)} to start a {@link MeshPart}. */ public void begin(final VertexAttributes attributes) { begin(attributes, 0); } /** Begin building a mesh. * @param attributes bitwise mask of the {@link com.badlogic.gdx.graphics.VertexAttributes.Usage}, * only Position, Color, Normal and TextureCoordinates is supported. */ public void begin(final long attributes, int primitiveType) { begin(createAttributes(attributes), primitiveType); } /** Begin building a mesh */ public void begin(final VertexAttributes attributes, int primitiveType) { if (this.attributes != null) throw new RuntimeException("Call end() first"); this.attributes = attributes; this.vertices.clear(); this.indices.clear(); this.parts.clear(); this.vindex = 0; this.istart = 0; this.part = null; this.stride = attributes.vertexSize / 4; this.vertex = new float[stride]; VertexAttribute a = attributes.findByUsage(Usage.Position); if (a == null) throw new GdxRuntimeException("Cannot build mesh without position attribute"); posOffset = a.offset / 4; posSize = a.numComponents; a = attributes.findByUsage(Usage.Normal); norOffset = a == null ? -1 : a.offset / 4; a = attributes.findByUsage(Usage.Color); colOffset = a == null ? -1 : a.offset / 4; colSize = a == null ? 0 : a.numComponents; a = attributes.findByUsage(Usage.ColorPacked); cpOffset = a == null ? -1 : a.offset / 4; a = attributes.findByUsage(Usage.TextureCoordinates); uvOffset = a == null ? -1 : a.offset / 4; setColor(null); this.primitiveType = primitiveType; } private void endpart() { if (part != null) { part.indexOffset = istart; part.numVertices = indices.size - istart; istart = indices.size; part = null; } } /** Starts a new MeshPart. The mesh part is not usable until end() is called */ public MeshPart part(final String id, int primitiveType) { if (this.attributes == null) throw new RuntimeException("Call begin() first"); endpart(); part = new MeshPart(); part.id = id; this.primitiveType = part.primitiveType = primitiveType; parts.add(part); setColor(null); return part; } /** End building the mesh and returns the mesh */ public Mesh end() { if (this.attributes == null) throw new RuntimeException("Call begin() first"); endpart(); final Mesh mesh = new Mesh(true, vertices.size, indices.size, attributes); mesh.setVertices(vertices.items, 0, vertices.size); mesh.setIndices(indices.items, 0, indices.size); for (MeshPart p : parts) p.mesh = mesh; parts.clear(); attributes = null; vertices.clear(); indices.clear(); return mesh; } @Override public VertexAttributes getAttributes() { return attributes; } @Override public MeshPart getMeshPart() { return part; } private final static Pool<Vector3> vectorPool = new Pool<Vector3>() { @Override protected Vector3 newObject () { return new Vector3(); } }; private final static Array<Vector3> vectorArray = new Array<Vector3>(); private Vector3 tmp(float x, float y, float z) { final Vector3 result = vectorPool.obtain().set(x, y, z); vectorArray.add(result); return result; } private Vector3 tmp(Vector3 copyFrom) { return tmp(copyFrom.x, copyFrom.y, copyFrom.z); } private void cleanup() { vectorPool.freeAll(vectorArray); vectorArray.clear(); } @Override public void setColor(float r, float g, float b, float a) { color.set(r, g, b, a); colorSet = true; } @Override public void setColor(final Color color) { if ((colorSet = color != null)==true) this.color.set(color); } @Override public void setUVRange(float u1, float v1, float u2, float v2) { uMin = u1; vMin = v1; uMax = u2; vMax = v2; } /** Increases the size of the backing vertices array to accommodate the specified number of additional vertices. * Useful before adding many vertices to avoid multiple backing array resizes. * @param numVertices The number of vertices you are about to add */ public void ensureVertices(int numVertices) { vertices.ensureCapacity(vertex.length * numVertices); } /** Increases the size of the backing indices array to accommodate the specified number of additional indices. * Useful before adding many indices to avoid multiple backing array resizes. * @param numIndices The number of indices you are about to add */ public void ensureIndices(int numIndices) { indices.ensureCapacity(numIndices); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and indices. Useful before adding many vertices and indices to avoid multiple backing array resizes. * @param numVertices The number of vertices you are about to add * @param numIndices The number of indices you are about to add */ public void ensureCapacity(int numVertices, int numIndices) { ensureVertices(numVertices); ensureIndices(numIndices); } /** Increases the size of the backing indices array to accommodate the specified number of additional triangles. * Useful before adding many triangles to avoid multiple backing array resizes. * @param numTriangles The number of triangles you are about to add */ public void ensureTriangleIndices(int numTriangles) { if (primitiveType == GL10.GL_LINES) ensureIndices(6 * numTriangles); else // GL_TRIANGLES || GL_POINTS ensureIndices(3 * numTriangles); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and triangles. Useful before adding many triangles to avoid multiple backing array resizes. * @param numVertices The number of vertices you are about to add * @param numTriangles The number of triangles you are about to add */ public void ensureTriangles(int numVertices, int numTriangles) { ensureVertices(numVertices); ensureTriangleIndices(numTriangles); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and triangles. Useful before adding many triangles to avoid multiple backing array resizes. * Assumes each triangles adds 3 vertices. * @param numTriangles The number of triangles you are about to add */ public void ensureTriangles(int numTriangles) { ensureTriangles(3 * numTriangles, numTriangles); } /** Increases the size of the backing indices array to accommodate the specified number of additional rectangles. * Useful before adding many rectangles to avoid multiple backing array resizes. * @param numRectangles The number of rectangles you are about to add */ public void ensureRectangleIndices(int numRectangles) { if (primitiveType == GL10.GL_POINTS) ensureIndices(4 * numRectangles); else if (primitiveType == GL10.GL_LINES) ensureIndices(8 * numRectangles); else // GL_TRIANGLES ensureIndices(6 * numRectangles); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and rectangles. Useful before adding many rectangles to avoid multiple backing array resizes. * @param numVertices The number of vertices you are about to add * @param numRectangles The number of rectangles you are about to add */ public void ensureRectangles(int numVertices, int numRectangles) { ensureVertices(numVertices); ensureRectangleIndices(numRectangles); } /** Increases the size of the backing vertices and indices arrays to accommodate the specified number of additional * vertices and rectangles. Useful before adding many rectangles to avoid multiple backing array resizes. * Assumes each rectangles adds 4 vertices * @param numRectangles The number of rectangles you are about to add */ public void ensureRectangles(int numRectangles) { ensureRectangles(4 * numRectangles, numRectangles); } @Override public short vertex(Vector3 pos, Vector3 nor, Color col, Vector2 uv) { if (vindex >= Short.MAX_VALUE) throw new GdxRuntimeException("Too many vertices used"); if (col == null && colorSet) col = color; if (pos != null) { vertex[posOffset ] = pos.x; if (posSize > 1) vertex[posOffset+1] = pos.y; if (posSize > 2) vertex[posOffset+2] = pos.z; } if (nor != null && norOffset >= 0) { vertex[norOffset ] = nor.x; vertex[norOffset+1] = nor.y; vertex[norOffset+2] = nor.z; } if (col != null) { if (colOffset >= 0) { vertex[colOffset ] = col.r; vertex[colOffset+1] = col.g; vertex[colOffset+2] = col.b; if (colSize > 3) vertex[colOffset+3] = col.a; } else if (cpOffset > 0) vertex[cpOffset] = col.toFloatBits(); // FIXME cache packed color? } if (uv != null && uvOffset >= 0) { vertex[uvOffset ] = uv.x; vertex[uvOffset+1] = uv.y; } vertices.addAll(vertex); return (short)(vindex++); } @Override public short lastIndex() { return (short)(vindex-1); } @Override public short vertex(final float... values) { vertices.addAll(values); vindex += values.length / stride; return (short)(vindex-1); } @Override public short vertex(final VertexInfo info) { return vertex(info.hasPosition ? info.position : null, info.hasNormal ? info.normal : null, info.hasColor ? info.color : null, info.hasUV ? info.uv : null); } @Override public void index(final short value) { indices.add(value); } @Override public void index(final short value1, final short value2) { ensureIndices(2); indices.add(value1); indices.add(value2); } @Override public void index(final short value1, final short value2, final short value3) { ensureIndices(3); indices.add(value1); indices.add(value2); indices.add(value3); } @Override public void index(final short value1, final short value2, final short value3, final short value4) { ensureIndices(4); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); } @Override public void index(short value1, short value2, short value3, short value4, short value5, short value6) { ensureIndices(6); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); indices.add(value5); indices.add(value6); } @Override public void index(short value1, short value2, short value3, short value4, short value5, short value6, short value7, short value8) { ensureIndices(8); indices.add(value1); indices.add(value2); indices.add(value3); indices.add(value4); indices.add(value5); indices.add(value6); indices.add(value7); indices.add(value8); } @Override public void line(short index1, short index2) { if (primitiveType != GL10.GL_LINES) throw new GdxRuntimeException("Incorrect primitive type"); index(index1, index2); } @Override public void line(VertexInfo p1, VertexInfo p2) { ensureVertices(2); line(vertex(p1), vertex(p2)); } @Override public void line(Vector3 p1, Vector3 p2) { line(vertTmp1.set(p1, null, null, null), vertTmp2.set(p2, null, null, null)); } @Override public void line(float x1, float y1, float z1, float x2, float y2, float z2) { line(vertTmp1.set(null, null, null, null).setPos(x1, y1, z1), vertTmp2.set(null, null, null, null).setPos(x2, y2, z2)); } @Override public void line(Vector3 p1, Color c1, Vector3 p2, Color c2) { line(vertTmp1.set(p1, null, c1, null), vertTmp2.set(p2, null, c2, null)); } @Override public void triangle(short index1, short index2, short index3) { if (primitiveType == GL10.GL_TRIANGLES || primitiveType == GL10.GL_POINTS) { index(index1, index2, index3); } else if (primitiveType == GL10.GL_LINES) { index(index1, index2, index2, index3, index3, index1); } else throw new GdxRuntimeException("Incorrect primitive type"); } @Override public void triangle(VertexInfo p1, VertexInfo p2, VertexInfo p3) { ensureVertices(3); triangle(vertex(p1), vertex(p2), vertex(p3)); } @Override public void triangle(Vector3 p1, Vector3 p2, Vector3 p3) { triangle(vertTmp1.set(p1, null, null, null), vertTmp2.set(p2, null, null, null), vertTmp3.set(p3, null, null, null)); } @Override public void triangle(Vector3 p1, Color c1, Vector3 p2, Color c2, Vector3 p3, Color c3) { triangle(vertTmp1.set(p1, null, c1, null), vertTmp2.set(p2, null, c2, null), vertTmp3.set(p3, null, c3, null)); } @Override public void rect(short corner00, short corner10, short corner11, short corner01) { if (primitiveType == GL10.GL_TRIANGLES) { index(corner00, corner10, corner11, corner11, corner01, corner00); } else if (primitiveType == GL10.GL_LINES) { index(corner00, corner10, corner10, corner11, corner11, corner01, corner01, corner00); } else if (primitiveType == GL10.GL_POINTS) { index(corner00, corner10, corner11, corner01); } else throw new GdxRuntimeException("Incorrect primitive type"); } @Override public void rect(VertexInfo corner00, VertexInfo corner10, VertexInfo corner11, VertexInfo corner01) { ensureVertices(4); rect(vertex(corner00), vertex(corner10), vertex(corner11), vertex(corner01)); } @Override public void rect(Vector3 corner00, Vector3 corner10, Vector3 corner11, Vector3 corner01, Vector3 normal) { rect(vertTmp1.set(corner00, normal, null, null).setUV(uMin,vMin), vertTmp2.set(corner10, normal, null, null).setUV(uMax,vMin), vertTmp3.set(corner11, normal, null, null).setUV(uMax,vMax), vertTmp4.set(corner01, normal, null, null).setUV(uMin,vMax)); } @Override public void rect(float x00, float y00, float z00, float x10, float y10, float z10, float x11, float y11, float z11, float x01, float y01, float z01, float normalX, float normalY, float normalZ) { rect(vertTmp1.set(null, null, null, null).setPos(x00,y00,z00).setNor(normalX,normalY,normalZ).setUV(uMin,vMin), vertTmp2.set(null, null, null, null).setPos(x10,y10,z10).setNor(normalX,normalY,normalZ).setUV(uMax,vMin), vertTmp3.set(null, null, null, null).setPos(x11,y11,z11).setNor(normalX,normalY,normalZ).setUV(uMax,vMax), vertTmp4.set(null, null, null, null).setPos(x01,y01,z01).setNor(normalX,normalY,normalZ).setUV(uMin,vMax)); } @Override public void patch(VertexInfo corner00, VertexInfo corner10, VertexInfo corner11, VertexInfo corner01, int divisionsU, int divisionsV) { ensureRectangles((divisionsV + 1) * (divisionsU + 1), divisionsV * divisionsU); for (int u = 0; u <= divisionsU; u++) { final float alphaU = (float)u / (float)divisionsU; vertTmp5.set(corner00).lerp(corner10, alphaU); vertTmp6.set(corner01).lerp(corner11, alphaU); for (int v = 0; v <= divisionsV; v++) { final short idx = vertex(vertTmp7.set(vertTmp5).lerp(vertTmp6, (float)v / (float)divisionsV)); if (u > 0 && v > 0) rect((short)(idx-divisionsV-2), (short)(idx-1), idx, (short)(idx-divisionsV-1)); } } } @Override public void patch(Vector3 corner00, Vector3 corner10, Vector3 corner11, Vector3 corner01, Vector3 normal, int divisionsU, int divisionsV) { patch(vertTmp1.set(corner00, normal, null, null).setUV(uMin,vMin), vertTmp2.set(corner10, normal, null, null).setUV(uMax,vMin), vertTmp3.set(corner11, normal, null, null).setUV(uMax,vMax), vertTmp4.set(corner01, normal, null, null).setUV(uMin,vMax), divisionsU, divisionsV); } public void patch(float x00, float y00, float z00, float x10, float y10, float z10, float x11, float y11, float z11, float x01, float y01, float z01, float normalX, float normalY, float normalZ, int divisionsU, int divisionsV) { patch(vertTmp1.set(null).setPos(x00, y00, z00).setNor(normalX, normalY, normalZ).setUV(uMin,vMin), vertTmp2.set(null).setPos(x10, y10, z10).setNor(normalX, normalY, normalZ).setUV(uMax,vMin), vertTmp3.set(null).setPos(x11, y11, z11).setNor(normalX, normalY, normalZ).setUV(uMax,vMax), vertTmp4.set(null).setPos(x01, y01, z01).setNor(normalX, normalY, normalZ).setUV(uMin,vMax), divisionsU, divisionsV); } @Override public void box(VertexInfo corner000, VertexInfo corner010, VertexInfo corner100, VertexInfo corner110, VertexInfo corner001, VertexInfo corner011, VertexInfo corner101, VertexInfo corner111) { ensureVertices(8); final short i000 = vertex(corner000); final short i100 = vertex(corner100); final short i110 = vertex(corner110); final short i010 = vertex(corner010); final short i001 = vertex(corner001); final short i101 = vertex(corner101); final short i111 = vertex(corner111); final short i011 = vertex(corner011); if (primitiveType == GL10.GL_LINES) { ensureIndices(24); rect(i000, i100, i110, i010); rect(i101, i001, i011, i111); index(i000, i001, i010, i011, i110, i111, i100, i101); } else if (primitiveType != GL10.GL_POINTS) { ensureRectangleIndices(2); rect(i000, i100, i110, i010); rect(i101, i001, i011, i111); } else { // GL10.GL_TRIANGLES ensureRectangleIndices(6); rect(i000, i100, i110, i010); rect(i101, i001, i011, i111); rect(i000, i010, i011, i001); rect(i101, i111, i110, i100); rect(i101, i100, i000, i001); rect(i110, i111, i011, i010); } } @Override public void box(Vector3 corner000, Vector3 corner010, Vector3 corner100, Vector3 corner110, Vector3 corner001, Vector3 corner011, Vector3 corner101, Vector3 corner111) { if (norOffset < 0 && uvOffset < 0) { box(vertTmp1.set(corner000, null, null, null), vertTmp2.set(corner010, null, null, null), vertTmp3.set(corner100, null, null, null), vertTmp4.set(corner110, null, null, null), vertTmp5.set(corner001, null, null, null), vertTmp6.set(corner011, null, null, null), vertTmp7.set(corner101, null, null, null), vertTmp8.set(corner111, null, null, null)); } else { ensureRectangles(6); Vector3 nor = tempV1.set(corner000).lerp(corner110, 0.5f).sub(tempV2.set(corner001).lerp(corner111, 0.5f)).nor(); rect(corner000, corner010, corner110, corner100, nor); rect(corner011, corner001, corner101, corner111, nor.scl(-1)); nor = tempV1.set(corner000).lerp(corner101, 0.5f).sub(tempV2.set(corner010).lerp(corner111, 0.5f)).nor(); rect(corner001, corner000, corner100, corner101, nor); rect(corner010, corner011, corner111, corner110, nor.scl(-1)); nor = tempV1.set(corner000).lerp(corner011, 0.5f).sub(tempV2.set(corner100).lerp(corner111, 0.5f)).nor(); rect(corner001, corner011, corner010, corner000, nor); rect(corner100, corner110, corner111, corner101, nor.scl(-1)); } } @Override public void box(Matrix4 transform) { box(tmp(-0.5f,-0.5f,-0.5f).mul(transform),tmp(-0.5f,0.5f,-0.5f).mul(transform),tmp(0.5f,-0.5f,-0.5f).mul(transform),tmp(0.5f,0.5f,-0.5f).mul(transform), tmp(-0.5f,-0.5f,0.5f).mul(transform),tmp(-0.5f,0.5f,0.5f).mul(transform),tmp(0.5f,-0.5f,0.5f).mul(transform),tmp(0.5f,0.5f,0.5f).mul(transform)); cleanup(); } @Override public void box(float width, float height, float depth) { box(matTmp1.setToScaling(width, height, depth)); } @Override public void box(float x, float y, float z, float width, float height, float depth) { box(matTmp1.setToScaling(width, height, depth).trn(x, y, z)); } @Override public void circle(float width, float height, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, int divisions) { circle(width, height, centerX, centerY, centerZ, normalX, normalY, normalZ, divisions, 0, 360); } @Override public void circle(float width, float height, final Vector3 center, final Vector3 normal, int divisions) { circle(width, height, center.x, center.y, center.z, normal.x, normal.y, normal.z, divisions); } @Override public void circle(float width, float height, final Vector3 center, final Vector3 normal, final Vector3 tangent, final Vector3 binormal, int divisions) { circle(width, height, center.x, center.y, center.z, normal.x, normal.y, normal.z, tangent.x, tangent.y, tangent.z, binormal.x, binormal.y, binormal.z, divisions); } @Override public void circle(float width, float height, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, int divisions) { circle(width, height, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ, divisions, 0, 360); } @Override public void circle(float width, float height, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, int divisions, float angleFrom, float angleTo) { tempV1.set(normalX, normalY, normalZ).crs(0, 0, 1); tempV2.set(normalX, normalY, normalZ).crs(0, 1, 0); if (tempV2.len2() > tempV1.len2()) tempV1.set(tempV2); tempV2.set(tempV1.nor()).crs(normalX, normalY, normalZ).nor(); circle(width, height, centerX, centerY, centerZ, normalX, normalY, normalZ, tempV1.x, tempV1.y, tempV1.z, tempV2.x, tempV2.y, tempV2.z, divisions, angleFrom, angleTo); } @Override public void circle(float width, float height, final Vector3 center, final Vector3 normal, int divisions, float angleFrom, float angleTo) { circle(width, height, center.x, center.y, center.z, normal.x, normal.y, normal.z, divisions, angleFrom, angleTo); } @Override public void circle(float width, float height, final Vector3 center, final Vector3 normal, final Vector3 tangent, final Vector3 binormal, int divisions, float angleFrom, float angleTo) { circle(width, height, center.x, center.y, center.z, normal.x, normal.y, normal.z, tangent.x, tangent.y, tangent.z, binormal.x, binormal.y, binormal.z, divisions, angleFrom, angleTo); } @Override public void circle(float width, float height, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, int divisions, float angleFrom, float angleTo) { ellipse(width, height, 0, 0, centerX, centerY, centerZ, normalX, normalY, normalZ, tangentX, tangentY, tangentZ, binormalX, binormalY, binormalZ, divisions, angleFrom, angleTo); } @Override public void ellipse(float width, float height, float innerWidth, float innerHeight, Vector3 center, Vector3 normal, int divisions) { ellipse(width, height, innerWidth, innerHeight, center.x, center.y, center.z, normal.x, normal.y, normal.z, divisions, 0, 360); } @Override public void ellipse(float width, float height, float innerWidth, float innerHeight, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, int divisions) { ellipse(width, height, innerWidth, innerHeight, centerX, centerY, centerZ, normalX, normalY, normalZ, divisions, 0, 360); } @Override public void ellipse(float width, float height, float innerWidth, float innerHeight, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, int divisions, float angleFrom, float angleTo) { tempV1.set(normalX, normalY, normalZ).crs(0, 0, 1); tempV2.set(normalX, normalY, normalZ).crs(0, 1, 0); if (tempV2.len2() > tempV1.len2()) tempV1.set(tempV2); tempV2.set(tempV1.nor()).crs(normalX, normalY, normalZ).nor(); ellipse(width, height, innerWidth, innerHeight, centerX, centerY, centerZ, normalX, normalY, normalZ, tempV1.x, tempV1.y, tempV1.z, tempV2.x, tempV2.y, tempV2.z, divisions, angleFrom, angleTo); } @Override public void ellipse(float width, float height, float innerWidth, float innerHeight, float centerX, float centerY, float centerZ, float normalX, float normalY, float normalZ, float tangentX, float tangentY, float tangentZ, float binormalX, float binormalY, float binormalZ, int divisions, float angleFrom, float angleTo) { if(innerWidth <= 0 || innerHeight <= 0) { ensureTriangles(divisions + 2, divisions); } else if (innerWidth == width && innerHeight == height){ ensureVertices(divisions + 1); if(primitiveType != GL10.GL_LINES) throw new GdxRuntimeException("Incorrect primitive type : expect GL_LINES because innerWidth == width && innerHeight == height"); } else { ensureRectangleIndices(divisions + 1); } final float ao = MathUtils.degreesToRadians * angleFrom; final float step = (MathUtils.degreesToRadians * (angleTo - angleFrom)) / divisions; final Vector3 sxEx = tempV1.set(tangentX, tangentY, tangentZ).scl(width * 0.5f); final Vector3 syEx = tempV2.set(binormalX, binormalY, binormalZ).scl(height * 0.5f); final Vector3 sxIn = tempV3.set(tangentX, tangentY, tangentZ).scl(innerWidth * 0.5f); final Vector3 syIn = tempV4.set(binormalX, binormalY, binormalZ).scl(innerHeight * 0.5f); VertexInfo currIn = vertTmp3.set(null, null, null, null); currIn.hasUV = true; currIn.uv.set(.5f, .5f); currIn.hasPosition = currIn.hasNormal = true; currIn.position.set(centerX, centerY, centerZ); currIn.normal.set(normalX, normalY, normalZ); VertexInfo currEx = vertTmp4.set(null, null, null, null); currEx.hasUV = true; currEx.uv.set(.5f, .5f); currEx.hasPosition = currEx.hasNormal = true; currEx.position.set(centerX, centerY, centerZ); currEx.normal.set(normalX, normalY, normalZ); final short center = vertex(currEx); float angle = 0f; for (int i = 0; i <= divisions; i++) { angle = ao + step * i; final float x = MathUtils.cos(angle); final float y = MathUtils.sin(angle); currEx.position.set(centerX, centerY, centerZ).add(sxEx.x*x+syEx.x*y, sxEx.y*x+syEx.y*y, sxEx.z*x+syEx.z*y); currEx.uv.set(.5f + .5f * x, .5f + .5f * y); vertex(currEx); if(innerWidth <= 0 || innerHeight <= 0) { if (i != 0) triangle((short)(vindex - 1), (short)(vindex - 2), center); } else if (innerWidth == width && innerHeight == height){ if (i != 0) line((short)(vindex - 1), (short)(vindex - 2)); } else { currIn.position.set(centerX, centerY, centerZ).add(sxIn.x*x+syIn.x*y, sxIn.y*x+syIn.y*y, sxIn.z*x+syIn.z*y); currIn.uv.set(.5f + .5f * x, .5f + .5f * y); vertex(currIn); if( i != 0) rect((short)(vindex - 1), (short)(vindex - 2),(short)(vindex - 4), (short)(vindex - 3)); } } } @Override public void cylinder(float width, float height, float depth, int divisions) { cylinder(width, height, depth, divisions, 0, 360); } @Override public void cylinder(float width, float height, float depth, int divisions, float angleFrom, float angleTo) { cylinder(width, height, depth, divisions, angleFrom, angleTo, true); } /** Add a cylinder */ public void cylinder(float width, float height, float depth, int divisions, float angleFrom, float angleTo, boolean close) { // FIXME create better cylinder method (- axis on which to create the cylinder (matrix?)) final float hw = width * 0.5f; final float hh = height * 0.5f; final float hd = depth * 0.5f; final float ao = MathUtils.degreesToRadians * angleFrom; final float step = (MathUtils.degreesToRadians * (angleTo - angleFrom)) / divisions; final float us = 1f / divisions; float u = 0f; float angle = 0f; VertexInfo curr1 = vertTmp3.set(null, null, null, null); curr1.hasUV = curr1.hasPosition = curr1.hasNormal = true; VertexInfo curr2 = vertTmp4.set(null, null, null, null); curr2.hasUV = curr2.hasPosition = curr2.hasNormal = true; ensureRectangles(2 * (divisions + 1), divisions); for (int i = 0; i <= divisions; i++) { angle = ao + step * i; u = 1f - us * i; curr1.position.set(MathUtils.cos(angle) * hw, 0f, MathUtils.sin(angle) * hd); curr1.normal.set(curr1.position).nor(); curr1.position.y = -hh; curr1.uv.set(u, 1); curr2.position.set(curr1.position); curr2.normal.set(curr1.normal); curr2.position.y = hh; curr2.uv.set(u, 0); vertex(curr1); vertex(curr2); if (i != 0) rect((short)(vindex-3), (short)(vindex-1), (short)(vindex-2), (short)(vindex-4)); // FIXME don't duplicate lines and points } if (close) { circle(width, depth, 0, hh, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, divisions, angleFrom, angleTo); circle(width, depth, 0, -hh, 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, divisions, 180f-angleTo, 180f-angleFrom); } } @Override public void cone(float width, float height, float depth, int divisions) { cone(width, height, depth, divisions, 0, 360); } @Override public void cone(float width, float height, float depth, int divisions, float angleFrom, float angleTo) { // FIXME create better cylinder method (- axis on which to create the cone (matrix?)) ensureTriangles(divisions + 2, divisions); final float hw = width * 0.5f; final float hh = height * 0.5f; final float hd = depth * 0.5f; final float ao = MathUtils.degreesToRadians * angleFrom; final float step = (MathUtils.degreesToRadians * (angleTo - angleFrom)) / divisions; final float us = 1f / divisions; float u = 0f; float angle = 0f; VertexInfo curr1 = vertTmp3.set(null, null, null, null); curr1.hasUV = curr1.hasPosition = curr1.hasNormal = true; VertexInfo curr2 = vertTmp4.set(null, null, null, null).setPos(0,hh,0).setNor(0,1,0).setUV(0.5f, 0); final int base = vertex(curr2); for (int i = 0; i <= divisions; i++) { angle = ao + step * i; u = 1f - us * i; curr1.position.set(MathUtils.cos(angle) * hw, 0f, MathUtils.sin(angle) * hd); curr1.normal.set(curr1.position).nor(); curr1.position.y = -hh; curr1.uv.set(u, 1); vertex(curr1); if (i == 0) continue; triangle((short)base, (short)(vindex-1), (short)(vindex-2)); // FIXME don't duplicate lines and points } circle(width, depth, 0, -hh, 0, 0, -1, 0, -1, 0, 0, 0, 0, 1, divisions, 180f-angleTo, 180f-angleFrom); } @Override public void sphere(float width, float height, float depth, int divisionsU, int divisionsV) { sphere(width, height, depth, divisionsU, divisionsV, 0, 360, 0, 180); } @Override public void sphere(final Matrix4 transform, float width, float height, float depth, int divisionsU, int divisionsV) { sphere(transform, width, height, depth, divisionsU, divisionsV, 0, 360, 0, 180); } @Override public void sphere(float width, float height, float depth, int divisionsU, int divisionsV, float angleUFrom, float angleUTo, float angleVFrom, float angleVTo) { sphere(matTmp1.idt(), width, height, depth, divisionsU, divisionsV, angleUFrom, angleUTo, angleVFrom, angleVTo); } @Override public void sphere(final Matrix4 transform, float width, float height, float depth, int divisionsU, int divisionsV, float angleUFrom, float angleUTo, float angleVFrom, float angleVTo) { // FIXME create better sphere method (- only one vertex for each pole, - position) final float hw = width * 0.5f; final float hh = height * 0.5f; final float hd = depth * 0.5f; final float auo = MathUtils.degreesToRadians * angleUFrom; final float stepU = (MathUtils.degreesToRadians * (angleUTo - angleUFrom)) / divisionsU; final float avo = MathUtils.degreesToRadians * angleVFrom; final float stepV = (MathUtils.degreesToRadians * (angleVTo - angleVFrom)) / divisionsV; final float us = 1f / divisionsU; final float vs = 1f / divisionsV; float u = 0f; float v = 0f; float angleU = 0f; float angleV = 0f; VertexInfo curr1 = vertTmp3.set(null, null, null, null); curr1.hasUV = curr1.hasPosition = curr1.hasNormal = true; ensureRectangles((divisionsV + 1) * (divisionsU + 1), divisionsV * divisionsU); for (int iv = 0; iv <= divisionsV; iv++) { angleV = avo + stepV * iv; v = vs * iv; final float t = MathUtils.sin(angleV); final float h = MathUtils.cos(angleV) * hh; for (int iu = 0; iu <= divisionsU; iu++) { angleU = auo + stepU * iu; u = 1f - us * iu; curr1.position.set(MathUtils.cos(angleU) * hw * t, h, MathUtils.sin(angleU) * hd * t).mul(transform); curr1.normal.set(curr1.position).nor(); curr1.uv.set(u, v); vertex(curr1); if ((iv > 0) && (iu > 0)) // FIXME don't duplicate lines and points rect((short)(vindex-1), (short)(vindex-2), (short)(vindex-(divisionsU+3)), (short)(vindex-(divisionsU+2))); } } } @Override public void capsule(float radius, float height, int divisions) { if (height < 2f * radius) throw new GdxRuntimeException("Height must be at least twice the radius"); final float d = 2f * radius; cylinder(d, height - d, d, divisions, 0, 360, false); sphere(matTmp1.setToTranslation(0, .5f*(height-d), 0), d, d, d, divisions, divisions, 0, 360, 0, 90); sphere(matTmp1.setToTranslation(0, -.5f*(height-d), 0), d, d, d, divisions, divisions, 0, 360, 90, 180); } }
fixed vertices and indices ensuring
gdx/src/com/badlogic/gdx/graphics/g3d/utils/MeshBuilder.java
fixed vertices and indices ensuring
<ide><path>dx/src/com/badlogic/gdx/graphics/g3d/utils/MeshBuilder.java <ide> } <ide> else if (innerWidth == width && innerHeight == height){ <ide> ensureVertices(divisions + 1); <add> ensureIndices(divisions + 1); <ide> if(primitiveType != GL10.GL_LINES) <ide> throw new GdxRuntimeException("Incorrect primitive type : expect GL_LINES because innerWidth == width && innerHeight == height"); <ide> } <ide> else { <del> ensureRectangleIndices(divisions + 1); <add> ensureRectangles((divisions + 1)*2, divisions + 1); <ide> } <ide> <ide> final float ao = MathUtils.degreesToRadians * angleFrom;
Java
mpl-2.0
error: pathspec 'scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java' did not match any file(s) known to git
c67bd421506eedc58fcb6d8e24fd70eae021fc5e
1
JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core,JurassicWordExcel/core
/************************************************************************* * * $RCSfile: PkgProviderBrowseNode.java,v $ * * $Revision: 1.2 $ * * last change: $Author: hr $ $Date: 2004-07-23 13:55:51 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * This library 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 library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ package com.sun.star.script.framework.browse; import com.sun.star.beans.PropertyAttribute; import com.sun.star.lib.uno.helper.PropertySet; import com.sun.star.uno.Any; import com.sun.star.uno.AnyConverter; import com.sun.star.uno.Type; import com.sun.star.uno.XComponentContext; import com.sun.star.beans.XIntrospectionAccess; import com.sun.star.script.XInvocation; import drafts.com.sun.star.script.browse.XBrowseNode; import drafts.com.sun.star.script.browse.BrowseNodeTypes; import com.sun.star.script.framework.provider.ScriptProvider; import com.sun.star.script.framework.log.*; import com.sun.star.script.framework.container.*; import com.sun.star.script.framework.browse.DialogFactory; import java.io.*; import java.util.*; import javax.swing.JOptionPane; public class PkgProviderBrowseNode extends ProviderBrowseNode implements XBrowseNode, XInvocation { public PkgProviderBrowseNode( ScriptProvider provider, ParcelContainer container, XComponentContext xCtx ) { super( provider, container, xCtx ); LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container name = " + container.getName()); LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container path = " + container.getParcelContainerDir()); LogUtils.DEBUG("*** PkgProviderBrowseNode ctor, container has num parcels = " + container.getElementNames().length); deletable = false; editable = false; creatable = false; } public String getName() { String name = "Unknown"; if ( container != null ) { name = container.getName(); } return name; } }
scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java
INTEGRATION: CWS scriptingf7 (1.1.2); FILE ADDED 2004/07/15 09:55:58 npower 1.1.2.2: #i25269# Changes to ProviderBrowseNode so that is doesn't try to get the scriptng context ( this was causing a crash in the cmdline version of pkgchk as it tried to instantiate the desktop component ). Changed the ctor to take XComponentContext, also changed PkgProviderBrowseNode the same way and additionally changed ScriptProvider to use the new ctor. 2004/06/22 07:41:18 npower 1.1.2.1: #i25269# new class support for uno package browsing
scripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java
INTEGRATION: CWS scriptingf7 (1.1.2); FILE ADDED 2004/07/15 09:55:58 npower 1.1.2.2: #i25269# Changes to ProviderBrowseNode so that is doesn't try to get the scriptng context ( this was causing a crash in the cmdline version of pkgchk as it tried to instantiate the desktop component ). Changed the ctor to take XComponentContext, also changed PkgProviderBrowseNode the same way and additionally changed ScriptProvider to use the new ctor. 2004/06/22 07:41:18 npower 1.1.2.1: #i25269# new class support for uno package browsing
<ide><path>cripting/java/com/sun/star/script/framework/browse/PkgProviderBrowseNode.java <add>/************************************************************************* <add> * <add> * $RCSfile: PkgProviderBrowseNode.java,v $ <add> * <add> * $Revision: 1.2 $ <add> * <add> * last change: $Author: hr $ $Date: 2004-07-23 13:55:51 $ <add> * <add> * The Contents of this file are made available subject to the terms of <add> * either of the following licenses <add> * <add> * - GNU Lesser General Public License Version 2.1 <add> * - Sun Industry Standards Source License Version 1.1 <add> * <add> * Sun Microsystems Inc., October, 2000 <add> * <add> * GNU Lesser General Public License Version 2.1 <add> * ============================================= <add> * Copyright 2000 by Sun Microsystems, Inc. <add> * 901 San Antonio Road, Palo Alto, CA 94303, USA <add> * <add> * This library is free software; you can redistribute it and/or <add> * modify it under the terms of the GNU Lesser General Public <add> * License version 2.1, as published by the Free Software Foundation. <add> * <add> * This library is distributed in the hope that it will be useful, <add> * but WITHOUT ANY WARRANTY; without even the implied warranty of <add> * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU <add> * Lesser General Public License for more details. <add> * <add> * You should have received a copy of the GNU Lesser General Public <add> * License along with this library; if not, write to the Free Software <add> * Foundation, Inc., 59 Temple Place, Suite 330, Boston, <add> * MA 02111-1307 USA <add> * <add> * <add> * Sun Industry Standards Source License Version 1.1 <add> * ================================================= <add> * The contents of this file are subject to the Sun Industry Standards <add> * Source License Version 1.1 (the "License"); You may not use this file <add> * except in compliance with the License. You may obtain a copy of the <add> * License at http://www.openoffice.org/license.html. <add> * <add> * Software provided under this License is provided on an "AS IS" basis, <add> * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, <add> * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, <add> * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. <add> * See the License for the specific provisions governing your rights and <add> * obligations concerning the Software. <add> * <add> * The Initial Developer of the Original Code is: Sun Microsystems, Inc. <add> * <add> * Copyright: 2000 by Sun Microsystems, Inc. <add> * <add> * All Rights Reserved. <add> * <add> * Contributor(s): _______________________________________ <add> * <add> * <add> ************************************************************************/ <add> <add>package com.sun.star.script.framework.browse; <add> <add>import com.sun.star.beans.PropertyAttribute; <add>import com.sun.star.lib.uno.helper.PropertySet; <add>import com.sun.star.uno.Any; <add>import com.sun.star.uno.AnyConverter; <add>import com.sun.star.uno.Type; <add>import com.sun.star.uno.XComponentContext; <add> <add>import com.sun.star.beans.XIntrospectionAccess; <add>import com.sun.star.script.XInvocation; <add> <add>import drafts.com.sun.star.script.browse.XBrowseNode; <add>import drafts.com.sun.star.script.browse.BrowseNodeTypes; <add> <add>import com.sun.star.script.framework.provider.ScriptProvider; <add>import com.sun.star.script.framework.log.*; <add>import com.sun.star.script.framework.container.*; <add>import com.sun.star.script.framework.browse.DialogFactory; <add> <add>import java.io.*; <add>import java.util.*; <add>import javax.swing.JOptionPane; <add> <add>public class PkgProviderBrowseNode extends ProviderBrowseNode <add> implements XBrowseNode, XInvocation <add>{ <add> <add> public PkgProviderBrowseNode( ScriptProvider provider, ParcelContainer container, XComponentContext xCtx ) { <add> super( provider, container, xCtx ); <add> LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container name = " + container.getName()); <add> LogUtils.DEBUG("*** PkgProviderBrowseNode ctor container path = " + container.getParcelContainerDir()); <add> LogUtils.DEBUG("*** PkgProviderBrowseNode ctor, container has num parcels = " + container.getElementNames().length); <add> deletable = false; <add> editable = false; <add> creatable = false; <add> <add> } <add> <add> public String getName() { <add> String name = "Unknown"; <add> if ( container != null ) <add> { <add> name = container.getName(); <add> } <add> return name; <add> } <add> <add>}
Java
mit
a22cd20483310fca6730b91c664423c74c049563
0
elBukkit/MagicPlugin,elBukkit/MagicPlugin,elBukkit/MagicPlugin
package com.elmakers.mine.bukkit.wand; import static com.google.common.base.Verify.verifyNotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.block.BrushMode; import com.elmakers.mine.bukkit.api.event.WandPreActivateEvent; import com.elmakers.mine.bukkit.api.magic.MageClassTemplate; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.MagicProperties; import com.elmakers.mine.bukkit.api.magic.MaterialSet; import com.elmakers.mine.bukkit.api.magic.Messages; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellKey; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.api.wand.WandAction; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.effect.EffectPlayer; import com.elmakers.mine.bukkit.effect.SoundEffect; import com.elmakers.mine.bukkit.effect.WandEffectContext; import com.elmakers.mine.bukkit.effect.builtin.EffectRing; import com.elmakers.mine.bukkit.heroes.HeroesManager; import com.elmakers.mine.bukkit.magic.BaseMagicConfigurable; import com.elmakers.mine.bukkit.magic.Mage; import com.elmakers.mine.bukkit.magic.MageClass; import com.elmakers.mine.bukkit.magic.MagicAttribute; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.magic.MagicPropertyType; import com.elmakers.mine.bukkit.utility.ColorHD; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.elmakers.mine.bukkit.utility.NMSUtils; import com.google.common.base.Preconditions; public class Wand extends WandProperties implements CostReducer, com.elmakers.mine.bukkit.api.wand.Wand { public static final int OFFHAND_SLOT = 40; public static final int INVENTORY_SIZE = 27; public static final int PLAYER_INVENTORY_SIZE = 36; public static final int INVENTORY_ORGANIZE_BUFFER = 4; public static final int HOTBAR_SIZE = 9; public static final int HOTBAR_INVENTORY_SIZE = HOTBAR_SIZE - 1; public static final float DEFAULT_SPELL_COLOR_MIX_WEIGHT = 0.0001f; public static boolean FILL_CREATOR = false; public static Vector DEFAULT_CAST_OFFSET = new Vector(0, 0, 0.5); public static String DEFAULT_WAND_TEMPLATE = "default"; private static final String[] EMPTY_PARAMETERS = new String[0]; private static final Random random = new Random(); /** * The item as it appears in the inventory of the player. */ protected @Nullable ItemStack item; /** * The currently active mage. * * <p>Is only set when the wand is active or when the wand is * used for off-hand casting. */ protected @Nullable Mage mage; protected @Nullable WandEffectContext effectContext; // Cached state private String id = ""; private List<Inventory> hotbars; private List<Inventory> inventories; private Map<String, Integer> spellInventory = new HashMap<>(); private Set<String> spells = new LinkedHashSet<>(); private Map<String, Integer> spellLevels = new HashMap<>(); private Map<String, Integer> brushInventory = new HashMap<>(); private Set<String> brushes = new LinkedHashSet<>(); private String activeSpell = ""; private String alternateSpell = ""; private String alternateSpell2 = ""; private String activeBrush = ""; protected String wandName = ""; protected String description = ""; private String owner = ""; private String ownerId = ""; private String template = ""; private String path = ""; private List<String> mageClassKeys = null; private boolean superProtected = false; private boolean superPowered = false; private boolean glow = false; private boolean bound = false; private boolean indestructible = false; private boolean undroppable = false; private boolean keep = false; private boolean passive = false; private boolean autoOrganize = false; private boolean autoAlphabetize = false; private boolean autoFill = false; private boolean isUpgrade = false; private boolean randomizeOnActivate = true; private boolean rename = false; private boolean renameDescription = false; private boolean quickCast = false; private boolean quickCastDisabled = false; private boolean manualQuickCastDisabled = false; private boolean isInOffhand = false; private boolean hasId = false; private int inventoryRows = 1; private Vector castLocation; private WandAction leftClickAction = WandAction.NONE; private WandAction rightClickAction = WandAction.NONE; private WandAction dropAction = WandAction.NONE; private WandAction swapAction = WandAction.NONE; private MaterialAndData icon = null; private MaterialAndData upgradeIcon = null; private MaterialAndData inactiveIcon = null; private int inactiveIconDelay = 0; private String upgradeTemplate = null; protected float consumeReduction = 0; protected float cooldownReduction = 0; protected float costReduction = 0; protected Map<String, Double> protection; private float power = 0; private float spMultiplier = 1; private float blockFOV = 0; private float blockChance = 0; private float blockReflectChance = 0; private int blockMageCooldown = 0; private int blockCooldown = 0; private int maxEnchantCount = 0; private int enchantCount = 0; private boolean hasInventory = false; private boolean locked = false; private boolean lockedAllowUpgrades = false; private boolean forceUpgrade = false; private boolean isHeroes = false; private int uses = 0; private boolean hasUses = false; private boolean isSingleUse = false; private boolean limitSpellsToPath = false; private boolean limitBrushesToPath = false; private float manaPerDamage = 0; private ColorHD effectColor = null; private float effectColorSpellMixWeight = DEFAULT_SPELL_COLOR_MIX_WEIGHT; private Particle effectParticle = null; private float effectParticleData = 0; private int effectParticleCount = 0; private int effectParticleInterval = 0; private double effectParticleMinVelocity = 0; private double effectParticleRadius = 0; private double effectParticleOffset = 0; private boolean effectBubbles = false; private boolean activeEffectsOnly = false; private EffectRing effectPlayer = null; private int castInterval = 0; private double castMinVelocity = 0; private Vector castVelocityDirection = null; private String castSpell = null; private ConfigurationSection castParameters = null; private Map<PotionEffectType, Integer> potionEffects = new HashMap<>(); private SoundEffect effectSound = null; private int effectSoundInterval = 0; private int quietLevel = 0; private Map<String, String> castOverrides = null; // Transient state private boolean hasSpellProgression = false; private long lastSoundEffect; private long lastParticleEffect; private long lastSpellCast; // Inventory functionality private WandMode mode = null; private WandMode brushMode = null; private int openInventoryPage = 0; private boolean inventoryIsOpen = false; private boolean inventoryWasOpen = false; private Inventory displayInventory = null; private int currentHotbar = 0; public static WandManaMode manaMode = WandManaMode.BAR; public static WandManaMode spMode = WandManaMode.NUMBER; public static boolean regenWhileInactive = true; public static Material DefaultUpgradeMaterial = Material.NETHER_STAR; public static Material DefaultWandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = null; public static boolean SpellGlow = false; public static boolean BrushGlow = false; public static boolean BrushItemGlow = true; public static boolean LiveHotbar = true; public static boolean LiveHotbarSkills = false; public static boolean LiveHotbarCooldown = true; public static boolean Unbreakable = false; public static boolean Unstashable = true; public static SoundEffect inventoryOpenSound = null; public static SoundEffect inventoryCloseSound = null; public static SoundEffect inventoryCycleSound = null; public static SoundEffect noActionSound = null; public static String WAND_KEY = "wand"; public static String UPGRADE_KEY = "wand_upgrade"; public static String WAND_SELF_DESTRUCT_KEY = null; public static byte HIDE_FLAGS = 63; public static String brushSelectSpell = ""; private Inventory storedInventory = null; private int heldSlot = 0; public Wand(MagicController controller) { super(controller); hotbars = new ArrayList<>(); inventories = new ArrayList<>(); } /** * @deprecated Use {@link MagicController#getWand(ItemStack)}. */ @Deprecated public Wand(MagicController controller, ItemStack itemStack) { this(controller); Preconditions.checkNotNull(itemStack); if (itemStack.getType() == Material.AIR) { itemStack.setType(DefaultWandMaterial); } this.icon = new MaterialAndData(itemStack); item = itemStack; boolean needsSave = false; boolean isWand = isWand(item); boolean isUpgradeItem = isUpgrade(item); if (isWand || isUpgradeItem) { ConfigurationSection wandConfig = itemToConfig(item, new MemoryConfiguration()); // Check for template migration WandTemplate wandTemplate = controller.getWandTemplate(wandConfig.getString("template")); WandTemplate migrateTemplate = wandTemplate == null ? null : wandTemplate.getMigrateTemplate(); if (migrateTemplate != null) { wandConfig.set("template", migrateTemplate.getKey()); } // Check for wand data migration int version = wandConfig.getInt("version", 0); if (version < CURRENT_VERSION) { // Migration will be handled by CasterProperties, this is just here // So that we save the data after to avoid re-migrating. needsSave = true; } randomizeOnActivate = !wandConfig.contains("icon"); load(wandConfig); } else { updateIcon(); needsSave = true; } loadProperties(); // Migrate old upgrade items if ((isUpgrade || isUpgradeItem) && isWand) { needsSave = true; InventoryUtils.removeMeta(item, WAND_KEY); } if (needsSave) { saveState(); updateName(); updateLore(); } } public Wand(MagicController controller, ConfigurationSection config) { this(controller, DefaultWandMaterial, (short)0); load(config); loadProperties(); updateName(); updateLore(); saveState(); } protected Wand(MagicController controller, String templateName) throws UnknownWandException { this(controller); // Default to "default" wand if (templateName == null || templateName.length() == 0) { templateName = DEFAULT_WAND_TEMPLATE; } // Check for randomized/pre-enchanted wands int level = 0; if (templateName.contains("(")) { String levelString = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); try { level = Integer.parseInt(levelString); } catch (Exception ex) { throw new IllegalArgumentException(ex); } templateName = templateName.substring(0, templateName.indexOf('(')); } WandTemplate template = controller.getWandTemplate(templateName); if (template == null) { throw new UnknownWandException(templateName); } WandTemplate migrateTemplate = template.getMigrateTemplate(); if (migrateTemplate != null) { template = migrateTemplate; templateName = migrateTemplate.getKey(); } setTemplate(templateName); setProperty("version", CURRENT_VERSION); ConfigurationSection templateConfig = template.getConfiguration(); if (templateConfig == null) { throw new UnknownWandException(templateName); } // Load all properties loadProperties(); // Enchant, if an enchanting level was provided if (level > 0) { // Account for randomized locked wands boolean wasLocked = locked; locked = false; randomize(level, false, null, true); locked = wasLocked; } // Don't randomize now if set to randomize later // Otherwise, do this here so the description updates if (!randomizeOnActivate) { randomize(); } updateName(); updateLore(); saveState(); } public Wand(MagicController controller, Material icon, short iconData) { // This will make the Bukkit ItemStack into a real ItemStack with NBT data. this(controller, InventoryUtils.makeReal(new ItemStack(icon, 1, iconData))); saveState(); updateName(); } @Override @SuppressWarnings("unchecked") protected void migrate(int version, ConfigurationSection wandConfig) { // First migration, clean out wand data that matches template // We've done this twice now, the second time to handle removing hard-coded defaults that // were not present in the template configs. if (version <= 1) { ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(wandConfig.getString("template")); if (templateConfig != null) { // This is an unfortunate special case for wands waiting to be randomized String randomizeIcon = templateConfig.getString("randomize_icon"); String currentIcon = wandConfig.getString("icon"); if (randomizeIcon != null && currentIcon != null && randomizeIcon.equals(currentIcon)) { wandConfig.set("icon", null); } // This was a potentially leftover property from randomized wands we can ditch wandConfig.set("randomize", null); Set<String> keys = templateConfig.getKeys(false); for (String key : keys) { Object templateData = templateConfig.get(key); Object wandData = wandConfig.get(key); if (wandData == null) continue; String templateString = templateData.toString(); String wandString = wandData.toString(); if (templateData instanceof List) { templateString = templateString.substring(1, templateString.length() - 1); templateString = templateString.replace(", ", ","); templateData = templateString; } if (wandString.equalsIgnoreCase(templateString)) { wandConfig.set(key, null); continue; } try { double numericValue = Double.parseDouble(wandString); double numericTemplate = Double.parseDouble(templateString); if (numericValue == numericTemplate) { wandConfig.set(key, null); continue; } } catch (NumberFormatException ignored) { } if (wandData.equals(templateData)) { wandConfig.set(key, null); } } } } // Remove icon if matches template if (version <= 3) { ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(wandConfig.getString("template")); String templateIcon = templateConfig == null ? null : templateConfig.getString("icon"); if (templateIcon != null && templateIcon.equals(wandConfig.getString("icon", ""))) { wandConfig.set("icon", null); } } // Migration: remove level from spell inventory if (version <= 4) { Object spellInventoryRaw = wandConfig.get("spell_inventory"); if (spellInventoryRaw != null) { Map<String, ? extends Object> spellInventory = null; Map<String, Integer> newSpellInventory = new HashMap<>(); if (spellInventoryRaw instanceof Map) { spellInventory = (Map<String, ? extends Object>)spellInventoryRaw; } else if (spellInventoryRaw instanceof ConfigurationSection) { spellInventory = NMSUtils.getMap((ConfigurationSection)spellInventoryRaw); } if (spellInventory != null) { for (Map.Entry<String, ? extends Object> spellEntry : spellInventory.entrySet()) { Object slot = spellEntry.getValue(); if (slot != null && slot instanceof Integer) { SpellKey spellKey = new SpellKey(spellEntry.getKey()); // Prefer to use the base spell if present since that is what we'd be // using on load. Object testSlot = spellInventory.get(spellKey.getBaseKey()); if (testSlot != null) { slot = testSlot; } newSpellInventory.put(spellKey.getBaseKey(), (Integer)slot); } } wandConfig.set("spell_inventory", newSpellInventory); } } } // Migration: move attributes to item_attributes if (version <= 5) { ConfigurationSection attributes = wandConfig.getConfigurationSection("attributes"); wandConfig.set("attributes", null); wandConfig.set("item_attributes", attributes); } super.migrate(version, wandConfig); } @Override public void load(ConfigurationSection configuration) { if (configuration != null) { setTemplate(configuration.getString("template")); } super.load(configuration); } protected void updateHotbarCount() { int hotbarCount = Math.max(1, getInt("hotbar_count", 1)); if (hotbarCount != hotbars.size()) { if (isInventoryOpen()) { closeInventory(); } hotbars.clear(); while (hotbars.size() < hotbarCount) { hotbars.add(CompatibilityUtils.createInventory(null, HOTBAR_INVENTORY_SIZE, "Wand")); } while (hotbars.size() > hotbarCount) { hotbars.remove(0); } } } @Override public void unenchant() { controller.cleanItem(item); clear(); } public void updateItemIcon() { setIcon(icon); } protected void updateIcon() { if (icon != null && icon.getMaterial() != null && icon.getMaterial() != Material.AIR) { String iconKey = icon.getKey(); if (iconKey != null && iconKey.isEmpty()) { iconKey = null; } WandTemplate template = getTemplate(); String templateIcon = template != null ? template.getProperty("icon", "") : null; if (templateIcon == null || !templateIcon.equals(iconKey)) { setProperty("icon", iconKey); } } } @Override public void setInactiveIcon(com.elmakers.mine.bukkit.api.block.MaterialAndData materialData) { if (materialData == null) { inactiveIcon = null; } else if (materialData instanceof MaterialAndData) { inactiveIcon = ((MaterialAndData)materialData); } else { inactiveIcon = new MaterialAndData(materialData); } String inactiveIconKey = null; if (inactiveIcon != null && inactiveIcon.getMaterial() != null && inactiveIcon.getMaterial() != Material.AIR) { inactiveIconKey = inactiveIcon.getKey(); if (inactiveIconKey != null && inactiveIconKey.isEmpty()) { inactiveIconKey = null; } } setProperty("inactive_icon", inactiveIconKey); updateItemIcon(); } public void setIcon(Material material, byte data) { setIcon(material == null ? null : new MaterialAndData(material, data)); updateIcon(); } @Override public void setIcon(com.elmakers.mine.bukkit.api.block.MaterialAndData materialData) { if (materialData instanceof MaterialAndData) { setIcon((MaterialAndData)materialData); } else { setIcon(new MaterialAndData(materialData)); } updateIcon(); } public void setIcon(MaterialAndData materialData) { if (materialData == null || !materialData.isValid()) return; if (materialData.getMaterial() == Material.AIR || materialData.getMaterial() == null) { materialData.setMaterial(DefaultWandMaterial); } icon = materialData; if (item == null) { item = InventoryUtils.makeReal(this.icon.getItemStack(1)); } Short durability = null; if (!indestructible && !isUpgrade && icon.getMaterial().getMaxDurability() > 0) { durability = item.getDurability(); } try { if (inactiveIcon == null || (mage != null && getMode() == WandMode.INVENTORY && isInventoryOpen())) { icon.applyToItem(item); } else { inactiveIcon.applyToItem(item); } } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Unable to apply wand icon", ex); item.setType(DefaultWandMaterial); } if (durability != null) { item.setDurability(durability); } // Make indestructible // The isUpgrade checks here and above are for using custom icons in 1.9, this is a bit hacky. if ((indestructible || Unbreakable || isUpgrade) && !manaMode.useDurability()) { CompatibilityUtils.makeUnbreakable(item); } else { CompatibilityUtils.removeUnbreakable(item); } CompatibilityUtils.hideFlags(item, getProperty("hide_flags", HIDE_FLAGS)); } @Override public void makeUpgrade() { if (!isUpgrade) { isUpgrade = true; String oldName = wandName; String newName = getMessage("upgrade_name"); newName = newName.replace("$name", oldName); String newDescription = controller.getMessages().get("wand.upgrade_default_description"); if (template != null && template.length() > 0) { newDescription = controller.getMessages().get("wands." + template + ".upgrade_description", description); } setIcon(DefaultUpgradeMaterial, (byte) 0); setName(newName); setDescription(newDescription); InventoryUtils.removeMeta(item, WAND_KEY); saveState(); updateName(true); updateLore(); } } public void newId() { id = UUID.randomUUID().toString(); setProperty("id", id); } public boolean checkId() { if (id == null || id.length() == 0) { newId(); return true; } return false; } @Override public String getId() { return id; } public boolean isModifiable() { return !locked; } @Override public boolean isIndestructible() { return indestructible; } @Override public boolean isUndroppable() { return undroppable; } public boolean isUpgrade() { return isUpgrade; } public static boolean isUpgrade(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, UPGRADE_KEY); } @Override public boolean usesMana() { if (isCostFree()) return false; return getManaMax() > 0 || (isHeroes && mage != null); } @Override public void removeMana(float amount) { if (isHeroes && mage != null) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { heroes.removeMana(mage.getPlayer(), (int)Math.ceil(amount)); } } super.removeMana(amount); updateMana(); } @Override public float getCostReduction() { if (mage != null) { float reduction = mage.getCostReduction(); return passive ? reduction : stackPassiveProperty(reduction, costReduction); } return costReduction; } @Override public float getCooldownReduction() { if (mage != null) { float reduction = mage.getCooldownReduction(); return passive ? reduction : stackPassiveProperty(reduction, cooldownReduction); } return cooldownReduction; } @Override public float getConsumeReduction() { if (mage != null) { float reduction = mage.getConsumeReduction(); return passive ? reduction : stackPassiveProperty(reduction, consumeReduction); } return consumeReduction; } @Override public float getCostScale() { return 1; } @Override public boolean hasInventory() { return hasInventory; } @Override public float getPower() { return power; } @Override public boolean isSuperProtected() { return superProtected; } @Override public boolean isSuperPowered() { return superPowered; } @Override public boolean isConsumeFree() { return consumeReduction >= 1; } @Override public boolean isCooldownFree() { return cooldownReduction > 1; } @Override public String getName() { return ChatColor.translateAlternateColorCodes('&', wandName); } public String getDescription() { return description; } public String getOwner() { return owner == null ? "" : owner; } public String getOwnerId() { return ownerId; } @Override public long getWorth() { long worth = 0; // TODO: Item properties, brushes, etc Set<String> spells = getSpells(); for (String spellKey : spells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) { worth = (long)(worth + spell.getWorth()); } } return worth; } @Override public void setName(String name) { wandName = ChatColor.stripColor(name); setProperty("name", wandName); updateName(); } public void setTemplate(String templateName) { this.template = templateName; WandTemplate wandTemplate = controller.getWandTemplate(templateName); if (wandTemplate != null) { setWandTemplate(wandTemplate); } setProperty("template", template); } @Override public String getTemplateKey() { return this.template; } @Override public boolean hasTag(String tag) { WandTemplate template = getTemplate(); return template != null && template.hasTag(tag); } @Override public WandUpgradePath getPath() { String pathKey = path; if (pathKey == null || pathKey.length() == 0) { pathKey = controller.getDefaultWandPath(); } return WandUpgradePath.getPath(pathKey); } public boolean hasPath() { return path != null && path.length() > 0; } @Override public void setDescription(String description) { this.description = description; setProperty("description", description); updateLore(); } public boolean tryToOwn(Player player) { if (ownerId == null || ownerId.length() == 0) { takeOwnership(player); return true; } return false; } public void takeOwnership(Player player) { Mage mage = this.mage; if (mage == null) { mage = controller.getMage(player); } if ((ownerId == null || ownerId.length() == 0) && quietLevel < 2) { mage.sendMessage(getMessage("bound_instructions", "").replace("$wand", getName())); String spellKey = getActiveSpellKey(); SpellTemplate spellTemplate = spellKey != null && !spellKey.isEmpty() ? controller.getSpellTemplate(spellKey) : null; if (spellTemplate != null) { String message = getMessage("spell_instructions", "").replace("$wand", getName()); mage.sendMessage(message.replace("$spell", spellTemplate.getName())); } if (spells.size() > 1) { String controlKey = getControlKey(WandAction.TOGGLE); if (controlKey != null) { controlKey = controller.getMessages().get("controls." + controlKey); mage.sendMessage(getMessage("inventory_instructions", "") .replace("$wand", getName()).replace("$toggle", controlKey)); } } com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); if (path != null) { String message = getMessage("enchant_instructions", "").replace("$wand", getName()); mage.sendMessage(message); } } owner = ChatColor.stripColor(player.getDisplayName()); ownerId = mage.getId(); setProperty("owner", owner); setProperty("owner_id", ownerId); updateLore(); saveState(); } @Nullable public String getControlKey(WandAction action) { String controlKey = null; if (rightClickAction == action) { controlKey = "right_click"; } else if (dropAction == action) { controlKey = "drop"; } else if (leftClickAction == action) { controlKey = "left_click"; } else if (swapAction == action) { controlKey = "swap"; } return controlKey; } @Nullable @Override public ItemStack getItem() { return item; } public void setItem(ItemStack item) { this.item = item; } @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getIcon() { return icon; } @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getInactiveIcon() { return inactiveIcon; } protected List<Inventory> getAllInventories() { int hotbarCount = getHotbarCount(); List<Inventory> allInventories = new ArrayList<>(inventories.size() + hotbarCount); if (hotbarCount > 0) { allInventories.addAll(hotbars); } allInventories.addAll(inventories); return allInventories; } @Override public Set<String> getBaseSpells() { return spells; } @Override protected @Nonnull Map<String, Integer> getSpellLevels() { return spellLevels; } @Override public Set<String> getSpells() { Set<String> spellSet = new HashSet<>(); for (String key : spells) { Integer level = spellLevels.get(key); if (level != null) { spellSet.add(new SpellKey(key, level).getKey()); } else { spellSet.add(key); } } return spellSet; } @Override public Set<String> getBrushes() { return brushes; } @Nullable protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 1) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } public void addToInventory(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) { return; } if (getBrushMode() != WandMode.INVENTORY && isBrush(itemStack)) { String brushKey = getBrush(itemStack); if (!MaterialBrush.isSpecialMaterialKey(brushKey) || MaterialBrush.isSchematic(brushKey)) { return; } } List<Inventory> checkInventories = getAllInventories(); boolean added = false; WandMode mode = getMode(); int fullSlot = 0; for (Inventory inventory : checkInventories) { int inventorySize = inventory.getSize(); Integer slot = null; int freeSpace = 0; for (int i = 0; i < inventorySize && freeSpace < INVENTORY_ORGANIZE_BUFFER; i++) { ItemStack existing = inventory.getItem(i); if (InventoryUtils.isEmpty(existing)) { if (slot == null) { slot = i; } freeSpace++; } } // Don't leave free space in hotbars if (slot != null && (freeSpace >= INVENTORY_ORGANIZE_BUFFER || inventorySize == HOTBAR_INVENTORY_SIZE || mode == WandMode.CHEST)) { added = true; inventory.setItem(slot, itemStack); fullSlot += slot; break; } fullSlot += inventory.getSize(); } if (!added) { fullSlot = getHotbarSize() + getInventorySize() * inventories.size(); Inventory newInventory = CompatibilityUtils.createInventory(null, getInventorySize(), "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } updateSlot(fullSlot, itemStack); } protected @Nonnull Inventory getInventoryByIndex(int inventoryIndex) { // Auto create while (inventoryIndex >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, getInventorySize(), "Wand")); } return inventories.get(inventoryIndex); } protected int getHotbarSize() { if (getMode() != WandMode.INVENTORY) return 0; return hotbars.size() * HOTBAR_INVENTORY_SIZE; } protected @Nonnull Inventory getInventory(int slot) { int hotbarSize = getHotbarSize(); if (slot < hotbarSize) { return hotbars.get(slot / HOTBAR_INVENTORY_SIZE); } int inventoryIndex = (slot - hotbarSize) / getInventorySize(); return getInventoryByIndex(inventoryIndex); } protected int getInventorySlot(int slot) { int hotbarSize = getHotbarSize(); if (slot < hotbarSize) { return slot % HOTBAR_INVENTORY_SIZE; } return ((slot - hotbarSize) % getInventorySize()); } protected void buildInventory() { // Force an update of the display inventory since chest mode is a different size displayInventory = null; updateHotbarCount(); for (Inventory hotbar : hotbars) { hotbar.clear(); } inventories.clear(); List<ItemStack> unsorted = new ArrayList<>(); for (String key : spells) { int spellLevel = getSpellLevel(key); SpellKey spellKey = new SpellKey(key, spellLevel); SpellTemplate spell = controller.getSpellTemplate(spellKey.getKey()); ItemStack itemStack = createSpellItem(spell, "", controller, getActiveMage(), this, false); if (itemStack != null) { Integer slot = spellInventory.get(spell.getSpellKey().getBaseKey()); if (slot == null) { unsorted.add(itemStack); } else { addToInventory(itemStack, slot); } } } WandMode brushMode = getBrushMode(); for (String brushKey : brushes) { boolean addToInventory = brushMode == WandMode.INVENTORY || (MaterialBrush.isSpecialMaterialKey(brushKey) && !MaterialBrush.isSchematic(brushKey)); if (addToInventory) { ItemStack itemStack = createBrushIcon(brushKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create brush icon for key " + brushKey); continue; } Integer slot = brushInventory.get(brushKey); if (activeBrush == null || activeBrush.length() == 0) activeBrush = brushKey; addToInventory(itemStack, slot); } } for (ItemStack unsortedItem : unsorted) { addToInventory(unsortedItem); } updateHasInventory(); if (openInventoryPage >= inventories.size() && openInventoryPage != 0 && hasInventory) { setOpenInventoryPage(0); } } protected void parseSpells(String spellString) { // Support YML-List-As-String format // Maybe don't need this anymore since loading lists is now a separate path spellString = spellString.replaceAll("[\\]\\[]", ""); String[] spellNames = StringUtils.split(spellString, ','); loadSpells(Arrays.asList(spellNames)); } protected void clearSpells() { spellLevels.clear(); spells.clear(); } protected void loadSpells(Collection<String> spellKeys) { clearSpells(); WandUpgradePath path = getPath(); for (String spellName : spellKeys) { String[] pieces = StringUtils.split(spellName, '@'); Integer slot = parseSlot(pieces); // Handle aliases and upgrades smoothly String loadedKey = pieces[0].trim(); SpellKey spellKey = new SpellKey(loadedKey); SpellTemplate spell = controller.getSpellTemplate(loadedKey); if (limitSpellsToPath && path != null && !path.containsSpell(spellKey.getBaseKey())) continue; // Downgrade spells if higher levels have gone missing while (spell == null && spellKey.getLevel() > 0) { spellKey = new SpellKey(spellKey.getBaseKey(), spellKey.getLevel() - 1); spell = controller.getSpellTemplate(spellKey.getKey()); } if (spell != null) { spellKey = spell.getSpellKey(); Integer currentLevel = spellLevels.get(spellKey.getBaseKey()); if (spellKey.getLevel() > 1 && (currentLevel == null || currentLevel < spellKey.getLevel())) { setSpellLevel(spellKey.getBaseKey(), spellKey.getLevel()); } if (slot != null) { spellInventory.put(spellKey.getBaseKey(), slot); } spells.add(spellKey.getBaseKey()); if (activeSpell == null || activeSpell.length() == 0) { activeSpell = spellKey.getBaseKey(); } } } } private void loadSpells() { Object wandSpells = getObject("spells"); if (wandSpells != null) { if (wandSpells instanceof String) { parseSpells((String)wandSpells); } else if (wandSpells instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> spellList = (Collection<String>)wandSpells; loadSpells(spellList); } else { clearSpells(); } } else { clearSpells(); } } protected void parseBrushes(String brushString) { // Support YML-List-As-String format // Maybe don't need this anymore since loading lists is now a separate path brushString = brushString.replaceAll("[\\]\\[]", ""); String[] brushNames = StringUtils.split(brushString, ','); loadBrushes(Arrays.asList(brushNames)); } protected void clearBrushes() { brushes.clear(); } protected void loadBrushes(Collection<String> brushKeys) { WandUpgradePath path = getPath(); clearBrushes(); for (String materialName : brushKeys) { String[] pieces = StringUtils.split(materialName, '@'); Integer slot = parseSlot(pieces); String materialKey = pieces[0].trim(); if (limitBrushesToPath && path != null && !path.containsBrush(materialKey)) continue; if (slot != null) { brushInventory.put(materialKey, slot); } brushes.add(materialKey); } } private void loadBrushes() { Object wandBrushes = getObject("brushes", getObject("materials")); if (wandBrushes != null) { if (wandBrushes instanceof String) { parseBrushes((String)wandBrushes); } else if (wandBrushes instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> brushList = (Collection<String>)wandBrushes; loadBrushes(brushList); } else { clearBrushes(); } } else { clearBrushes(); } } protected void loadBrushInventory(Map<String, ? extends Object> inventory) { if (inventory == null) return; WandUpgradePath path = getPath(); for (Map.Entry<String, ?> brushEntry : inventory.entrySet()) { Object slot = brushEntry.getValue(); String brushKey = brushEntry.getKey(); if (limitBrushesToPath && path != null && !path.containsBrush(brushKey)) continue; if (slot != null && slot instanceof Integer) { brushInventory.put(brushKey, (Integer)slot); } } } protected void loadSpellInventory(Map<String, ? extends Object> inventory) { if (inventory == null) return; WandUpgradePath path = getPath(); for (Map.Entry<String, ? extends Object> spellEntry : inventory.entrySet()) { String spellKey = spellEntry.getKey(); if (limitSpellsToPath && path != null && !path.containsSpell(spellKey)) continue; Object slot = spellEntry.getValue(); if (slot != null && slot instanceof Integer) { spellInventory.put(spellKey, (Integer)slot); } } } protected void loadSpellLevels(Map<String, ? extends Object> levels) { if (levels == null) return; for (Map.Entry<String, ? extends Object> spellEntry : levels.entrySet()) { Object level = spellEntry.getValue(); if (level != null && level instanceof Integer) { setSpellLevel(spellEntry.getKey(), (Integer)level); } } } @Nullable protected ItemStack createSpellIcon(SpellTemplate spell) { return createSpellItem(spell, "", controller, getActiveMage(), this, false); } @Nullable public static ItemStack createSpellItem(String spellKey, MagicController controller, Wand wand, boolean isItem) { String[] split = spellKey.split(" ", 2); return createSpellItem(controller.getSpellTemplate(split[0]), split.length > 1 ? split[1] : "", controller, wand == null ? null : wand.getActiveMage(), wand, isItem); } @Nullable public static ItemStack createSpellItem(String spellKey, MagicController controller, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, boolean isItem) { String[] split = spellKey.split(" ", 2); return createSpellItem(controller.getSpellTemplate(split[0]), split.length > 1 ? split[1] : "", controller, mage, wand, isItem); } @Nullable public static ItemStack createSpellItem(SpellTemplate spell, String args, MagicController controller, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, boolean isItem) { if (spell == null) return null; String iconURL = spell.getIconURL(); ItemStack itemStack = null; if (iconURL != null && (controller.isUrlIconsEnabled() || spell.getIcon() == null || !spell.getIcon().isValid() || spell.getIcon().getMaterial() == Material.AIR)) { itemStack = controller.getURLSkull(iconURL); } if (itemStack == null) { ItemStack originalItemStack = null; com.elmakers.mine.bukkit.api.block.MaterialAndData icon = spell.getIcon(); if (icon == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); return null; } try { originalItemStack = new ItemStack(icon.getMaterial(), 1, icon.getData()); itemStack = InventoryUtils.makeReal(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { if (icon.getMaterial() != Material.AIR) { String iconName = icon.getName(); controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getKey() + " with material " + iconName); } return originalItemStack; } } InventoryUtils.makeUnbreakable(itemStack); InventoryUtils.hideFlags(itemStack, (byte)63); updateSpellItem(controller.getMessages(), itemStack, spell, args, mage, wand, wand == null ? null : wand.activeBrush, isItem); if (wand != null && wand.getMode() == WandMode.SKILLS && !isItem) { String mageClassKey = wand.getMageClassKey(); ConfigurationSection skillsConfig = wand.getConfigurationSection("skills"); InventoryUtils.configureSkillItem(itemStack, mageClassKey, skillsConfig); } return itemStack; } @Nullable protected ItemStack createBrushIcon(String materialKey) { return createBrushItem(materialKey, controller, this, false); } @Nullable public static ItemStack createBrushItem(String materialKey, com.elmakers.mine.bukkit.api.magic.MageController controller, Wand wand, boolean isItem) { MaterialBrush brushData = MaterialBrush.parseMaterialKey(materialKey); if (brushData == null) return null; ItemStack itemStack = brushData.getItem(controller, isItem); if (BrushGlow || (isItem && BrushItemGlow)) { CompatibilityUtils.addGlow(itemStack); } InventoryUtils.makeUnbreakable(itemStack); InventoryUtils.hideFlags(itemStack, (byte)63); updateBrushItem(controller.getMessages(), itemStack, brushData, wand); return itemStack; } protected boolean findItem() { if (mage != null && item != null) { Player player = mage.getPlayer(); if (player != null) { ItemStack itemInHand = player.getInventory().getItemInMainHand(); if (itemInHand != null && !InventoryUtils.isSameInstance(itemInHand, item) && itemInHand.equals(item)) { item = itemInHand; isInOffhand = false; return true; } itemInHand = player.getInventory().getItemInOffHand(); if (itemInHand != null && !InventoryUtils.isSameInstance(itemInHand, item) && itemInHand.equals(item)) { item = itemInHand; isInOffhand = true; return true; } itemInHand = player.getInventory().getItem(heldSlot); if (itemInHand != null && !InventoryUtils.isSameInstance(itemInHand, item) && itemInHand.equals(item)) { item = itemInHand; isInOffhand = true; return true; } } } return false; } @Override public void saveState() { // Make sure we're on the current item instance if (findItem()) { updateItemIcon(); updateName(); updateLore(); } if (item == null || item.getType() == Material.AIR) return; // Check for upgrades that still have wand data if (isUpgrade && isWand(item)) { InventoryUtils.removeMeta(item, WAND_KEY); } Object wandNode = InventoryUtils.createNode(item, isUpgrade ? UPGRADE_KEY : WAND_KEY); if (wandNode == null) { controller.getLogger().warning("Failed to save wand state for wand to : " + item); } else { InventoryUtils.saveTagsToNBT(getConfiguration(), wandNode); } } @Nullable public static ConfigurationSection itemToConfig(ItemStack item, ConfigurationSection stateNode) { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) { wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); if (wandNode == null) { return null; } } ConfigurationUtils.loadAllTagsFromNBT(stateNode, wandNode); return stateNode; } public static void configToItem(ConfigurationSection itemSection, ItemStack item) { ConfigurationSection stateNode = itemSection.getConfigurationSection("wand"); Object wandNode = InventoryUtils.createNode(item, Wand.WAND_KEY); if (wandNode != null) { InventoryUtils.saveTagsToNBT(stateNode, wandNode); } } @Nullable protected String getPotionEffectString() { return getPotionEffectString(potionEffects); } @Override public void save(ConfigurationSection node, boolean filtered) { ConfigurationUtils.addConfigurations(node, getConfiguration()); // Filter out some fields if (filtered) { node.set("id", null); node.set("owner_id", null); node.set("owner", null); node.set("template", null); node.set("mana_timestamp", null); node.set("enchant_count", null); } if (isUpgrade) { node.set("upgrade", true); } if (template != null && !template.isEmpty()) { node.set("template", null); node.set("inherit", template); } } public void save() { saveState(); updateName(); updateLore(); } public void updateBrushInventory() { if (brushInventory.isEmpty()) { setProperty("brush_inventory", null); } else { setProperty("brush_inventory", new HashMap<>(brushInventory)); } } protected void updateBrushInventory(Map<String, Integer> updateBrushes) { for (Map.Entry<String, Integer> brushEntry : brushInventory.entrySet()) { String brushKey = brushEntry.getKey(); Integer slot = updateBrushes.get(brushKey); if (slot != null) { brushEntry.setValue(slot); } } } public void updateSpellInventory() { if (spellInventory.isEmpty()) { setProperty("spell_inventory", null); } else { setProperty("spell_inventory", new HashMap<>(spellInventory)); } } protected void updateSpellInventory(Map<String, Integer> updateSpells) { for (Map.Entry<String, Integer> spellEntry : spellInventory.entrySet()) { String spellKey = spellEntry.getKey(); Integer slot = updateSpells.get(spellKey); if (slot != null) { spellEntry.setValue(slot); } } } public void setEffectColor(String hexColor) { // Annoying config conversion issue :\ if (hexColor.contains(".")) { hexColor = hexColor.substring(0, hexColor.indexOf('.')); } if (hexColor == null || hexColor.length() == 0 || hexColor.equals("none")) { effectColor = null; return; } effectColor = new ColorHD(hexColor); if (hexColor.equals("random")) { setProperty("effect_color", effectColor.toString()); } } private void migrateProtection(String legacy, String migrateTo) { if (hasProperty(legacy)) { double protection = getDouble(legacy); clearProperty(legacy); setProperty("protection." + migrateTo, protection); } } @Override public void loadProperties() { super.loadProperties(); locked = getBoolean("locked", locked); lockedAllowUpgrades = getBoolean("locked_allow_upgrades", false); consumeReduction = getFloat("consume_reduction"); cooldownReduction = getFloat("cooldown_reduction"); costReduction = getFloat("cost_reduction"); power = getFloat("power"); ConfigurationSection protectionConfig = getConfigurationSection("protection"); if (protectionConfig == null && hasProperty("protection")) { migrateProtection("protection", "overall"); migrateProtection("protection_physical", "physical"); migrateProtection("protection_projectiles", "projectile"); migrateProtection("protection_falling", "fall"); migrateProtection("protection_fire", "fire"); migrateProtection("protection_explosions", "explosion"); protectionConfig = getConfigurationSection("protection"); } if (protectionConfig != null) { protection = new HashMap<>(); for (String protectionKey : protectionConfig.getKeys(false)) { protection.put(protectionKey, protectionConfig.getDouble(protectionKey)); } } hasId = getBoolean("unique", false); blockChance = getFloat("block_chance"); blockReflectChance = getFloat("block_reflect_chance"); blockFOV = getFloat("block_fov"); blockMageCooldown = getInt("block_mage_cooldown"); blockCooldown = getInt("block_cooldown"); manaPerDamage = getFloat("mana_per_damage"); spMultiplier = getFloat("sp_multiplier", 1); String singleClass = getString("class"); if (singleClass != null && !singleClass.isEmpty()) { mageClassKeys = new ArrayList<>(); mageClassKeys.add(singleClass); } else { mageClassKeys = getStringList("classes"); } // Check for single-use wands uses = getInt("uses"); hasUses = uses > 0; // Convert some legacy properties to potion effects float healthRegeneration = getFloat("health_regeneration", 0); float hungerRegeneration = getFloat("hunger_regeneration", 0); float speedIncrease = getFloat("haste", 0); if (speedIncrease > 0) { potionEffects.put(PotionEffectType.SPEED, 1); } if (healthRegeneration > 0) { potionEffects.put(PotionEffectType.REGENERATION, 1); } if (hungerRegeneration > 0) { potionEffects.put(PotionEffectType.SATURATION, 1); } // This overrides the value loaded in CasterProperties if (!regenWhileInactive) { setProperty("mana_timestamp", System.currentTimeMillis()); } if (hasProperty("effect_color")) { setEffectColor(getString("effect_color")); } id = getString("id"); isUpgrade = getBoolean("upgrade"); quietLevel = getInt("quiet"); effectBubbles = getBoolean("effect_bubbles"); keep = getBoolean("keep"); passive = getBoolean("passive"); indestructible = getBoolean("indestructible"); superPowered = getBoolean("powered"); superProtected = getBoolean("protected"); glow = getBoolean("glow"); undroppable = getBoolean("undroppable"); isHeroes = getBoolean("heroes"); bound = getBoolean("bound"); forceUpgrade = getBoolean("force"); autoOrganize = getBoolean("organize"); autoAlphabetize = getBoolean("alphabetize"); autoFill = getBoolean("fill"); rename = getBoolean("rename"); renameDescription = getBoolean("rename_description"); enchantCount = getInt("enchant_count"); maxEnchantCount = getInt("max_enchant_count"); inventoryRows = getInt("inventory_rows", 5); if (inventoryRows <= 0) inventoryRows = 1; if (hasProperty("effect_particle")) { effectParticle = ConfigurationUtils.toParticleEffect(getString("effect_particle")); effectParticleData = 0; } else { effectParticle = null; } if (hasProperty("effect_sound")) { effectSound = ConfigurationUtils.toSoundEffect(getString("effect_sound")); } else { effectSound = null; } activeEffectsOnly = getBoolean("active_effects"); effectParticleData = getFloat("effect_particle_data"); effectParticleCount = getInt("effect_particle_count"); effectParticleRadius = getDouble("effect_particle_radius"); effectParticleOffset = getDouble("effect_particle_offset"); effectParticleInterval = getInt("effect_particle_interval"); effectParticleMinVelocity = getDouble("effect_particle_min_velocity"); effectSoundInterval = getInt("effect_sound_interval"); castLocation = getVector("cast_location"); castInterval = getInt("cast_interval"); castMinVelocity = getDouble("cast_min_velocity"); castVelocityDirection = getVector("cast_velocity_direction"); castSpell = getString("cast_spell"); String castParameterString = getString("cast_parameters", null); if (castParameterString != null && !castParameterString.isEmpty()) { castParameters = new MemoryConfiguration(); ConfigurationUtils.addParameters(StringUtils.split(castParameterString, ' '), castParameters); } else { castParameters = null; } WandMode newMode = parseWandMode(getString("mode"), controller.getDefaultWandMode()); if (newMode != mode) { if (isInventoryOpen()) { closeInventory(); } mode = newMode; } brushMode = parseWandMode(getString("brush_mode"), controller.getDefaultBrushMode()); // Backwards compatibility if (getBoolean("mode_drop", false)) { dropAction = WandAction.TOGGLE; swapAction = WandAction.CYCLE_HOTBAR; rightClickAction = WandAction.NONE; quickCast = true; // This is to turn the redundant spell lore off quickCastDisabled = true; manualQuickCastDisabled = false; } else if (mode == WandMode.CAST) { leftClickAction = WandAction.CAST; rightClickAction = WandAction.CAST; swapAction = WandAction.NONE; dropAction = WandAction.NONE; } else if (mode == WandMode.CYCLE) { leftClickAction = WandAction.CAST; rightClickAction = WandAction.NONE; swapAction = WandAction.NONE; dropAction = WandAction.CYCLE; } else { leftClickAction = WandAction.NONE; rightClickAction = WandAction.NONE; dropAction = WandAction.NONE; swapAction = WandAction.NONE; quickCast = false; quickCastDisabled = false; manualQuickCastDisabled = false; } String quickCastType = getString("quick_cast", getString("mode_cast")); if (quickCastType != null) { if (quickCastType.equalsIgnoreCase("true")) { quickCast = true; // This is to turn the redundant spell lore off quickCastDisabled = true; manualQuickCastDisabled = false; } else if (quickCastType.equalsIgnoreCase("manual")) { quickCast = false; quickCastDisabled = true; manualQuickCastDisabled = false; } else if (quickCastType.equalsIgnoreCase("disable")) { quickCast = false; quickCastDisabled = true; manualQuickCastDisabled = true; } else { quickCast = false; quickCastDisabled = false; manualQuickCastDisabled = false; } } leftClickAction = parseWandAction(getString("left_click"), leftClickAction); rightClickAction = parseWandAction(getString("right_click"), rightClickAction); dropAction = parseWandAction(getString("drop"), dropAction); swapAction = parseWandAction(getString("swap"), swapAction); owner = getString("owner"); ownerId = getString("owner_id"); template = getString("template"); upgradeTemplate = getString("upgrade_template"); path = getString("path"); activeSpell = getString("active_spell"); if (activeSpell != null && activeSpell.contains("|")) { SpellKey activeKey = new SpellKey(activeSpell); activeSpell = activeKey.getBaseKey(); setProperty("active_spell", activeSpell); } alternateSpell = getString("alternate_spell"); alternateSpell2 = getString("alternate_spell2"); activeBrush = getString("active_brush", getString("active_material")); if (hasProperty("hotbar")) { currentHotbar = getInt("hotbar"); } if (hasProperty("page")) { int page = getInt("page"); if (page != openInventoryPage) { openInventoryPage = page; } } // Default to template names, override with localizations and finally with wand data wandName = controller.getMessages().get("wand.default_name"); description = ""; // Check for migration information in the template config ConfigurationSection templateConfig = null; if (template != null && !template.isEmpty()) { templateConfig = controller.getWandTemplateConfiguration(template); if (templateConfig != null) { wandName = templateConfig.getString("name", wandName); description = templateConfig.getString("description", description); int templateUses = templateConfig.getInt("uses"); isSingleUse = templateUses == 1; hasUses = hasUses || templateUses > 0; } wandName = controller.getMessages().get("wands." + template + ".name", wandName); description = controller.getMessages().get("wands." + template + ".description", description); } wandName = getString("name", wandName); description = getString("description", description); WandTemplate wandTemplate = getTemplate(); if (hasProperty("icon_inactive")) { String iconKey = getString("icon_inactive"); if (wandTemplate != null) { iconKey = wandTemplate.migrateIcon(iconKey); } if (iconKey != null) { inactiveIcon = new MaterialAndData(iconKey); } } else { inactiveIcon = null; } if (inactiveIcon != null && (inactiveIcon.getMaterial() == null || inactiveIcon.getMaterial() == Material.AIR)) { inactiveIcon = null; } inactiveIconDelay = getInt("icon_inactive_delay"); randomizeOnActivate = randomizeOnActivate && hasProperty("randomize_icon"); if (randomizeOnActivate) { String randomizeIcon = getString("randomize_icon"); setIcon(new MaterialAndData(randomizeIcon)); if (item == null) { controller.getLogger().warning("Invalid randomize_icon in wand '" + template + "' config: " + randomizeIcon); } } else if (hasProperty("icon")) { String iconKey = getString("icon"); if (wandTemplate != null) { iconKey = wandTemplate.migrateIcon(iconKey); } if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; } // Port old custom wand icons if (templateConfig != null && iconKey.contains("i.imgur.com")) { iconKey = templateConfig.getString("icon"); } setIcon(new MaterialAndData(iconKey)); if (item == null) { controller.getLogger().warning("Invalid icon in wand '" + template + "' config: " + iconKey); } updateIcon(); } else if (isUpgrade) { setIcon(new MaterialAndData(DefaultUpgradeMaterial)); } else { setIcon(new MaterialAndData(DefaultWandMaterial)); } if (hasProperty("upgrade_icon")) { upgradeIcon = new MaterialAndData(getString("upgrade_icon")); } // Add vanilla attributes InventoryUtils.applyAttributes(item, getConfigurationSection("item_attributes"), getString("item_attribute_slot", getString("attribute_slot"))); // Add unstashable and unmoveable tags if (getBoolean("unstashable") || (undroppable && Unstashable)) { InventoryUtils.setMetaBoolean(item, "unstashable", true); } else { InventoryUtils.removeMeta(item, "unstashable"); } if (getBoolean("unmoveable")) { InventoryUtils.setMetaBoolean(item, "unmoveable", true); } else { InventoryUtils.removeMeta(item, "unmoveable"); } if (undroppable) { InventoryUtils.setMetaBoolean(item, "undroppable", true); } else { InventoryUtils.removeMeta(item, "undroppable"); } if (keep) { InventoryUtils.setMetaBoolean(item, "keep", true); } else { InventoryUtils.removeMeta(item, "keep"); } // Add vanilla enchantments ConfigurationSection enchantments = getConfigurationSection("enchantments"); InventoryUtils.applyEnchantments(item, enchantments); // Add enchantment glow if (enchantments == null || enchantments.getKeys(false).isEmpty()) { if (glow) { CompatibilityUtils.addGlow(item); } else { CompatibilityUtils.removeGlow(item); } } // Check for path-based migration, may update icons com.elmakers.mine.bukkit.api.wand.WandUpgradePath upgradePath = getPath(); if (upgradePath != null) { hasSpellProgression = upgradePath.getSpells().size() > 0 || upgradePath.getExtraSpells().size() > 0 || upgradePath.getRequiredSpells().size() > 0; upgradePath.checkMigration(this); } else { hasSpellProgression = false; } if (isHeroes) { hasSpellProgression = true; } brushInventory.clear(); spellInventory.clear(); limitSpellsToPath = getBoolean("limit_spells_to_path"); limitBrushesToPath = getBoolean("limit_brushes_to_path"); loadSpells(); // Load spell levels Object spellLevelsRaw = getObject("spell_levels"); if (spellLevelsRaw != null) { // Not sure this will ever appear as a Map, but just in case if (spellLevelsRaw instanceof Map) { @SuppressWarnings("unchecked") Map<String, Integer> spellLevels = (Map<String, Integer>)spellLevelsRaw; loadSpellLevels(spellLevels); } else if (spellLevelsRaw instanceof ConfigurationSection) { loadSpellLevels(NMSUtils.getMap((ConfigurationSection)spellLevelsRaw)); } } checkActiveSpell(); loadBrushes(); Object brushInventoryRaw = getObject("brush_inventory"); if (brushInventoryRaw != null) { // Not sure this will ever appear as a Map, but just in case if (brushInventoryRaw instanceof Map) { @SuppressWarnings("unchecked") Map<String, Integer> brushInventory = (Map<String, Integer>)brushInventoryRaw; loadBrushInventory(brushInventory); } else if (brushInventoryRaw instanceof ConfigurationSection) { loadBrushInventory(NMSUtils.getMap((ConfigurationSection)brushInventoryRaw)); } } Object spellInventoryRaw = getObject("spell_inventory"); if (spellInventoryRaw != null) { // Not sure this will ever appear as a Map, but just in case if (spellInventoryRaw instanceof Map) { @SuppressWarnings("unchecked") Map<String, Integer> spellInventory = (Map<String, Integer>)spellInventoryRaw; loadSpellInventory(spellInventory); } else if (spellInventoryRaw instanceof ConfigurationSection) { loadSpellInventory(NMSUtils.getMap((ConfigurationSection)spellInventoryRaw)); } } else { // Spells may have contained an inventory from migration or templates with a spell@slot format. updateSpellInventory(); } castOverrides = null; if (hasProperty("overrides")) { castOverrides = null; Object overridesGeneric = getObject("overrides"); if (overridesGeneric != null) { castOverrides = new HashMap<>(); if (overridesGeneric instanceof String) { String overrides = (String) overridesGeneric; if (!overrides.isEmpty()) { // Support YML-List-As-String format // May not really need this anymore. overrides = overrides.replaceAll("[\\]\\[]", ""); String[] pairs = StringUtils.split(overrides, ','); for (String override : pairs) { parseOverride(override); } } } else if (overridesGeneric instanceof List) { @SuppressWarnings("unchecked") List<String> overrideList = (List<String>)overridesGeneric; for (String override : overrideList) { parseOverride(override); } } else if (overridesGeneric instanceof ConfigurationSection) { ConfigurationSection overridesSection = (ConfigurationSection)overridesGeneric; Set<String> keys = overridesSection.getKeys(true); for (String key : keys) { Object leaf = overridesSection.get(key); if (!(leaf instanceof ConfigurationSection) && !(leaf instanceof Map)) { castOverrides.put(key, leaf.toString()); } } } } } potionEffects.clear(); if (hasProperty("potion_effects")) { addPotionEffects(potionEffects, getString("potion_effects", null)); } // Some cleanup and sanity checks. In theory we don't need to store any non-zero value (as it is with the traders) // so try to keep defaults as 0/0.0/false. if (effectSound == null) { effectSoundInterval = 0; } else { effectSoundInterval = (effectSoundInterval == 0) ? 5 : effectSoundInterval; } if (effectParticle == null) { effectParticleInterval = 0; } checkActiveMaterial(); } private void parseOverride(String override) { // Unescape commas override = override.replace("\\|", ","); String[] keyValue = StringUtils.split(override, ' '); if (keyValue.length > 0) { String value = keyValue.length > 1 ? keyValue[1] : ""; castOverrides.put(keyValue[0], value); } } @Override public void describe(CommandSender sender, @Nullable Set<String> ignoreProperties) { ChatColor wandColor = isModifiable() ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + getName()); if (isUpgrade) { sender.sendMessage(ChatColor.YELLOW + "(Upgrade)"); } if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner != null && owner.length() > 0 && ownerId != null && ownerId.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner + " (" + ChatColor.GRAY + ownerId + ChatColor.WHITE + ")"); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } super.describe(sender, ignoreProperties); WandTemplate template = getTemplate(); if (template != null) { sender.sendMessage("" + ChatColor.BOLD + ChatColor.GREEN + "Template Configuration:"); ConfigurationSection itemConfig = getConfiguration(); Set<String> ownKeys = itemConfig.getKeys(false); template.describe(sender, ignoreProperties, ownKeys); } } private static String getBrushDisplayName(Messages messages, com.elmakers.mine.bukkit.api.block.MaterialBrush brush) { String materialName = brush == null ? null : brush.getName(messages); if (materialName == null) { materialName = "none"; } String brushPrefix = ChatColor.translateAlternateColorCodes('&', messages.get("wand.brush_prefix")); return brushPrefix + materialName; } private static String getSpellDisplayName(Messages messages, SpellTemplate spell, com.elmakers.mine.bukkit.api.block.MaterialBrush brush) { String name = ""; if (spell != null) { String spellPrefix = ChatColor.translateAlternateColorCodes('&', messages.get("wand.spell_prefix")); if (brush != null && spell.usesBrush()) { name = spellPrefix + spell.getName() + " " + getBrushDisplayName(messages, brush) + ChatColor.WHITE; } else { name = spellPrefix + spell.getName() + ChatColor.WHITE; } } return name; } private String getActiveWandName(SpellTemplate spell, com.elmakers.mine.bukkit.api.block.MaterialBrush brush) { // Build wand name int remaining = getRemainingUses(); String wandColorPrefix = (hasUses && remaining <= 1) ? "single_use_prefix" : isModifiable() ? (bound ? "bound_prefix" : "unbound_prefix") : (path != null && path.length() > 0 ? "has_path_prefix" : "unmodifiable_prefix"); String name = ChatColor.translateAlternateColorCodes('&', getMessage(wandColorPrefix)) + getDisplayName(); if (randomizeOnActivate) return name; Set<String> spells = getSpells(); // Add active spell to description Messages messages = controller.getMessages(); boolean showSpell = isModifiable() && hasSpellProgression(); showSpell = !quickCast && (spells.size() > 1 || showSpell) && getMode() != WandMode.SKILLS; if (spell != null && showSpell) { name = getSpellDisplayName(messages, spell, brush) + " (" + name + ChatColor.WHITE + ")"; } if (remaining > 1) { String message = getMessage("uses_remaining_brief"); name = name + ChatColor.DARK_RED + " (" + message.replace("$count", Integer.toString(remaining)) + ChatColor.DARK_RED + ")"; } return name; } private String getActiveWandName(SpellTemplate spell) { return getActiveWandName(spell, mage == null ? MaterialBrush.parseMaterialKey(activeBrush) : mage.getBrush()); } private String getActiveWandName(MaterialBrush brush) { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell, brush); } private String getActiveWandName() { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell); } protected String getDisplayName() { return ChatColor.translateAlternateColorCodes('&', randomizeOnActivate ? getMessage("randomized_name") : wandName); } public void updateName(boolean isActive) { if (isActive) { CompatibilityUtils.setDisplayName(item, !isUpgrade ? getActiveWandName() : ChatColor.translateAlternateColorCodes('&', getMessage("upgrade_prefix")) + getDisplayName()); } else { CompatibilityUtils.setDisplayName(item, ChatColor.stripColor(getDisplayName())); } } private void updateName() { updateName(true); } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } protected void addPropertyLore(List<String> lore, boolean isSingleSpell) { if (usesMana() && effectiveManaMax > 0) { int manaMax = getManaMax(); if (effectiveManaMax != manaMax) { String fullMessage = getLevelString("mana_amount_boosted", manaMax, controller.getMaxMana()); ConfigurationUtils.addIfNotEmpty(fullMessage.replace("$mana", Integer.toString(effectiveManaMax)), lore); } else { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_amount", manaMax, controller.getMaxMana()), lore); } int manaRegeneration = getManaRegeneration(); if (manaRegeneration > 0 && effectiveManaRegeneration > 0) { if (effectiveManaRegeneration != manaRegeneration) { String fullMessage = getLevelString("mana_regeneration_boosted", manaRegeneration, controller.getMaxManaRegeneration()); ConfigurationUtils.addIfNotEmpty(fullMessage.replace("$mana", Integer.toString(effectiveManaRegeneration)), lore); } else { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_regeneration", manaRegeneration, controller.getMaxManaRegeneration()), lore); } } if (manaPerDamage > 0) { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_per_damage", manaPerDamage, controller.getMaxManaRegeneration()), lore); } } if (superPowered) { ConfigurationUtils.addIfNotEmpty(getMessage("super_powered"), lore); } if (blockReflectChance > 0) { ConfigurationUtils.addIfNotEmpty(getLevelString("reflect_chance", blockReflectChance), lore); } else if (blockChance != 0) { ConfigurationUtils.addIfNotEmpty(getLevelString("block_chance", blockChance), lore); } float manaMaxBoost = getManaMaxBoost(); if (manaMaxBoost != 0) { ConfigurationUtils.addIfNotEmpty(getPropertyString("mana_boost", manaMaxBoost), lore); } float manaRegenerationBoost = getManaRegenerationBoost(); if (manaRegenerationBoost != 0) { ConfigurationUtils.addIfNotEmpty(getPropertyString("mana_regeneration_boost", manaRegenerationBoost), lore); } if (castSpell != null) { SpellTemplate spell = controller.getSpellTemplate(castSpell); if (spell != null) { ConfigurationUtils.addIfNotEmpty(getMessage("spell_aura").replace("$spell", spell.getName()), lore); } } for (Map.Entry<PotionEffectType, Integer> effect : potionEffects.entrySet()) { ConfigurationUtils.addIfNotEmpty(describePotionEffect(effect.getKey(), effect.getValue()), lore); } // If this is a passive wand, then reduction properties stack onto the mage when worn. // In this case we should show it as such in the lore. if (passive) isSingleSpell = false; if (consumeReduction != 0 && !isSingleSpell) ConfigurationUtils.addIfNotEmpty(getPropertyString("consume_reduction", consumeReduction), lore); if (costReduction != 0 && !isSingleSpell) ConfigurationUtils.addIfNotEmpty(getPropertyString("cost_reduction", costReduction), lore); if (cooldownReduction != 0 && !isSingleSpell) ConfigurationUtils.addIfNotEmpty(getPropertyString("cooldown_reduction", cooldownReduction), lore); if (power > 0) ConfigurationUtils.addIfNotEmpty(getLevelString("power", power), lore); if (superProtected) { ConfigurationUtils.addIfNotEmpty(getMessage("super_protected"), lore); } else if (protection != null) { for (Map.Entry<String, Double> entry : protection.entrySet()) { String protectionType = entry.getKey(); double amount = entry.getValue(); addDamageTypeLore("protection", protectionType, amount, lore); } } ConfigurationSection weaknessConfig = getConfigurationSection("weakness"); if (weaknessConfig != null) { Set<String> keys = weaknessConfig.getKeys(false); for (String key : keys) { addDamageTypeLore("weakness", key, weaknessConfig.getDouble(key), lore); } } ConfigurationSection strengthConfig = getConfigurationSection("strength"); if (strengthConfig != null) { Set<String> keys = strengthConfig.getKeys(false); for (String key : keys) { addDamageTypeLore("strength", key, strengthConfig.getDouble(key), lore); } } if (spMultiplier > 1) { ConfigurationUtils.addIfNotEmpty(getPropertyString("sp_multiplier", spMultiplier - 1), lore); } ConfigurationSection attributes = getConfigurationSection("attributes"); if (attributes != null) { // Don't bother with the lore at all if the template has been blanked out String template = getMessage("attributes"); if (!template.isEmpty()) { Set<String> keys = attributes.getKeys(false); for (String key : keys) { String label = controller.getMessages().get("attributes." + key + ".name", key); // We are only display attributes as integers for now int value = attributes.getInt(key); if (value == 0) continue; float max = 1; MagicAttribute attribute = controller.getAttribute(key); if (attribute != null) { Double maxValue = attribute.getMax(); if (maxValue != null) { max = (float)(double)maxValue; } } label = getPropertyString("attributes", value, max).replace("$attribute", label); lore.add(label); } } } } private String getPropertyString(String templateName, float value) { return getPropertyString(templateName, value, 1); } private String getPropertyString(String templateName, float value, float max) { String propertyTemplate = getBoolean("stack") ? "property_stack" : "property_value"; if (value < 0) { propertyTemplate = propertyTemplate + "_negative"; } return controller.getMessages().getPropertyString(getMessageKey(templateName), value, max, getMessageKey(propertyTemplate)); } private String formatPropertyString(String template, float value) { return formatPropertyString(template, value, 1); } private String formatPropertyString(String template, float value, float max) { String propertyTemplate = getBoolean("stack") ? "property_stack" : "property_value"; if (value < 0) { propertyTemplate = propertyTemplate + "_negative"; } return controller.getMessages().formatPropertyString(template, value, max, getMessage(propertyTemplate)); } private void addDamageTypeLore(String property, String propertyType, double amount, List<String> lore) { if (amount != 0) { String templateKey = getMessageKey(property + "." + propertyType); String template; if (controller.getMessages().containsKey(templateKey)) { template = controller.getMessages().get(templateKey); } else { templateKey = getMessageKey("protection.unknown"); template = controller.getMessages().get(templateKey); String pretty = propertyType.substring(0, 1).toUpperCase() + propertyType.substring(1); template = template.replace("$type", pretty); } template = formatPropertyString(template, (float)amount); ConfigurationUtils.addIfNotEmpty(template, lore); } } public String getLevelString(String templateName, float amount) { return controller.getMessages().getLevelString(getMessageKey(templateName), amount); } public String getLevelString(String templateName, float amount, float max) { return controller.getMessages().getLevelString(getMessageKey(templateName), amount, max); } protected List<String> getCustomLore(Collection<String> loreTemplate) { List<String> lore = new ArrayList<>(); for (String line : loreTemplate) { if (line.startsWith("$")) { switch (line) { case "$description": addDescriptionLore(lore); break; case "$path": String pathTemplate = getMessage("path_lore", ""); String pathName = getPathName(); if (pathName != null && !pathTemplate.isEmpty()) { lore.add(pathTemplate.replace("$path", pathName)); } break; case "$owner": addOwnerDescription(lore); break; case "$spells": int spellCount = getSpells().size(); if (spellCount > 0) { ConfigurationUtils.addIfNotEmpty(getMessage("spell_count").replace("$count", Integer.toString(spellCount)), lore); } break; case "$brushes": int materialCount = getBrushes().size(); if (materialCount > 0) { ConfigurationUtils.addIfNotEmpty(getMessage("material_count").replace("$count", Integer.toString(materialCount)), lore); } break; case "$uses": addUseLore(lore); break; case "$mana_max": if (usesMana()) { int manaMax = getManaMax(); if (effectiveManaMax != manaMax) { String fullMessage = getLevelString("mana_amount_boosted", manaMax, controller.getMaxMana()); ConfigurationUtils.addIfNotEmpty(fullMessage.replace("$mana", Integer.toString(effectiveManaMax)), lore); } else { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_amount", manaMax, controller.getMaxMana()), lore); } } break; case "$mana_regeneration": if (usesMana()) { int manaRegeneration = getManaRegeneration(); if (manaRegeneration > 0) { if (effectiveManaRegeneration != manaRegeneration) { String fullMessage = getLevelString("mana_regeneration_boosted", manaRegeneration, controller.getMaxManaRegeneration()); ConfigurationUtils.addIfNotEmpty(fullMessage.replace("$mana", Integer.toString(effectiveManaRegeneration)), lore); } else { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_regeneration", manaRegeneration, controller.getMaxManaRegeneration()), lore); } } } break; default: lore.add(ChatColor.translateAlternateColorCodes('&', line)); } } else { lore.add(ChatColor.translateAlternateColorCodes('&', line)); } } return lore; } protected void addDescriptionLore(List<String> lore) { String descriptionTemplate = controller.getMessages().get(getMessageKey("description_lore"), ""); if (!description.isEmpty() && !descriptionTemplate.isEmpty()) { if (description.contains("$path")) { String pathName = getPathName(); String description = ChatColor.translateAlternateColorCodes('&', this.description); description = description.replace("$path", pathName == null ? "Unknown" : pathName); InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore); } else { String description = ChatColor.translateAlternateColorCodes('&', this.description); InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore); } } } @Nullable protected String getPathName() { String pathName = null; com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); if (path != null) { pathName = path.getName(); } else if (mageClassKeys != null && !mageClassKeys.isEmpty()) { MageClassTemplate classTemplate = controller.getMageClassTemplate(mageClassKeys.get(0)); if (classTemplate != null) { String pathKey = classTemplate.getProperty("path", ""); if (!pathKey.isEmpty()) { path = controller.getPath(pathKey); } if (path != null) { pathName = path.getName(); } else { pathName = classTemplate.getName(); } } } return pathName; } protected void addOwnerDescription(List<String> lore) { if (owner != null && owner.length() > 0) { if (bound) { String ownerDescription = getMessage("bound_description", "$name").replace("$name", owner); ConfigurationUtils.addIfNotEmpty(ownerDescription, lore); } else { String ownerDescription = getMessage("owner_description", "$name").replace("$name", owner); ConfigurationUtils.addIfNotEmpty(ownerDescription, lore); } } } @SuppressWarnings("unchecked") protected List<String> getLore() { Object customLore = getProperty("lore"); if (customLore != null && customLore instanceof Collection) { return getCustomLore((Collection<String>)customLore); } List<String> lore = new ArrayList<>(); int spellCount = getSpells().size(); int materialCount = getBrushes().size(); String pathName = getPathName(); if (description.length() > 0) { if (randomizeOnActivate) { String randomDescription = getMessage("randomized_lore"); String randomTemplate = controller.getMessages().get(getMessageKey("randomized_description"), ""); if (randomDescription.length() > 0 && !randomTemplate.isEmpty()) { InventoryUtils.wrapText(randomTemplate.replace("$description", randomDescription), lore); return lore; } } if (description.contains("$") && !description.contains("$path")) { String newDescription = controller.getMessages().escape(description); if (!newDescription.equals(description)) { this.description = newDescription; setProperty("description", description); } } String descriptionTemplate = controller.getMessages().get(getMessageKey("description_lore"), ""); if (description.contains("$path") && !descriptionTemplate.isEmpty()) { String description = ChatColor.translateAlternateColorCodes('&', this.description); description = description.replace("$path", pathName == null ? "Unknown" : pathName); InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore); } else if (description.contains("$")) { String randomDescription = getMessage("randomized_lore"); String randomTemplate = controller.getMessages().get(getMessageKey("randomized_description"), ""); if (randomDescription.length() > 0 && !randomTemplate.isEmpty()) { randomDescription = ChatColor.translateAlternateColorCodes('&', randomDescription); InventoryUtils.wrapText(randomTemplate.replace("$description", randomDescription), lore); return lore; } } else if (!descriptionTemplate.isEmpty()) { String description = ChatColor.translateAlternateColorCodes('&', this.description); InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore); } } String pathTemplate = getMessage("path_lore", ""); if (pathName != null && !pathTemplate.isEmpty()) { lore.add(pathTemplate.replace("$path", pathName)); } if (!isUpgrade) { addOwnerDescription(lore); } SpellTemplate spell = controller.getSpellTemplate(getActiveSpellKey()); Messages messages = controller.getMessages(); // This is here specifically for a wand that only has // one spell now, but may get more later. Since you // can't open the inventory in this state, you can not // otherwise see the spell lore. boolean isSingleSpell = spell != null && spellCount == 1 && !hasInventory && !isUpgrade; if (isSingleSpell) { addSpellLore(messages, spell, lore, getActiveMage(), this); } if (materialCount == 1 && activeBrush != null && activeBrush.length() > 0) { lore.add(getBrushDisplayName(messages, MaterialBrush.parseMaterialKey(activeBrush))); } if (spellCount > 0) { if (isUpgrade) { ConfigurationUtils.addIfNotEmpty(getMessage("upgrade_spell_count").replace("$count", Integer.toString(spellCount)), lore); } else if (spellCount > 1) { ConfigurationUtils.addIfNotEmpty(getMessage("spell_count").replace("$count", Integer.toString(spellCount)), lore); } } if (materialCount > 0) { if (isUpgrade) { ConfigurationUtils.addIfNotEmpty(getMessage("upgrade_material_count").replace("$count", Integer.toString(materialCount)), lore); } else if (materialCount > 1) { ConfigurationUtils.addIfNotEmpty(getMessage("material_count").replace("$count", Integer.toString(materialCount)), lore); } } addUseLore(lore); addPropertyLore(lore, isSingleSpell); if (isUpgrade) { ConfigurationUtils.addIfNotEmpty(getMessage("upgrade_item_description"), lore); } return lore; } protected void addUseLore(List<String> lore) { int remaining = getRemainingUses(); if (!isSingleUse && remaining > 0) { if (isUpgrade) { String message = (remaining == 1) ? getMessage("upgrade_uses_singular") : getMessage("upgrade_uses"); ConfigurationUtils.addIfNotEmpty(message.replace("$count", Integer.toString(remaining)), lore); } else { String message = (remaining == 1) ? getMessage("uses_remaining_singular") : getMessage("uses_remaining_brief"); ConfigurationUtils.addIfNotEmpty(message.replace("$count", Integer.toString(remaining)), lore); } } } protected void updateLore() { CompatibilityUtils.setLore(item, getLore()); } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { if (EnchantableWandMaterial == null) return; if (!enchantable) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } else { MaterialSet enchantableMaterials = controller.getMaterialSetManager().getMaterialSetEmpty("enchantable"); if (!enchantableMaterials.testItem(item)) { item.setType(EnchantableWandMaterial); item.setDurability((short) 0); } } updateName(); } public static boolean hasActiveWand(Player player) { if (player == null) return false; ItemStack activeItem = player.getInventory().getItemInMainHand(); return isWand(activeItem); } @Nullable public static Wand getActiveWand(MagicController controller, Player player) { ItemStack activeItem = player.getInventory().getItemInMainHand(); if (isWand(activeItem)) { return controller.getWand(activeItem); } return null; } public static boolean isWand(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, WAND_KEY); } public static boolean isWandOrUpgrade(ItemStack item) { return isWand(item) || isUpgrade(item); } public static boolean isSpecial(ItemStack item) { return isWand(item) || isUpgrade(item) || isSpell(item) || isBrush(item) || isSP(item); } public static boolean isSelfDestructWand(ItemStack item) { return item != null && WAND_SELF_DESTRUCT_KEY != null && InventoryUtils.hasMeta(item, WAND_SELF_DESTRUCT_KEY); } public static boolean isSP(ItemStack item) { return InventoryUtils.hasMeta(item, "sp"); } @Nullable public static Integer getSP(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; String spNode = InventoryUtils.getMetaString(item, "sp"); if (spNode == null) return null; Integer sp = null; try { sp = Integer.parseInt(spNode); } catch (Exception ex) { sp = null; } return sp; } public static boolean isSpell(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "spell"); } public static boolean isSkill(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "skill"); } public static boolean isBrush(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "brush"); } @Nullable protected static Object getWandOrUpgradeNode(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) { wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); } return wandNode; } @Nullable public static String getWandTemplate(ItemStack item) { Object wandNode = getWandOrUpgradeNode(item); if (wandNode == null) return null; return InventoryUtils.getMetaString(wandNode, "template"); } @Nullable public static String getWandId(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) return null; return InventoryUtils.getMetaString(wandNode, "id"); } @Nullable public static String getSpell(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "key"); } @Nullable @Override public Spell getSpell(String spellKey, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage == null) { return null; } if (!hasSpell(spellKey)) return null; SpellKey key = new SpellKey(spellKey); spellKey = key.getBaseKey(); Integer level = spellLevels.get(spellKey); if (level != null) { spellKey = new SpellKey(spellKey, level).getKey(); } return mage.getSpell(spellKey); } @Nullable @Override public Spell getSpell(String spellKey) { return getSpell(spellKey, mage); } @Nullable public static String getSpellClass(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "class"); } public static boolean isQuickCastSkill(ItemStack item) { if (InventoryUtils.isEmpty(item)) return false; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return false; Boolean quickCast = InventoryUtils.containsNode(spellNode, "quick_cast") ? InventoryUtils.getMetaBoolean(spellNode, "quick_cast") : null; return quickCast == null ? true : quickCast; } @Nullable public static String getSpellArgs(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "args"); } @Nullable public static String getBrush(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object brushNode = InventoryUtils.getNode(item, "brush"); if (brushNode == null) return null; return InventoryUtils.getMetaString(brushNode, "key"); } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = mage.getSpell(getSpell(item)); if (spell != null) { updateSpellName(controller.getMessages(), item, spell, activeName ? this : null, activeBrush); } } else if (isBrush(item)) { updateBrushName(controller.getMessages(), item, getBrush(item), activeName ? this : null); } } public static void updateSpellItem(Messages messages, ItemStack itemStack, SpellTemplate spell, String args, Wand wand, String activeMaterial, boolean isItem) { updateSpellItem(messages, itemStack, spell, args, wand == null ? null : wand.getActiveMage(), wand, activeMaterial, isItem); } public static void updateSpellItem(Messages messages, ItemStack itemStack, SpellTemplate spell, String args, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, String activeMaterial, boolean isItem) { updateSpellName(messages, itemStack, spell, wand, activeMaterial); List<String> lore = new ArrayList<>(); addSpellLore(messages, spell, lore, mage, wand); if (isItem) { ConfigurationUtils.addIfNotEmpty(messages.get("wand.spell_item_description"), lore); } CompatibilityUtils.setLore(itemStack, lore); Object spellNode = CompatibilityUtils.createNode(itemStack, "spell"); CompatibilityUtils.setMeta(spellNode, "key", spell.getKey()); CompatibilityUtils.setMeta(spellNode, "args", args); if (SpellGlow) { CompatibilityUtils.addGlow(itemStack); } } public static void updateSpellName(Messages messages, ItemStack itemStack, SpellTemplate spell, Wand wand, String activeMaterial) { String displayName; if (wand != null && !wand.isQuickCast()) { displayName = wand.getActiveWandName(spell); } else { displayName = getSpellDisplayName(messages, spell, MaterialBrush.parseMaterialKey(activeMaterial)); } CompatibilityUtils.setDisplayName(itemStack, displayName); } public static void updateBrushName(Messages messages, ItemStack itemStack, String materialKey, Wand wand) { updateBrushName(messages, itemStack, MaterialBrush.parseMaterialKey(materialKey), wand); } public static void updateBrushName(Messages messages, ItemStack itemStack, MaterialBrush brush, Wand wand) { String displayName; if (wand != null) { Spell activeSpell = wand.getActiveSpell(); if (activeSpell != null && activeSpell.usesBrush()) { displayName = wand.getActiveWandName(brush); } else { displayName = ChatColor.RED + brush.getName(messages); } } else { displayName = brush.getName(messages); } CompatibilityUtils.setDisplayName(itemStack, displayName); } public static void updateBrushItem(Messages messages, ItemStack itemStack, String materialKey, Wand wand) { updateBrushItem(messages, itemStack, MaterialBrush.parseMaterialKey(materialKey), wand); } public static void updateBrushItem(Messages messages, ItemStack itemStack, MaterialBrush brush, Wand wand) { updateBrushName(messages, itemStack, brush, wand); Object brushNode = CompatibilityUtils.createNode(itemStack, "brush"); CompatibilityUtils.setMeta(brushNode, "key", brush.getKey()); } public void updateHotbar() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; if (!hasStoredInventory()) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { PlayerInventory inventory = player.getInventory(); updateHotbar(inventory); DeprecatedUtils.updateInventory(player); } } private boolean updateHotbar(PlayerInventory playerInventory) { if (getMode() != WandMode.INVENTORY) return false; Inventory hotbar = getHotbar(); if (hotbar == null) return false; // Make sure the wand is still in the held slot ItemStack currentItem = playerInventory.getItem(heldSlot); if (currentItem == null || !currentItem.getItemMeta().equals(item.getItemMeta())) { controller.getLogger().warning("Trying to update hotbar but the wand has gone missing"); return false; } // Set hotbar items from remaining list int targetOffset = 0; for (int hotbarSlot = 0; hotbarSlot < HOTBAR_INVENTORY_SIZE; hotbarSlot++) { if (hotbarSlot == heldSlot) { targetOffset = 1; } ItemStack hotbarItem = hotbar.getItem(hotbarSlot); updateInventoryName(hotbarItem, true); playerInventory.setItem(hotbarSlot + targetOffset, hotbarItem); } return true; } private void updateInventory() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { if (!hasStoredInventory()) return; PlayerInventory inventory = player.getInventory(); if (!updateHotbar(inventory)) { for (int i = 0; i < HOTBAR_SIZE; i++) { if (i != inventory.getHeldItemSlot()) { inventory.setItem(i, null); } } } updateInventory(inventory); updateName(); } else if (wandMode == WandMode.CHEST || wandMode == WandMode.SKILLS) { Inventory inventory = getDisplayInventory(); inventory.clear(); updateInventory(inventory); } } private void updateInventory(Inventory targetInventory) { // Set inventory from current page, taking into account hotbar offset int currentOffset = getHotbarSize() > 0 ? HOTBAR_SIZE : 0; List<Inventory> inventories = this.inventories; if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } for (;currentOffset < targetInventory.getSize() && currentOffset < PLAYER_INVENTORY_SIZE; currentOffset++) { targetInventory.setItem(currentOffset, null); } } protected static void addSpellLore(Messages messages, SpellTemplate spell, List<String> lore, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand) { spell.addLore(messages, mage, wand, lore); } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, getInventorySize(), "Wand")); } return inventories.get(openInventoryPage); } protected Inventory getDisplayInventory() { if (displayInventory == null || displayInventory.getSize() != getInventorySize()) { displayInventory = CompatibilityUtils.createInventory(null, getInventorySize(), "Wand"); } return displayInventory; } public void saveChestInventory() { if (displayInventory == null) return; Inventory openInventory = getOpenInventory(); Map<String, Integer> previousSlots = new HashMap<>(); Set<String> addedBack = new HashSet<>(); for (int i = 0; i < displayInventory.getSize(); i++) { ItemStack playerItem = displayInventory.getItem(i); String itemSpellKey = getSpell(playerItem); if (!updateSlot(i + openInventoryPage * getInventorySize(), playerItem)) { playerItem = new ItemStack(Material.AIR); displayInventory.setItem(i, playerItem); } else if (itemSpellKey != null) { addedBack.add(itemSpellKey); } // We don't want to clear items that were taken out, so save them to check later ItemStack current = openInventory.getItem(i); String spellKey = getSpell(current); if (spellKey != null) { previousSlots.put(spellKey, i); } openInventory.setItem(i, playerItem); } // Put back any items that were taken out for (Map.Entry<String, Integer> entry : previousSlots.entrySet()) { if (!addedBack.contains(entry.getKey())) { ItemStack current = openInventory.getItem(entry.getValue()); ItemStack itemStack = createSpellItem(controller.getSpellTemplate(entry.getKey()), "", controller, getActiveMage(), this, false); if (current == null || current.getType() == Material.AIR) { openInventory.setItem(entry.getValue(), itemStack); } else { openInventory.addItem(itemStack); } } } } public void saveInventory() { if (mage == null) return; if (getMode() == WandMode.SKILLS) { saveChestInventory(); return; } if (!isInventoryOpen()) return; if (mage.getPlayer() == null) return; if (getMode() != WandMode.INVENTORY) return; if (!hasStoredInventory()) return; // Work-around glitches that happen if you're dragging an item on death if (mage.isDead()) return; // Fill in the hotbar Player player = mage.getPlayer(); PlayerInventory playerInventory = player.getInventory(); Inventory hotbar = getHotbar(); if (hotbar != null) { int saveOffset = 0; for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { saveOffset = -1; continue; } int hotbarOffset = i + saveOffset; if (hotbarOffset >= hotbar.getSize()) { // This can happen if there is somehow no wand in the wand inventory. break; } if (!updateSlot(i + saveOffset + currentHotbar * HOTBAR_INVENTORY_SIZE, playerItem)) { playerItem = new ItemStack(Material.AIR); playerInventory.setItem(i, playerItem); } hotbar.setItem(i + saveOffset, playerItem); } } // Fill in the active inventory page int hotbarOffset = getHotbarSize(); Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { ItemStack playerItem = playerInventory.getItem(i + HOTBAR_SIZE); if (!updateSlot(i + hotbarOffset + openInventoryPage * getInventorySize(), playerItem)) { playerItem = new ItemStack(Material.AIR); playerInventory.setItem(i + HOTBAR_SIZE, playerItem); } openInventory.setItem(i, playerItem); } } protected boolean updateSlot(int slot, ItemStack item) { if (item == null || item.getType() == Material.AIR) return true; String spellKey = getSpell(item); if (spellKey != null) { SpellKey key = new SpellKey(spellKey); spellInventory.put(key.getBaseKey(), slot); } else { String brushKey = getBrush(item); if (brushKey != null) { brushInventory.put(brushKey, slot); } else if (mage != null) { // Must have been an item inserted directly into player's inventory? mage.giveItem(item); return false; } } return true; } @Override public int enchant(int totalLevels, com.elmakers.mine.bukkit.api.magic.Mage mage, boolean addSpells) { return randomize(totalLevels, true, mage, addSpells); } @Override public int enchant(int totalLevels, com.elmakers.mine.bukkit.api.magic.Mage mage) { return randomize(totalLevels, true, mage, true); } @Override public int enchant(int totalLevels) { return randomize(totalLevels, true, null, true); } protected int randomize(int totalLevels, boolean additive, com.elmakers.mine.bukkit.api.magic.Mage enchanter, boolean addSpells) { if (enchanter == null && mage != null) { enchanter = mage; } if (maxEnchantCount > 0 && enchantCount >= maxEnchantCount) { if (enchanter != null && addSpells) { enchanter.sendMessage(getMessage("max_enchanted").replace("$wand", getName())); } return 0; } WandUpgradePath path = getPath(); if (path == null) { if (enchanter != null && addSpells) { enchanter.sendMessage(getMessage("no_path").replace("$wand", getName())); } return 0; } int minLevel = path.getMinLevel(); if (totalLevels < minLevel) { if (enchanter != null && addSpells) { String levelMessage = getMessage("need_more_levels"); levelMessage = levelMessage.replace("$levels", Integer.toString(minLevel)); enchanter.sendMessage(levelMessage); } return 0; } // Just a hard-coded sanity check int maxLevel = path.getMaxLevel(); totalLevels = Math.min(totalLevels, maxLevel * 50); int addLevels = Math.min(totalLevels, maxLevel); int levels = 0; boolean modified = true; while (addLevels >= minLevel && modified) { boolean hasUpgrade = path.hasUpgrade(); WandLevel level = path.getLevel(addLevels); if (!path.canEnchant(this) && (path.hasSpells() || path.hasMaterials())) { // Check for level up WandUpgradePath nextPath = path.getUpgrade(); if (nextPath != null) { if (path.checkUpgradeRequirements(this, addSpells ? enchanter : null)) { path.upgrade(this, enchanter); } break; } else { if (enchanter != null && addSpells) { enchanter.sendMessage(getMessage("fully_enchanted").replace("$wand", getName())); } break; } } modified = level.randomizeWand(enchanter, this, additive, hasUpgrade, addSpells); totalLevels -= maxLevel; if (modified) { if (enchanter != null) { path.enchanted(enchanter); } levels += addLevels; // Check for level up WandUpgradePath nextPath = path.getUpgrade(); if (nextPath != null && path.checkUpgradeRequirements(this, null) && !path.canEnchant(this)) { path.upgrade(this, enchanter); path = nextPath; } } else if (path.canEnchant(this)) { if (enchanter != null && levels == 0 && addSpells) { String message = getMessage("require_more_levels"); enchanter.sendMessage(message); } } else if (hasUpgrade) { if (path.checkUpgradeRequirements(this, addSpells ? enchanter : null)) { path.upgrade(this, enchanter); levels += addLevels; } } else if (enchanter != null && addSpells) { enchanter.sendMessage(getMessage("fully_enchanted").replace("$wand", getName())); } addLevels = Math.min(totalLevels, maxLevel); additive = true; } if (levels > 0) { enchantCount++; setProperty("enchant_count", enchantCount); } saveState(); updateName(); updateLore(); return levels; } protected void randomize() { if (template != null && template.length() > 0) { ConfigurationSection wandConfig = controller.getWandTemplateConfiguration(template); if (wandConfig != null && wandConfig.contains("icon")) { String iconKey = wandConfig.getString("icon"); if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; } setIcon(ConfigurationUtils.toMaterialAndData(iconKey)); updateIcon(); playEffects("randomize"); } } } @Nullable public static ItemStack createItem(MagicController controller, String templateName) { ItemStack item = createSpellItem(templateName, controller, null, true); if (item == null) { item = createBrushItem(templateName, controller, null, true); if (item == null) { Wand wand = createWand(controller, templateName); if (wand != null) { item = wand.getItem(); } } } return item; } @Nullable public static Wand createWand(MagicController controller, String templateName) { if (controller == null) return null; Wand wand = null; try { wand = new Wand(controller, templateName); } catch (UnknownWandException ignore) { // the Wand constructor throws an exception on an unknown template } catch (Exception ex) { ex.printStackTrace(); } return wand; } @Nullable public static Wand createWand(MagicController controller, ItemStack itemStack) { if (controller == null) return null; Wand wand = null; try { wand = controller.getWand(InventoryUtils.makeReal(itemStack)); wand.saveState(); wand.updateName(); } catch (Exception ex) { ex.printStackTrace(); } return wand; } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other) { if (other instanceof Wand) { return add((Wand)other); } return false; } public boolean add(Wand other) { return add(other, this.mage); } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (other instanceof Wand) { return add((Wand)other, mage); } return false; } public boolean add(Wand other, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (!isModifiable()) { // Only allow upgrading a modifiable wand via an upgrade item // and only if the paths match. if (!other.isUpgrade() || other.path == null || path == null || other.path.isEmpty() || path.isEmpty() || !other.path.equals(path)) { return false; } } // Can't combine limited-use wands if (hasUses || other.hasUses) { return false; } if (isHeroes || other.isHeroes) { return false; } ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(other.getTemplateKey()); // Check for forced upgrades if (other.isForcedUpgrade()) { if (templateConfig == null) { return false; } templateConfig = ConfigurationUtils.cloneConfiguration(templateConfig); templateConfig.set("name", templateConfig.getString("upgrade_name")); templateConfig.set("description", templateConfig.getString("upgrade_description")); templateConfig.set("force", null); templateConfig.set("upgrade", null); templateConfig.set("icon", templateConfig.getString("upgrade_icon")); templateConfig.set("indestructible", null); templateConfig.set("upgrade_icon", null); configure(templateConfig); return true; } // Don't allow upgrades from an item on a different path if (other.isUpgrade() && other.path != null && !other.path.isEmpty() && (this.path == null || !this.path.equals(other.path))) { return false; } ConfigurationSection upgradeConfig = ConfigurationUtils.cloneConfiguration(other.getEffectiveConfiguration()); upgradeConfig.set("id", null); upgradeConfig.set("indestructible", null); upgradeConfig.set("upgrade", null); upgradeConfig.set("icon", other.upgradeIcon == null ? null : other.upgradeIcon.getKey()); upgradeConfig.set("upgrade_icon", null); upgradeConfig.set("template", other.upgradeTemplate); Messages messages = controller.getMessages(); if (other.rename && templateConfig != null) { String newName = messages.get("wands." + other.template + ".name"); newName = templateConfig.getString("name", newName); upgradeConfig.set("name", newName); } else { upgradeConfig.set("name", null); } if (other.renameDescription && templateConfig != null) { String newDescription = messages.get("wands." + other.template + ".description"); newDescription = templateConfig.getString("description", newDescription); upgradeConfig.set("description", newDescription); } else { upgradeConfig.set("description", null); } return upgrade(upgradeConfig); } public boolean isForcedUpgrade() { return isUpgrade && forceUpgrade; } public boolean keepOnDeath() { return keep; } public static WandMode parseWandMode(String modeString, WandMode defaultValue) { if (modeString != null && !modeString.isEmpty()) { try { defaultValue = WandMode.valueOf(modeString.toUpperCase()); } catch (Exception ignored) { } } return defaultValue; } public static WandAction parseWandAction(String actionString, WandAction defaultValue) { if (actionString != null && !actionString.isEmpty()) { try { defaultValue = WandAction.valueOf(actionString.toUpperCase()); } catch (Exception ignored) { } } return defaultValue; } private void updateActiveMaterial() { if (mage == null) return; if (activeBrush == null) { mage.clearBuildingMaterial(); } else { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); brush.update(activeBrush); } } public void cycleActive(int direction) { Player player = mage != null ? mage.getPlayer() : null; if (player != null && player.isSneaking()) { com.elmakers.mine.bukkit.api.spell.Spell activeSpell = getActiveSpell(); boolean cycleMaterials = false; if (activeSpell != null) { cycleMaterials = activeSpell.usesBrushSelection(); } if (cycleMaterials) { cycleMaterials(direction); } else { cycleSpells(direction); } } else { cycleSpells(direction); } } public void toggleInventory() { if (mage != null && mage.cancelSelection()) { mage.playSoundEffect(noActionSound); return; } Player player = mage == null ? null : mage.getPlayer(); boolean isSneaking = player != null && player.isSneaking(); Spell currentSpell = getActiveSpell(); if (getBrushMode() == WandMode.CHEST && brushSelectSpell != null && !brushSelectSpell.isEmpty() && isSneaking && currentSpell != null && currentSpell.usesBrushSelection()) { Spell brushSelect = mage.getSpell(brushSelectSpell); if (brushSelect != null) { brushSelect.cast(); return; } } if (!hasInventory) { if (activeSpell == null || activeSpell.length() == 0) { // Sanity check, so it'll switch to inventory next time updateHasInventory(); if (spells.size() > 0) { setActiveSpell(spells.iterator().next()); } } updateName(); return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } public void updateHasInventory() { int inventorySize = getSpells().size() + getBrushes().size(); hasInventory = inventorySize > 1 || (inventorySize == 1 && hasSpellProgression) || autoFill; } public void cycleInventory() { cycleInventory(1); } public void cycleInventory(int direction) { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); int inventoryCount = inventories.size(); setOpenInventoryPage(inventoryCount == 0 ? 0 : (openInventoryPage + inventoryCount + direction) % inventoryCount); updateInventory(); if (mage != null && inventories.size() > 1) { if (!playPassiveEffects("cycle") && inventoryCycleSound != null) { mage.playSoundEffect(inventoryCycleSound); } DeprecatedUtils.updateInventory(mage.getPlayer()); } } } @Override public void cycleHotbar() { cycleHotbar(1); } public void cycleHotbar(int direction) { if (!hasInventory || getMode() != WandMode.INVENTORY) { return; } if (isInventoryOpen() && mage != null && hotbars.size() > 1) { saveInventory(); int hotbarCount = hotbars.size(); setCurrentHotbar(hotbarCount == 0 ? 0 : (currentHotbar + hotbarCount + direction) % hotbarCount); updateHotbar(); if (!playPassiveEffects("cycle") && inventoryCycleSound != null) { mage.playSoundEffect(inventoryCycleSound); } sendMessage("hotbar_changed"); updateHotbarStatus(); DeprecatedUtils.updateInventory(mage.getPlayer()); } } public void openInventory() { if (mage == null) return; if (System.currentTimeMillis() < mage.getWandDisableTime()) return; WandMode wandMode = getMode(); if (wandMode == WandMode.CHEST || wandMode == WandMode.SKILLS) { inventoryIsOpen = true; if (!playPassiveEffects("open") && inventoryOpenSound != null) { mage.playSoundEffect(inventoryOpenSound); } updateInventory(); mage.getPlayer().openInventory(getDisplayInventory()); } else if (wandMode == WandMode.INVENTORY) { if (hasStoredInventory()) return; if (storeInventory()) { inventoryIsOpen = true; showActiveIcon(true); if (!playPassiveEffects("open") && inventoryOpenSound != null) { mage.playSoundEffect(inventoryOpenSound); } updateInventory(); updateHotbarStatus(); } } } @Override public void closeInventory() { if (!isInventoryOpen()) return; controller.disableItemSpawn(); inventoryWasOpen = true; WandMode mode = getMode(); try { saveInventory(); updateSpellInventory(); updateBrushInventory(); inventoryIsOpen = false; if (mage != null) { if (!playPassiveEffects("close") && inventoryCloseSound != null) { mage.playSoundEffect(inventoryCloseSound); } if (mode == WandMode.INVENTORY) { restoreInventory(); showActiveIcon(false); } else { mage.getPlayer().closeInventory(); } // Check for items the player might've glitched onto their body... PlayerInventory inventory = mage.getPlayer().getInventory(); ItemStack testItem = inventory.getHelmet(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setHelmet(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getBoots(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setBoots(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getLeggings(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setLeggings(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getChestplate(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setChestplate(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } // This is kind of a hack :( testItem = inventory.getItemInOffHand(); if ((isSpell(testItem) && !isSkill(testItem)) || isBrush(testItem)) { inventory.setItemInOffHand(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } } } catch (Throwable ex) { restoreInventory(); } if (mode == WandMode.INVENTORY && mage != null) { try { mage.getPlayer().closeInventory(); } catch (Throwable ex) { ex.printStackTrace(); } } controller.enableItemSpawn(); inventoryWasOpen = false; } @Override public boolean fill(Player player) { return fill(player, 0); } @Override public boolean fill(Player player, int maxLevel) { String mageId = mage.getId(); closeInventory(); Collection<String> currentSpells = new ArrayList<>(getSpells()); for (String spellKey : currentSpells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); boolean removeSpell = !spell.hasCastPermission(player); String creatorId = spell.getCreatorId(); removeSpell = removeSpell || (FILL_CREATOR && (creatorId == null || !mageId.equals(creatorId))); if (removeSpell) { removeSpell(spellKey); } } Collection<SpellTemplate> allSpells = controller.getPlugin().getSpellTemplates(); // Hack to prevent messaging Mage mage = this.mage; this.mage = null; for (SpellTemplate spell : allSpells) { String key = spell.getKey(); if (maxLevel > 0 && spell.getSpellKey().getLevel() > maxLevel) { continue; } if (key.startsWith("heroes*")) { continue; } String creatorId = spell.getCreatorId(); if (FILL_CREATOR && (creatorId == null || !mageId.equals(creatorId))) { continue; } if (spell.hasCastPermission(player) && spell.hasIcon() && !spell.isHidden()) { addSpell(key); } } this.mage = mage; if (!FILL_CREATOR) { if (autoFill) setProperty("fill", false); autoFill = false; } saveState(); return true; } protected void checkActiveMaterial() { if (activeBrush == null || activeBrush.length() == 0) { Set<String> materials = getBrushes(); if (materials.size() > 0) { activeBrush = materials.iterator().next(); } } } @Override public boolean addItem(ItemStack item) { if (isUpgrade) return false; if (isModifiable() && isSpell(item) && !isSkill(item)) { String spell = getSpell(item); SpellKey spellKey = new SpellKey(spell); Integer currentLevel = spellLevels.get(spellKey.getBaseKey()); if ((currentLevel == null || currentLevel < spellKey.getLevel()) && addSpell(spell)) { return true; } } else if (isModifiable() && isBrush(item)) { String materialKey = getBrush(item); Set<String> materials = getBrushes(); if (!materials.contains(materialKey) && addBrush(materialKey)) { return true; } } else if (isUpgrade(item)) { Wand wand = controller.getWand(item); return this.add(wand); } if (mage != null && !mage.isAtMaxSkillPoints() && controller.skillPointItemsEnabled()) { Integer sp = getSP(item); if (sp != null) { int amount = (int)Math.floor(mage.getSPMultiplier() * sp * item.getAmount()); mage.addSkillPoints(amount); return true; } } return false; } protected void updateEffects() { updateEffects(mage); } public void updateEffects(Mage mage) { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; // Update Bubble effects effects if (effectBubbles && effectColor != null) { Location potionEffectLocation = player.getLocation(); potionEffectLocation.setX(potionEffectLocation.getX() + random.nextDouble() - 0.5); potionEffectLocation.setY(potionEffectLocation.getY() + random.nextDouble() * player.getEyeHeight()); potionEffectLocation.setZ(potionEffectLocation.getZ() + random.nextDouble() - 0.5); EffectPlayer.displayParticle(Particle.SPELL_MOB, potionEffectLocation, 0, 0, 0, 0, 0, 1, effectColor.getColor(), null, (byte)0, 24); } Location location = mage.getLocation(); long now = System.currentTimeMillis(); boolean playEffects = !activeEffectsOnly || inventoryIsOpen || isInOffhand; if (playEffects && effectParticle != null && effectParticleInterval > 0 && effectParticleCount > 0) { boolean velocityCheck = true; if (effectParticleMinVelocity > 0) { double velocitySquared = effectParticleMinVelocity * effectParticleMinVelocity; Vector velocity = mage.getVelocity().clone(); velocity.setY(0); double speedSquared = velocity.lengthSquared(); velocityCheck = (speedSquared > velocitySquared); } if (velocityCheck && (lastParticleEffect == 0 || now > lastParticleEffect + effectParticleInterval)) { lastParticleEffect = now; Location effectLocation = player.getLocation(); Location eyeLocation = player.getEyeLocation(); effectLocation.setY(eyeLocation.getY() + effectParticleOffset); if (effectPlayer == null) { effectPlayer = new EffectRing(controller.getPlugin()); effectPlayer.setParticleCount(1); effectPlayer.setIterations(1); effectPlayer.setParticleOffset(0, 0, 0); } effectPlayer.setMaterial(location.getBlock().getRelative(BlockFace.DOWN)); if (effectParticleData == 0) { effectPlayer.setColor(getEffectColor()); } else { effectPlayer.setColor(null); } effectPlayer.setParticleType(effectParticle); effectPlayer.setParticleData(effectParticleData); effectPlayer.setSize(effectParticleCount); effectPlayer.setRadius((float)effectParticleRadius); effectPlayer.start(effectLocation, null); } } if (castSpell != null && castInterval > 0) { if (lastSpellCast == 0 || now > lastSpellCast + castInterval) { boolean velocityCheck = true; if (castMinVelocity > 0) { double velocitySquared = castMinVelocity * castMinVelocity; Vector velocity = mage.getVelocity(); if (castVelocityDirection != null) { velocity = velocity.clone().multiply(castVelocityDirection); // This is kind of a hack to make jump-detection work. if (castVelocityDirection.getY() < 0) { velocityCheck = velocity.getY() < 0; } else { velocityCheck = velocity.getY() > 0; } } if (velocityCheck) { double speedSquared = velocity.lengthSquared(); velocityCheck = (speedSquared > velocitySquared); } } if (velocityCheck) { lastSpellCast = now; Spell spell = mage.getSpell(castSpell); if (spell != null) { if (castParameters == null) { castParameters = new MemoryConfiguration(); } castParameters.set("passive", true); mage.setCostFree(true); mage.setQuiet(true); try { spell.cast(castParameters); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Error casting aura spell " + spell.getKey(), ex); } mage.setCostFree(false); mage.setQuiet(false); } } } } if (playEffects && effectSound != null && controller.soundsEnabled() && effectSoundInterval > 0) { if (lastSoundEffect == 0 || now > lastSoundEffect + effectSoundInterval) { lastSoundEffect = now; effectSound.play(controller.getPlugin(), mage.getPlayer()); } } } protected void updateDurability() { int maxDurability = item.getType().getMaxDurability(); if (maxDurability > 0 && effectiveManaMax > 0) { int durability = (short)(getMana() * maxDurability / effectiveManaMax); durability = maxDurability - durability; if (durability >= maxDurability) { durability = maxDurability - 1; } else if (durability < 0) { durability = 0; } item.setDurability((short)durability); } } public boolean usesXPBar() { return (usesSP() && spMode.useXP()) || (usesMana() && manaMode.useXP()); } public boolean usesXPNumber() { return (usesSP() && spMode.useXPNumber() && controller.isSPEnabled()) || (usesMana() && manaMode.useXP()); } public boolean hasSpellProgression() { return hasSpellProgression; } public boolean usesXPDisplay() { return usesXPBar() || usesXPNumber(); } @Override public void updateMana() { Player player = mage == null ? null : mage.getPlayer(); if (player == null) return; float mana = getMana(); if (usesMana()) { if (manaMode.useGlow()) { if (mana == effectiveManaMax) { CompatibilityUtils.addGlow(item); } else { CompatibilityUtils.removeGlow(item); } } if (manaMode.useDurability()) { updateDurability(); } } if (usesXPDisplay()) { int playerLevel = player.getLevel(); float playerProgress = player.getExp(); if (usesMana() && manaMode.useXPNumber()) { playerLevel = (int) mana; } if (usesMana() && manaMode.useXPBar()) { playerProgress = Math.max(0, mana / effectiveManaMax); } if (usesSP() && spMode.useXPNumber()) { playerLevel = mage.getSkillPoints(); } mage.sendExperience(playerProgress, playerLevel); } } @Override public boolean isInventoryOpen() { return mage != null && inventoryIsOpen; } // Somewhat hacky method to handle inventory close event knowing that this was a wand inventory that just closed. public boolean wasInventoryOpen() { return inventoryWasOpen; } @Override public void unbind() { if (!bound) return; com.elmakers.mine.bukkit.api.magic.Mage owningMage = this.mage; deactivate(); if (ownerId != null) { if (owningMage == null || !owningMage.getId().equals(ownerId)) { owningMage = controller.getRegisteredMage(ownerId); } if (owningMage != null) { owningMage.unbind(this); } ownerId = null; } bound = false; owner = null; setProperty("bound", false); setProperty("owner", null); setProperty("owner_id", null); saveState(); updateLore(); updateName(); } @Override public void bind() { if (bound) return; Mage holdingMage = mage; deactivate(); bound = true; setProperty("bound", true); saveState(); if (holdingMage != null) { holdingMage.checkWand(); } } @Override public void deactivate() { if (mage == null) return; // Play deactivate FX playPassiveEffects("deactivate"); // Cancel effects if (effectContext != null) { int cancelDelay = getInt("cancel_effects_delay", 0); if (cancelDelay == 0) { effectContext.cancelEffects(); } else { Plugin plugin = controller.getPlugin(); final WandEffectContext context = effectContext; plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { context.cancelEffects(); } }, cancelDelay * 20 / 1000); } } Mage mage = this.mage; if (isInventoryOpen()) { closeInventory(); } showActiveIcon(false); storedInventory = null; if (usesXPNumber() || usesXPBar()) { mage.resetSentExperience(); } saveState(); mage.deactivateWand(this); this.mage = null; updateMaxMana(true); } @Nullable @Override public Spell getActiveSpell() { if (mage == null) return null; String activeSpellKey = getActiveSpellKey(); if (activeSpellKey == null || activeSpellKey.length() == 0) return null; return mage.getSpell(activeSpellKey); } @Nullable public Spell getAlternateSpell() { if (mage == null || alternateSpell == null || alternateSpell.length() == 0) return null; return mage.getSpell(alternateSpell); } @Nullable public Spell getAlternateSpell2() { if (mage == null || alternateSpell2 == null || alternateSpell2.length() == 0) return null; return mage.getSpell(alternateSpell2); } @Nullable @Override public SpellTemplate getBaseSpell(String spellName) { return getBaseSpell(new SpellKey(spellName)); } @Nullable public SpellTemplate getBaseSpell(SpellKey key) { if (!spells.contains(key.getBaseKey())) return null; SpellKey baseKey = new SpellKey(key.getBaseKey(), getSpellLevel(key.getBaseKey())); return controller.getSpellTemplate(baseKey.getKey()); } @Override public String getActiveSpellKey() { String activeSpellKey = activeSpell; Integer level = spellLevels.get(activeSpellKey); if (level != null) { activeSpellKey = new SpellKey(activeSpellKey, level).getKey(); } return activeSpellKey; } @Override public String getActiveBrushKey() { return activeBrush; } @Override public void damageDealt(double damage, Entity target) { if (manaPerDamage > 0) { int manaMax = getEffectiveManaMax(); float mana = getMana(); if (manaMax > 0 && mana < manaMax) { setMana(Math.min(manaMax, mana + (float)damage * manaPerDamage)); updateMana(); } } } public boolean alternateCast() { return cast(getAlternateSpell()); } public boolean alternateCast2() { return cast(getAlternateSpell2()); } @Override public boolean cast() { return cast(getActiveSpell(), null); } @Override public boolean cast(String[] parameters) { return cast(getActiveSpell(), parameters); } public boolean cast(Spell spell) { return cast(spell, null); } public boolean cast(Spell spell, String[] parameters) { if (spell != null) { Collection<String> castParameters = null; if (castOverrides != null && castOverrides.size() > 0) { castParameters = new ArrayList<>(); for (Map.Entry<String, String> entry : castOverrides.entrySet()) { String[] key = StringUtils.split(entry.getKey(), '.'); if (key.length == 0) continue; if (key.length == 2 && !key[0].equals("default") && !key[0].equals(spell.getSpellKey().getBaseKey()) && !key[0].equals(spell.getSpellKey().getKey())) { continue; } castParameters.add(key.length == 2 ? key[1] : key[0]); castParameters.add(entry.getValue()); } } if (parameters != null) { if (castParameters == null) { castParameters = new ArrayList<>(); } for (String parameter : parameters) { castParameters.add(parameter); } } if (spell.cast(castParameters == null ? null : castParameters.toArray(EMPTY_PARAMETERS))) { Color spellColor = spell.getColor(); use(); if (spellColor != null && this.effectColor != null) { this.effectColor = this.effectColor.mixColor(spellColor, effectColorSpellMixWeight); setProperty("effect_color", effectColor.toString()); // Note that we don't save this change. // The hope is that the wand will get saved at some point later // And we don't want to trigger NBT writes every spell cast. // And the effect color morphing isn't all that important if a few // casts get lost. } updateHotbarStatus(); return true; } } return false; } protected void use() { if (hasUses) { findItem(); ItemStack item = getItem(); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { if (uses > 0) { uses--; } if (uses <= 0 && mage != null) { // If the wand is not currently active it will be destroyed on next activate Player player = mage.getPlayer(); deactivate(); PlayerInventory playerInventory = player.getInventory(); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { if (isInOffhand) { playerInventory.setItemInOffHand(new ItemStack(Material.AIR, 1)); } else { playerInventory.setItemInMainHand(new ItemStack(Material.AIR, 1)); } } DeprecatedUtils.updateInventory(player); } setProperty("uses", uses); saveState(); updateName(); updateLore(); } } } // Taken from NMS HumanEntity public static int getExpToLevel(int expLevel) { return expLevel >= 30 ? 112 + (expLevel - 30) * 9 : (expLevel >= 15 ? 37 + (expLevel - 15) * 5 : 7 + expLevel * 2); } public static int getExperience(int expLevel, float expProgress) { int xp = 0; for (int level = 0; level < expLevel; level++) { xp += Wand.getExpToLevel(level); } return xp + (int) (expProgress * Wand.getExpToLevel(expLevel)); } protected void updateHotbarStatus() { Player player = mage == null ? null : mage.getPlayer(); if (player != null && LiveHotbar && getMode() == WandMode.INVENTORY && isInventoryOpen()) { mage.updateHotbarStatus(); } } @Override public boolean tickMana() { if (isHeroes) { HeroesManager heroes = controller.getHeroes(); if (heroes != null && mage != null && mage.isPlayer()) { Player player = mage.getPlayer(); effectiveManaMax = heroes.getMaxMana(player); effectiveManaRegeneration = heroes.getManaRegen(player); setManaMax(effectiveManaMax); setManaRegeneration(effectiveManaRegeneration); setMana(heroes.getMana(player)); return true; } return false; } return super.tickMana(); } @Override public void tick() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; super.tick(); if (usesMana() && !isInOffhand) { updateMana(); } if (player.isBlocking() && blockMageCooldown > 0) { mage.setRemainingCooldown(blockMageCooldown); } // Update hotbar glow if (!isInOffhand) { updateHotbarStatus(); } if (!passive) { updateEffects(); } } @Override public void armorUpdated() { updateMaxMana(true); } protected void updateMaxMana(boolean updateLore) { if (isHeroes) return; if (!hasOwnMana() && mageClass != null) { if (mageClass.updateMaxMana(mage) && updateLore) { updateLore(); } effectiveManaMax = mageClass.getEffectiveManaMax(); effectiveManaRegeneration = mageClass.getEffectiveManaRegeneration(); } else if (super.updateMaxMana(mage) && updateLore) { updateLore(); } } public void cycleSpells(int direction) { ArrayList<String> spells = new ArrayList<>(this.spells); if (spells.size() == 0) return; if (activeSpell == null) { setActiveSpell(spells.get(0)); return; } int spellIndex = 0; for (int i = 0; i < spells.size(); i++) { if (spells.get(i).equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + direction) % spells.size(); setActiveSpell(spells.get(spellIndex)); } public void cycleMaterials(int direction) { Set<String> materialsSet = getBrushes(); ArrayList<String> materials = new ArrayList<>(materialsSet); if (materials.size() == 0) return; if (activeBrush == null) { setActiveBrush(StringUtils.split(materials.get(0), '@')[0]); return; } int materialIndex = 0; for (int i = 0; i < materials.size(); i++) { if (StringUtils.split(materials.get(i),'@')[0].equals(activeBrush)) { materialIndex = i; break; } } materialIndex = (materialIndex + direction) % materials.size(); setActiveBrush(StringUtils.split(materials.get(materialIndex), '@')[0]); } @Nullable public Mage getActiveMage() { // TODO: Duplicate of #getMage() return mage; } public void setActiveMage(com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage instanceof Mage) { this.mage = (Mage)mage; armorUpdated(); } } @Nullable @Override public Color getEffectColor() { return effectColor == null ? null : effectColor.getColor(); } public Particle getEffectParticle() { return effectParticle; } @Nullable @Override public String getEffectParticleName() { return effectParticle == null ? null : effectParticle.name(); } @Nullable public Inventory getHotbar() { if (this.hotbars.size() == 0) return null; if (currentHotbar < 0 || currentHotbar >= this.hotbars.size()) { setCurrentHotbar(0); } return this.hotbars.get(currentHotbar); } public int getHotbarCount() { if (getMode() != WandMode.INVENTORY) return 0; return hotbars.size(); } public List<Inventory> getHotbars() { return hotbars; } @Override public boolean isQuickCastDisabled() { return quickCastDisabled; } public boolean isManualQuickCastDisabled() { return manualQuickCastDisabled; } @Override public boolean isQuickCast() { return quickCast; } public WandMode getMode() { return mode; } public WandMode getBrushMode() { return brushMode; } public void setMode(WandMode mode) { this.mode = mode; } public void setBrushMode(WandMode mode) { this.brushMode = mode; } @Override public boolean showCastMessages() { return quietLevel == 0; } @Override public boolean showMessages() { return quietLevel < 2; } public boolean isStealth() { return quietLevel > 2; } @Override public void setPath(String path) { String oldPath = this.path; this.path = path; setProperty("path", path); // Handle the case of a path upgrade meaning there are suddenly more spells or brushes available boolean updateInventory = limitBrushesToPath || limitSpellsToPath; if (!oldPath.equals(path) && updateInventory) { closeInventory(); if (limitSpellsToPath) { loadSpells(); } if (limitBrushesToPath) { loadBrushes(); } buildInventory(); } } /* * Public API Implementation */ @Override public boolean isLost(com.elmakers.mine.bukkit.api.wand.LostWand lostWand) { return this.id != null && this.id.equals(lostWand.getId()); } @Override public LostWand makeLost(Location location) { checkId(); saveState(); return new LostWand(this, location); } protected void showActiveIcon(boolean show) { if (this.icon == null || this.inactiveIcon == null || this.inactiveIcon.getMaterial() == Material.AIR || this.inactiveIcon.getMaterial() == null) return; if (this.icon.getMaterial() == Material.AIR || this.icon.getMaterial() == null) { this.icon.setMaterial(DefaultWandMaterial); } if (show) { if (inactiveIconDelay > 0) { Plugin plugin = controller.getPlugin(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { findItem(); icon.applyToItem(item); } }, inactiveIconDelay * 20 / 1000); } else { findItem(); icon.applyToItem(item); } } else { findItem(); inactiveIcon.applyToItem(this.item); } } public boolean activateOffhand(Mage mage) { return activate(mage, true); } @Override @Deprecated public void activate(com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage instanceof Mage) { activate((Mage)mage); } } public boolean activate(Mage mage) { return activate(mage, false); } public boolean activate(Mage mage, boolean offhand) { if (mage == null) return false; Player player = mage.getPlayer(); if (player == null) return false; if (!controller.hasWandPermission(player, this)) return false; InventoryView openInventory = player.getOpenInventory(); InventoryType inventoryType = openInventory.getType(); if (inventoryType == InventoryType.ENCHANTING || inventoryType == InventoryType.ANVIL) return false; if (hasUses && uses <= 0) { if (offhand) { player.getInventory().setItemInOffHand(new ItemStack(Material.AIR, 1)); } else { player.getInventory().setItemInMainHand(new ItemStack(Material.AIR, 1)); } return false; } if (!canUse(player)) { mage.sendMessage(getMessage("bound").replace("$name", getOwner())); return false; } if (this.isUpgrade) { controller.getLogger().warning("Activated an upgrade item- this shouldn't happen"); return false; } WandPreActivateEvent preActivateEvent = new WandPreActivateEvent(mage, this); Bukkit.getPluginManager().callEvent(preActivateEvent); if (preActivateEvent.isCancelled()) { return false; } boolean needsSave = false; if (hasId) { needsSave = this.checkId() || needsSave; } else { setProperty("id", null); } this.mage = mage; this.isInOffhand = offhand; this.heldSlot = offhand ? OFFHAND_SLOT : player.getInventory().getHeldItemSlot(); if (mageClassKeys != null && !mageClassKeys.isEmpty()) { MageClass mageClass = null; for (String mageClassKey : mageClassKeys) { mageClass = mage.getClass(mageClassKey); if (mageClass != null) break; } if (mageClass == null) { Integer lastSlot = mage.getLastActivatedSlot(); if (!offhand && (lastSlot == null || lastSlot != player.getInventory().getHeldItemSlot())) { mage.setLastActivatedSlot(player.getInventory().getHeldItemSlot()); mage.sendMessage(controller.getMessages().get("mage.no_class").replace("$name", getName())); } return false; } setMageClass(mageClass); if (!offhand) { mage.setActiveClass(mageClass.getKey()); } // This double-load here is not really ideal. // Seems hard to prevent without merging Wand construction and activation, though. loadProperties(); } mage.setLastActivatedSlot(player.getInventory().getHeldItemSlot()); // Check for replacement template String replacementTemplate = getString("replace_on_activate", ""); if (!replacementTemplate.isEmpty() && !replacementTemplate.equals(template)) { playEffects("replace"); setTemplate(replacementTemplate); loadProperties(); saveState(); return activate(mage, offhand); } // Since these wands can't be opened we will just show them as open when held // We have to delay this 1 tick so it happens after the Mage has accepted the Wand if (getMode() != WandMode.INVENTORY || offhand) { Plugin plugin = controller.getPlugin(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { showActiveIcon(true); playPassiveEffects("open"); } }, 1); } // Check for an empty wand and auto-fill if (!isUpgrade && (controller.fillWands() || autoFill)) { fill(mage.getPlayer(), controller.getMaxWandFillLevel()); needsSave = true; } if (isHeroes) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { Set<String> skills = heroes.getSkills(player); Collection<String> currentSpells = new ArrayList<>(getSpells()); for (String spellKey : currentSpells) { if (spellKey.startsWith("heroes*") && !skills.contains(spellKey.substring(7))) { removeSpell(spellKey); } } // Hack to prevent messaging this.mage = null; for (String skillKey : skills) { String heroesKey = "heroes*" + skillKey; if (!spells.contains(heroesKey)) { addSpell(heroesKey); } } this.mage = mage; } } // Check for auto-organize if (autoOrganize && !isUpgrade) { organizeInventory(mage); needsSave = true; } // Check for auto-alphabetize if (autoAlphabetize && !isUpgrade) { alphabetizeInventory(); needsSave = true; } boolean forceUpdate = false; if (checkInventoryForUpgrades()) { forceUpdate = true; needsSave = true; } // Check for auto-bind if (bound) { String mageName = ChatColor.stripColor(mage.getPlayer().getDisplayName()); String mageId = mage.getId(); boolean ownerRenamed = owner != null && ownerId != null && ownerId.equals(mageId) && !owner.equals(mageName); if (ownerId == null || ownerId.length() == 0 || owner == null || ownerRenamed) { takeOwnership(mage.getPlayer()); needsSave = true; } } // Check for randomized wands if (randomizeOnActivate) { randomize(); randomizeOnActivate = false; forceUpdate = true; needsSave = true; } // Don't build the inventory until activated so we can take Mage boosts into account if (offhand) { mage.setOffhandWand(this); } else { mage.setActiveWand(this); } buildInventory(); updateMaxMana(false); tick(); if (!isInOffhand) { updateMana(); } checkActiveMaterial(); if (needsSave) { saveState(); } updateActiveMaterial(); updateName(); updateLore(); // Play activate FX playPassiveEffects("activate"); lastSoundEffect = 0; lastParticleEffect = 0; lastSpellCast = 0; if (forceUpdate) { DeprecatedUtils.updateInventory(player); } return true; } public boolean checkInventoryForUpgrades() { boolean updated = false; Player player = mage == null ? null : mage.getPlayer(); if (player == null || mage.hasStoredInventory()) return false; // Check for spell or other special icons in the player's inventory Inventory inventory = player.getInventory(); ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; if (addItem(item)) { inventory.setItem(i, null); updated = true; } } return updated; } private void setOpenInventoryPage(int page) { this.openInventoryPage = page; this.setProperty("page", page); } @Override public boolean organizeInventory() { if (mage != null) { return organizeInventory(mage); } return false; } @Override public boolean organizeInventory(com.elmakers.mine.bukkit.api.magic.Mage mage) { WandOrganizer organizer = new WandOrganizer(this, mage); closeInventory(); organizer.organize(); setOpenInventoryPage(0); setCurrentHotbar(currentHotbar); if (autoOrganize) setProperty("organize", false); autoOrganize = false; updateSpellInventory(); updateBrushInventory(); if (this.mage != null) { buildInventory(); } return true; } @Override public boolean alphabetizeInventory() { WandOrganizer organizer = new WandOrganizer(this); closeInventory(); organizer.alphabetize(); setOpenInventoryPage(0); setCurrentHotbar(0); if (autoAlphabetize) setProperty("alphabetize", false); autoAlphabetize = false; updateSpellInventory(); updateBrushInventory(); if (mage != null) { buildInventory(); } return true; } @Override public com.elmakers.mine.bukkit.api.wand.Wand duplicate() { ItemStack newItem = InventoryUtils.getCopy(item); Wand newWand = controller.getWand(newItem); newWand.saveState(); return newWand; } @Override @Deprecated public boolean configure(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); configure(ConfigurationUtils.toConfigurationSection(convertedProperties)); return true; } @Override public void updated() { loadProperties(); if (mage != null) { buildInventory(); } saveState(); updateMaxMana(false); updateName(); updateLore(); } @Override public boolean isLocked() { return this.locked; } @Override public boolean upgradesAllowed() { return !this.locked || this.lockedAllowUpgrades; } @Override public void unlock() { locked = false; setProperty("locked", false); } public boolean isPassive() { return passive; } @Override public boolean canUse(Player player) { if (!bound || ownerId == null || ownerId.length() == 0) return true; if (controller.hasPermission(player, "Magic.wand.override_bind", false)) return true; String playerId = controller.getMageIdentifier().fromEntity(player); if (ownerId.equalsIgnoreCase(playerId)) { return true; } // Fall back to checking the UUID rather than the mage ID // This can be removed when all AMC wands have been migrated return ownerId.equals(player.getUniqueId().toString()); } @Override public boolean addSpell(String spellName) { if (!isModifiable()) return false; return forceAddSpell(spellName); } @Override public boolean forceAddSpell(String spellName) { SpellTemplate template = controller.getSpellTemplate(spellName); if (template == null) { return false; } SpellKey spellKey = template.getSpellKey(); if (limitSpellsToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsSpell(spellKey.getBaseKey())) return false; } if (!super.addSpell(spellName)) { return false; } saveInventory(); ItemStack spellItem = createSpellIcon(template); if (spellItem == null) { return false; } int level = spellKey.getLevel(); int inventoryCount = inventories.size(); int spellCount = spells.size(); // Look for existing spells for spell upgrades Integer inventorySlot = spellInventory.get(spellKey.getBaseKey()); clearSlot(inventorySlot); setSpellLevel(spellKey.getBaseKey(), level); spells.add(spellKey.getBaseKey()); if (activeSpell == null || activeSpell.isEmpty()) { setActiveSpell(spellKey.getBaseKey()); } addToInventory(spellItem, inventorySlot); checkSpellLevelsAndInventory(); updateInventory(); updateHasInventory(); saveState(); updateLore(); if (mage != null) { if (spells.size() != spellCount) { if (spellCount == 0) { if (leftClickAction == WandAction.CAST) { String message = getMessage("spell_instructions", "").replace("$wand", getName()); mage.sendMessage(message.replace("$spell", template.getName())); } } else if (spellCount == 1) { String controlKey = getControlKey(WandAction.TOGGLE); String inventoryMessage = null; switch (getMode()) { case INVENTORY: inventoryMessage = "inventory_instructions"; break; case CHEST: inventoryMessage = "chest_instructions"; break; case SKILLS: inventoryMessage = "skills_instructions"; break; case CYCLE: inventoryMessage = "cycle_instructions"; if (controlKey == null) { controlKey = getControlKey(WandAction.CYCLE); } break; case CAST: case NONE: // Ignore break; } if (controlKey != null && inventoryMessage != null) { controlKey = controller.getMessages().get("controls." + controlKey); mage.sendMessage(getMessage(inventoryMessage, "") .replace("$wand", getName()).replace("$toggle", controlKey).replace("$cycle", controlKey)); } } if (inventoryCount == 1 && inventories.size() > 1) { mage.sendMessage(getMessage("page_instructions", "").replace("$wand", getName())); } } } return true; } /** * Covers the special case of a wand having spell levels and inventory slots that came from configs, * but now we've modified the spells list and need to figure out if we also need to pesist the levels and * slots separately. * * <p>This should all be moved to CasterProperties at some point to handle the same sort of issues with mage class * configs. */ private void checkSpellLevelsAndInventory() { if (!spellLevels.isEmpty()) { MagicProperties storage = getStorage("spell_levels"); if (storage == null || storage == this) { if (!configuration.contains("spell_levels")) { configuration.set("spell_levels", spellLevels); } } } if (!spellInventory.isEmpty()) { MagicProperties storage = getStorage("spell_inventory"); if (storage == null || storage == this) { if (!configuration.contains("spell_inventory")) { configuration.set("spell_inventory", spellInventory); } } } } private void clearSlot(Integer slot) { if (slot != null) { Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); inventory.setItem(slot, null); } } @Override public String getMessage(String messageKey, String defaultValue) { String message = super.getMessage(messageKey, defaultValue); // Some special-casing here, not sure how to avoid. if (messageKey.equals("hotbar_count_usage")) { String controlKey = getControlKey(WandAction.CYCLE_HOTBAR); if (controlKey != null) { controlKey = controller.getMessages().get("controls." + controlKey); message = message.replace("$cycle_hotbar", controlKey); } else { return ""; } } return message; } @Override protected String getMessageKey(String key) { String wandKey = "wands." + template + "." + key; if (template != null && !template.isEmpty() && controller.getMessages().containsKey(wandKey)) { return wandKey; } return "wand." + key; } @Override protected String parameterizeMessage(String message) { return message.replace("$wand", getName()); } @Override public boolean hasBrush(String materialKey) { if (limitBrushesToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsBrush(materialKey)) return false; } return getBrushes().contains(materialKey); } @Override public boolean hasSpell(String spellName) { return hasSpell(new SpellKey(spellName)); } @Override public boolean hasSpell(SpellKey spellKey) { if (!spells.contains(spellKey.getBaseKey())) return false; if (limitSpellsToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsSpell(spellKey.getBaseKey())) return false; } int level = getSpellLevel(spellKey.getBaseKey()); return (level >= spellKey.getLevel()); } @Override public boolean addBrush(String materialKey) { if (!isModifiable()) return false; if (limitBrushesToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsBrush(materialKey)) return false; } if (!super.addBrush(materialKey)) return false; saveInventory(); ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) return false; int inventoryCount = inventories.size(); int brushCount = brushes.size(); brushInventory.put(materialKey, null); brushes.add(materialKey); addToInventory(itemStack); if (activeBrush == null || activeBrush.length() == 0) { activateBrush(materialKey); } else { updateInventory(); } updateHasInventory(); saveState(); updateLore(); if (mage != null) { if (brushCount == 0) { String controlKey = getControlKey(WandAction.TOGGLE); if (controlKey != null) { controlKey = controller.getMessages().get("controls." + controlKey); mage.sendMessage(getMessage("brush_instructions") .replace("$wand", getName()).replace("$toggle", controlKey)); } } if (inventoryCount == 1 && inventories.size() > 1) { mage.sendMessage(getMessage("page_instructions").replace("$wand", getName())); } } return true; } @Override public void setActiveBrush(String materialKey) { activateBrush(materialKey); if (materialKey == null || mage == null) { return; } com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); if (brush == null) { return; } boolean eraseWasActive = brush.isEraseModifierActive(); brush.activate(mage.getLocation(), materialKey); BrushMode mode = brush.getMode(); if (mode == BrushMode.CLONE) { mage.sendMessage(getMessage("clone_material_activated")); } else if (mode == BrushMode.REPLICATE) { mage.sendMessage(getMessage("replicate_material_activated")); } if (!eraseWasActive && brush.isEraseModifierActive()) { mage.sendMessage(getMessage("erase_modifier_activated")); } } public void setActiveBrush(ItemStack itemStack) { if (!isBrush(itemStack)) return; setActiveBrush(getBrush(itemStack)); } public void activateBrush(String materialKey) { this.activeBrush = materialKey; setProperty("active_brush", this.activeBrush); saveState(); updateActiveMaterial(); updateName(); updateHotbar(); } @Override public void setActiveSpell(String activeSpell) { if (activeSpell != null) { SpellKey spellKey = new SpellKey(activeSpell); this.activeSpell = spellKey.getBaseKey(); } else { this.activeSpell = null; } checkActiveSpell(); setProperty("active_spell", this.activeSpell); saveState(); updateName(); } protected void checkActiveSpell() { // Support wands with just an active spell and no spells list if (activeSpell != null && !spells.isEmpty() && !spells.contains(activeSpell)) { activeSpell = null; } } @Override public boolean removeBrush(String materialKey) { if (!isModifiable() || materialKey == null) return false; if (limitBrushesToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsBrush(materialKey)) return false; } if (!removeBrush(materialKey)) return false; saveInventory(); if (materialKey.equals(activeBrush)) { activeBrush = null; } clearSlot(brushInventory.get(materialKey)); brushInventory.remove(materialKey); boolean found = brushes.remove(materialKey); if (activeBrush == null && brushes.size() > 0) { activeBrush = brushes.iterator().next(); } updateActiveMaterial(); updateInventory(); updateBrushInventory(); saveState(); updateName(); updateLore(); return found; } @Override public boolean removeSpell(String spellName) { if (!isModifiable()) return false; SpellKey spellKey = new SpellKey(spellName); if (limitSpellsToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsSpell(spellKey.getBaseKey())) return false; } if (!super.removeSpell(spellName)) return false; saveInventory(); if (activeSpell != null) { SpellKey activeKey = new SpellKey(activeSpell); if (spellKey.getBaseKey().equals(activeKey.getBaseKey())) { setActiveSpell(null); } } clearSlot(spellInventory.get(spellKey.getBaseKey())); spells.remove(spellKey.getBaseKey()); spellLevels.remove(spellKey.getBaseKey()); spellInventory.remove(spellKey.getBaseKey()); if (activeSpell == null && spells.size() > 0) { setActiveSpell(spells.iterator().next()); } checkSpellLevelsAndInventory(); updateInventory(); updateHasInventory(); updateSpellInventory(); saveState(); updateName(); updateLore(); return true; } @Override public Map<String, String> getOverrides() { return castOverrides == null ? new HashMap<String, String>() : new HashMap<>(castOverrides); } @Override public void setOverrides(Map<String, String> overrides) { if (overrides == null) { this.castOverrides = null; } else { this.castOverrides = new HashMap<>(overrides); } updateOverrides(); } @Override public void removeOverride(String key) { if (castOverrides != null) { castOverrides.remove(key); updateOverrides(); } } @Override public void setOverride(String key, String value) { if (castOverrides == null) { castOverrides = new HashMap<>(); } if (value == null || value.length() == 0) { castOverrides.remove(key); } else { castOverrides.put(key, value); } updateOverrides(); } @Override public boolean addOverride(String key, String value) { if (castOverrides == null) { castOverrides = new HashMap<>(); } boolean modified = false; if (value == null || value.length() == 0) { modified = castOverrides.containsKey(key); castOverrides.remove(key); } else { String current = castOverrides.get(key); modified = current == null || !current.equals(value); castOverrides.put(key, value); } if (modified) { updateOverrides(); } return modified; } protected void updateOverrides() { if (castOverrides != null && !castOverrides.isEmpty()) { setProperty("overrides", castOverrides); } else { setProperty("overrides", null); } } public boolean hasStoredInventory() { return storedInventory != null; } public Inventory getStoredInventory() { return storedInventory; } public boolean addToStoredInventory(ItemStack item) { if (storedInventory == null) { return false; } HashMap<Integer, ItemStack> remainder = storedInventory.addItem(item); return remainder.size() == 0; } public void setHeldSlot(int slot) { this.heldSlot = slot; } public boolean storeInventory() { if (storedInventory != null) { if (mage != null) { mage.sendMessage("Your wand contains a previously stored inventory and will not activate, let go of it to clear."); } controller.getLogger().warning("Tried to store an inventory with one already present: " + (mage == null ? "?" : mage.getName())); return false; } Player player = mage.getPlayer(); if (player == null) { return false; } PlayerInventory inventory = player.getInventory(); storedInventory = CompatibilityUtils.createInventory(null, PLAYER_INVENTORY_SIZE, "Stored Inventory"); for (int i = 0; i < PLAYER_INVENTORY_SIZE; i++) { ItemStack item = inventory.getItem(i); storedInventory.setItem(i, item); if (i != heldSlot) { inventory.setItem(i, null); } } return true; } public boolean restoreInventory() { if (storedInventory == null) { return false; } Player player = mage.getPlayer(); if (player == null) { return false; } PlayerInventory inventory = player.getInventory(); for (int i = 0; i < storedInventory.getSize(); i++) { if (i != heldSlot) { inventory.setItem(i, storedInventory.getItem(i)); } } storedInventory = null; inventory.setHeldItemSlot(heldSlot); return true; } @Override @Deprecated public boolean isSoul() { return false; } public static boolean isBound(ItemStack item) { Object wandSection = InventoryUtils.getNode(item, WAND_KEY); if (wandSection == null) return false; String boundValue = InventoryUtils.getMetaString(wandSection, "owner_id"); return boundValue != null; } @Override public boolean isBound() { return bound; } @Nullable @Override public SpellTemplate getSpellTemplate(String spellKey) { SpellKey key = new SpellKey(spellKey); spellKey = key.getBaseKey(); if (!spells.contains(spellKey)) return null; Integer level = spellLevels.get(spellKey); if (level != null) { spellKey = new SpellKey(spellKey, level).getKey(); } return controller.getSpellTemplate(spellKey); } private void setSpellLevel(String spellKey, int level) { if (level <= 1) { spellLevels.remove(spellKey); } else { spellLevels.put(spellKey, level); } } @Override public int getSpellLevel(String spellKey) { Integer level = spellLevels.get(spellKey); return level == null ? 1 : level; } @Override public MageController getController() { return controller; } protected Map<String, Integer> getSpellInventory() { return new HashMap<>(spellInventory); } protected Map<String, Integer> getBrushInventory() { return new HashMap<>(brushInventory); } public Map<PotionEffectType, Integer> getPotionEffects() { return potionEffects; } @Override public float getHealthRegeneration() { Integer level = potionEffects.get(PotionEffectType.REGENERATION); return level != null && level > 0 ? (float)level : 0; } @Override public float getHungerRegeneration() { Integer level = potionEffects.get(PotionEffectType.SATURATION); return level != null && level > 0 ? (float)level : 0; } @Nullable @Override public WandTemplate getTemplate() { if (template == null || template.isEmpty()) return null; return controller.getWandTemplate(template); } public boolean playPassiveEffects(String effects) { WandTemplate wandTemplate = getTemplate(); if (wandTemplate != null && mage != null) { boolean offhandActive = mage.setOffhandActive(isInOffhand); boolean result = false; try { result = wandTemplate.playEffects(this, effects); } catch (Exception ex) { result = false; controller.getLogger().log(Level.WARNING, "Error playing effects " + effects + " from wand " + template, ex); } mage.setOffhandActive(offhandActive); return result; } return false; } @Override public boolean playEffects(String effects) { if (activeEffectsOnly && !inventoryIsOpen) { return false; } return playPassiveEffects(effects); } @Override public WandAction getDropAction() { return dropAction; } @Override public WandAction getRightClickAction() { return rightClickAction; } @Override public WandAction getLeftClickAction() { return leftClickAction; } @Override public WandAction getSwapAction() { return swapAction; } @Override public boolean performAction(WandAction action) { WandMode mode = getMode(); switch (action) { case CAST: cast(); break; case ALT_CAST: alternateCast(); break; case ALT_CAST2: alternateCast2(); break; case TOGGLE: if (mode == WandMode.CYCLE) { cycleActive(1); return true; } if (mode != WandMode.CHEST && mode != WandMode.INVENTORY && mode != WandMode.SKILLS) return false; toggleInventory(); break; case CYCLE: cycleActive(1); break; case CYCLE_REVERSE: cycleActive(-1); break; case CYCLE_HOTBAR: if (mode != WandMode.INVENTORY || !isInventoryOpen()) return false; if (getHotbarCount() > 1) { cycleHotbar(1); } else { closeInventory(); } break; case CYCLE_HOTBAR_REVERSE: if (mode != WandMode.INVENTORY) return false; if (getHotbarCount() > 1) { cycleHotbar(-1); } else if (isInventoryOpen()) { closeInventory(); } else { return false; } break; default: return false; } return true; } @Override public boolean checkAndUpgrade(boolean quiet) { WandUpgradePath path = getPath(); WandUpgradePath nextPath = path != null ? path.getUpgrade() : null; if (nextPath == null) { return true; } if (canProgress()) { return true; } if (!path.checkUpgradeRequirements(this, quiet ? null : mage)) { return false; } path.upgrade(this, mage); return true; } @Override public boolean hasUpgrade() { WandUpgradePath path = getPath(); return path != null && path.hasUpgrade(); } @Override public boolean checkUpgrade(boolean quiet) { WandUpgradePath path = getPath(); return path == null || !path.hasUpgrade() ? false : path.checkUpgradeRequirements(this, quiet ? null : mage); } @Override @Deprecated public boolean upgrade(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); return upgrade(ConfigurationUtils.toConfigurationSection(convertedProperties)); } @Override public boolean upgrade(boolean quiet) { WandUpgradePath path = getPath(); if (path == null) return false; path.upgrade(this, quiet ? null : mage); return true; } @Override public boolean isBlocked(double angle) { if (mage == null) return false; if (blockChance == 0) return false; if (blockFOV > 0 && angle > blockFOV) return false; long lastBlock = mage.getLastBlockTime(); if (blockCooldown > 0 && lastBlock > 0 && lastBlock + blockCooldown > System.currentTimeMillis()) return false; boolean isBlocked = Math.random() <= blockChance; if (isBlocked) { playEffects("spell_blocked"); mage.setLastBlockTime(System.currentTimeMillis()); } return isBlocked; } @Override public boolean isReflected(double angle) { if (mage == null) return false; if (blockReflectChance == 0) return false; if (blockFOV > 0 && angle > blockFOV) return false; long lastBlock = mage.getLastBlockTime(); if (blockCooldown > 0 && lastBlock > 0 && lastBlock + blockCooldown > System.currentTimeMillis()) return false; boolean isReflected = Math.random() <= blockReflectChance; if (isReflected) { playEffects("spell_reflected"); if (mage != null) mage.setLastBlockTime(System.currentTimeMillis()); } return isReflected; } @Nullable @Override public Location getLocation() { if (mage == null) { return null; } Location wandLocation = mage.getEyeLocation(); wandLocation = mage.getOffsetLocation(wandLocation, isInOffhand, castLocation == null ? DEFAULT_CAST_OFFSET : castLocation); return wandLocation; } @Nullable @Override public Mage getMage() { return mage; } @Override public @Nullable MageClass getMageClass() { return mageClass; } @Override public @Nullable String getMageClassKey() { if (mageClass != null) { return mageClass.getKey(); } return mageClassKeys == null || mageClassKeys.isEmpty() ? null : mageClassKeys.get(0); } public void setCurrentHotbar(int hotbar) { this.currentHotbar = hotbar; setProperty("hotbar", currentHotbar); } public int getInventorySize() { WandMode mode = getMode(); if (mode == WandMode.CHEST || mode == WandMode.SKILLS) { return 9 * inventoryRows; } return INVENTORY_SIZE; } public float getSPMultiplier() { return spMultiplier; } public boolean usesSP() { return hasSpellProgression && controller.isSPEnabled() && controller.isSPEarnEnabled() && spMultiplier > 0; } @Override public int getHeldSlot() { return heldSlot; } @Nullable @Override protected BaseMagicConfigurable getStorage(MagicPropertyType propertyType) { switch (propertyType) { case WAND: return this; case SUBCLASS: return mageClass; case CLASS: if (mageClass == null) { if (mage == null) { controller.getLogger().warning("Something is trying to modify a wand when it's not held, this may not work out"); } else { controller.getLogger().warning("Something is trying to modify a wand that has no class, this may not work out"); } Thread.dumpStack(); } return mageClass == null ? null : mageClass.getRoot(); case MAGE: if (mage == null) { controller.getLogger().warning("Something is trying to modify a wand when it's not held, this may not work out"); Thread.dumpStack(); } return mage == null ? null : mage.getProperties(); } return null; } @Override public boolean isPlayer() { return mage == null ? false : mage.isPlayer(); } @Nullable @Override public Player getPlayer() { return mage == null ? null : mage.getPlayer(); } @Override @Nonnull public WandEffectContext getEffectContext() { if (effectContext == null || (effectContext.getMage() != mage)) { // Lazy load or mage has changed effectContext = new WandEffectContext(mage, this); } return verifyNotNull(effectContext); } @Override public Wand getWand() { return this; } }
Magic/src/main/java/com/elmakers/mine/bukkit/wand/Wand.java
package com.elmakers.mine.bukkit.wand; import static com.google.common.base.Verify.verifyNotNull; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Set; import java.util.UUID; import java.util.logging.Level; import javax.annotation.Nonnull; import javax.annotation.Nullable; import org.apache.commons.lang.StringUtils; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Particle; import org.bukkit.block.BlockFace; import org.bukkit.command.CommandSender; import org.bukkit.configuration.ConfigurationSection; import org.bukkit.configuration.MemoryConfiguration; import org.bukkit.entity.Entity; import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.InventoryView; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.PlayerInventory; import org.bukkit.plugin.Plugin; import org.bukkit.potion.PotionEffectType; import org.bukkit.util.Vector; import com.elmakers.mine.bukkit.api.block.BrushMode; import com.elmakers.mine.bukkit.api.event.WandPreActivateEvent; import com.elmakers.mine.bukkit.api.magic.MageClassTemplate; import com.elmakers.mine.bukkit.api.magic.MageController; import com.elmakers.mine.bukkit.api.magic.MagicProperties; import com.elmakers.mine.bukkit.api.magic.MaterialSet; import com.elmakers.mine.bukkit.api.magic.Messages; import com.elmakers.mine.bukkit.api.spell.CostReducer; import com.elmakers.mine.bukkit.api.spell.Spell; import com.elmakers.mine.bukkit.api.spell.SpellKey; import com.elmakers.mine.bukkit.api.spell.SpellTemplate; import com.elmakers.mine.bukkit.api.wand.WandAction; import com.elmakers.mine.bukkit.block.MaterialAndData; import com.elmakers.mine.bukkit.block.MaterialBrush; import com.elmakers.mine.bukkit.effect.EffectPlayer; import com.elmakers.mine.bukkit.effect.SoundEffect; import com.elmakers.mine.bukkit.effect.WandEffectContext; import com.elmakers.mine.bukkit.effect.builtin.EffectRing; import com.elmakers.mine.bukkit.heroes.HeroesManager; import com.elmakers.mine.bukkit.magic.BaseMagicConfigurable; import com.elmakers.mine.bukkit.magic.Mage; import com.elmakers.mine.bukkit.magic.MageClass; import com.elmakers.mine.bukkit.magic.MagicAttribute; import com.elmakers.mine.bukkit.magic.MagicController; import com.elmakers.mine.bukkit.magic.MagicPropertyType; import com.elmakers.mine.bukkit.utility.ColorHD; import com.elmakers.mine.bukkit.utility.CompatibilityUtils; import com.elmakers.mine.bukkit.utility.ConfigurationUtils; import com.elmakers.mine.bukkit.utility.DeprecatedUtils; import com.elmakers.mine.bukkit.utility.InventoryUtils; import com.elmakers.mine.bukkit.utility.NMSUtils; import com.google.common.base.Preconditions; public class Wand extends WandProperties implements CostReducer, com.elmakers.mine.bukkit.api.wand.Wand { public static final int OFFHAND_SLOT = 40; public static final int INVENTORY_SIZE = 27; public static final int PLAYER_INVENTORY_SIZE = 36; public static final int INVENTORY_ORGANIZE_BUFFER = 4; public static final int HOTBAR_SIZE = 9; public static final int HOTBAR_INVENTORY_SIZE = HOTBAR_SIZE - 1; public static final float DEFAULT_SPELL_COLOR_MIX_WEIGHT = 0.0001f; public static boolean FILL_CREATOR = false; public static Vector DEFAULT_CAST_OFFSET = new Vector(0, 0, 0.5); public static String DEFAULT_WAND_TEMPLATE = "default"; private static final String[] EMPTY_PARAMETERS = new String[0]; private static final Random random = new Random(); /** * The item as it appears in the inventory of the player. */ protected @Nullable ItemStack item; /** * The currently active mage. * * <p>Is only set when the wand is active or when the wand is * used for off-hand casting. */ protected @Nullable Mage mage; protected @Nullable WandEffectContext effectContext; // Cached state private String id = ""; private List<Inventory> hotbars; private List<Inventory> inventories; private Map<String, Integer> spellInventory = new HashMap<>(); private Set<String> spells = new LinkedHashSet<>(); private Map<String, Integer> spellLevels = new HashMap<>(); private Map<String, Integer> brushInventory = new HashMap<>(); private Set<String> brushes = new LinkedHashSet<>(); private String activeSpell = ""; private String alternateSpell = ""; private String alternateSpell2 = ""; private String activeBrush = ""; protected String wandName = ""; protected String description = ""; private String owner = ""; private String ownerId = ""; private String template = ""; private String path = ""; private List<String> mageClassKeys = null; private boolean superProtected = false; private boolean superPowered = false; private boolean glow = false; private boolean bound = false; private boolean indestructible = false; private boolean undroppable = false; private boolean keep = false; private boolean passive = false; private boolean autoOrganize = false; private boolean autoAlphabetize = false; private boolean autoFill = false; private boolean isUpgrade = false; private boolean randomizeOnActivate = true; private boolean rename = false; private boolean renameDescription = false; private boolean quickCast = false; private boolean quickCastDisabled = false; private boolean manualQuickCastDisabled = false; private boolean isInOffhand = false; private boolean hasId = false; private int inventoryRows = 1; private Vector castLocation; private WandAction leftClickAction = WandAction.NONE; private WandAction rightClickAction = WandAction.NONE; private WandAction dropAction = WandAction.NONE; private WandAction swapAction = WandAction.NONE; private MaterialAndData icon = null; private MaterialAndData upgradeIcon = null; private MaterialAndData inactiveIcon = null; private int inactiveIconDelay = 0; private String upgradeTemplate = null; protected float consumeReduction = 0; protected float cooldownReduction = 0; protected float costReduction = 0; protected Map<String, Double> protection; private float power = 0; private float spMultiplier = 1; private float blockFOV = 0; private float blockChance = 0; private float blockReflectChance = 0; private int blockMageCooldown = 0; private int blockCooldown = 0; private int maxEnchantCount = 0; private int enchantCount = 0; private boolean hasInventory = false; private boolean locked = false; private boolean lockedAllowUpgrades = false; private boolean forceUpgrade = false; private boolean isHeroes = false; private int uses = 0; private boolean hasUses = false; private boolean isSingleUse = false; private boolean limitSpellsToPath = false; private boolean limitBrushesToPath = false; private float manaPerDamage = 0; private ColorHD effectColor = null; private float effectColorSpellMixWeight = DEFAULT_SPELL_COLOR_MIX_WEIGHT; private Particle effectParticle = null; private float effectParticleData = 0; private int effectParticleCount = 0; private int effectParticleInterval = 0; private double effectParticleMinVelocity = 0; private double effectParticleRadius = 0; private double effectParticleOffset = 0; private boolean effectBubbles = false; private boolean activeEffectsOnly = false; private EffectRing effectPlayer = null; private int castInterval = 0; private double castMinVelocity = 0; private Vector castVelocityDirection = null; private String castSpell = null; private ConfigurationSection castParameters = null; private Map<PotionEffectType, Integer> potionEffects = new HashMap<>(); private SoundEffect effectSound = null; private int effectSoundInterval = 0; private int quietLevel = 0; private Map<String, String> castOverrides = null; // Transient state private boolean hasSpellProgression = false; private long lastSoundEffect; private long lastParticleEffect; private long lastSpellCast; // Inventory functionality private WandMode mode = null; private WandMode brushMode = null; private int openInventoryPage = 0; private boolean inventoryIsOpen = false; private boolean inventoryWasOpen = false; private Inventory displayInventory = null; private int currentHotbar = 0; public static WandManaMode manaMode = WandManaMode.BAR; public static WandManaMode spMode = WandManaMode.NUMBER; public static boolean regenWhileInactive = true; public static Material DefaultUpgradeMaterial = Material.NETHER_STAR; public static Material DefaultWandMaterial = Material.BLAZE_ROD; public static Material EnchantableWandMaterial = null; public static boolean SpellGlow = false; public static boolean BrushGlow = false; public static boolean BrushItemGlow = true; public static boolean LiveHotbar = true; public static boolean LiveHotbarSkills = false; public static boolean LiveHotbarCooldown = true; public static boolean Unbreakable = false; public static boolean Unstashable = true; public static SoundEffect inventoryOpenSound = null; public static SoundEffect inventoryCloseSound = null; public static SoundEffect inventoryCycleSound = null; public static SoundEffect noActionSound = null; public static String WAND_KEY = "wand"; public static String UPGRADE_KEY = "wand_upgrade"; public static String WAND_SELF_DESTRUCT_KEY = null; public static byte HIDE_FLAGS = 63; public static String brushSelectSpell = ""; private Inventory storedInventory = null; private int heldSlot = 0; public Wand(MagicController controller) { super(controller); hotbars = new ArrayList<>(); inventories = new ArrayList<>(); } /** * @deprecated Use {@link MagicController#getWand(ItemStack)}. */ @Deprecated public Wand(MagicController controller, ItemStack itemStack) { this(controller); Preconditions.checkNotNull(itemStack); if (itemStack.getType() == Material.AIR) { itemStack.setType(DefaultWandMaterial); } this.icon = new MaterialAndData(itemStack); item = itemStack; boolean needsSave = false; boolean isWand = isWand(item); boolean isUpgradeItem = isUpgrade(item); if (isWand || isUpgradeItem) { ConfigurationSection wandConfig = itemToConfig(item, new MemoryConfiguration()); // Check for template migration WandTemplate wandTemplate = controller.getWandTemplate(wandConfig.getString("template")); WandTemplate migrateTemplate = wandTemplate == null ? null : wandTemplate.getMigrateTemplate(); if (migrateTemplate != null) { wandConfig.set("template", migrateTemplate.getKey()); } // Check for wand data migration int version = wandConfig.getInt("version", 0); if (version < CURRENT_VERSION) { // Migration will be handled by CasterProperties, this is just here // So that we save the data after to avoid re-migrating. needsSave = true; } randomizeOnActivate = !wandConfig.contains("icon"); load(wandConfig); } else { updateIcon(); needsSave = true; } loadProperties(); // Migrate old upgrade items if ((isUpgrade || isUpgradeItem) && isWand) { needsSave = true; InventoryUtils.removeMeta(item, WAND_KEY); } if (needsSave) { saveState(); updateName(); updateLore(); } } public Wand(MagicController controller, ConfigurationSection config) { this(controller, DefaultWandMaterial, (short)0); load(config); loadProperties(); updateName(); updateLore(); saveState(); } protected Wand(MagicController controller, String templateName) throws UnknownWandException { this(controller); // Default to "default" wand if (templateName == null || templateName.length() == 0) { templateName = DEFAULT_WAND_TEMPLATE; } // Check for randomized/pre-enchanted wands int level = 0; if (templateName.contains("(")) { String levelString = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1); try { level = Integer.parseInt(levelString); } catch (Exception ex) { throw new IllegalArgumentException(ex); } templateName = templateName.substring(0, templateName.indexOf('(')); } WandTemplate template = controller.getWandTemplate(templateName); if (template == null) { throw new UnknownWandException(templateName); } WandTemplate migrateTemplate = template.getMigrateTemplate(); if (migrateTemplate != null) { template = migrateTemplate; templateName = migrateTemplate.getKey(); } setTemplate(templateName); setProperty("version", CURRENT_VERSION); ConfigurationSection templateConfig = template.getConfiguration(); if (templateConfig == null) { throw new UnknownWandException(templateName); } // Load all properties loadProperties(); // Enchant, if an enchanting level was provided if (level > 0) { // Account for randomized locked wands boolean wasLocked = locked; locked = false; randomize(level, false, null, true); locked = wasLocked; } // Don't randomize now if set to randomize later // Otherwise, do this here so the description updates if (!randomizeOnActivate) { randomize(); } updateName(); updateLore(); saveState(); } public Wand(MagicController controller, Material icon, short iconData) { // This will make the Bukkit ItemStack into a real ItemStack with NBT data. this(controller, InventoryUtils.makeReal(new ItemStack(icon, 1, iconData))); saveState(); updateName(); } @Override @SuppressWarnings("unchecked") protected void migrate(int version, ConfigurationSection wandConfig) { // First migration, clean out wand data that matches template // We've done this twice now, the second time to handle removing hard-coded defaults that // were not present in the template configs. if (version <= 1) { ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(wandConfig.getString("template")); if (templateConfig != null) { // This is an unfortunate special case for wands waiting to be randomized String randomizeIcon = templateConfig.getString("randomize_icon"); String currentIcon = wandConfig.getString("icon"); if (randomizeIcon != null && currentIcon != null && randomizeIcon.equals(currentIcon)) { wandConfig.set("icon", null); } // This was a potentially leftover property from randomized wands we can ditch wandConfig.set("randomize", null); Set<String> keys = templateConfig.getKeys(false); for (String key : keys) { Object templateData = templateConfig.get(key); Object wandData = wandConfig.get(key); if (wandData == null) continue; String templateString = templateData.toString(); String wandString = wandData.toString(); if (templateData instanceof List) { templateString = templateString.substring(1, templateString.length() - 1); templateString = templateString.replace(", ", ","); templateData = templateString; } if (wandString.equalsIgnoreCase(templateString)) { wandConfig.set(key, null); continue; } try { double numericValue = Double.parseDouble(wandString); double numericTemplate = Double.parseDouble(templateString); if (numericValue == numericTemplate) { wandConfig.set(key, null); continue; } } catch (NumberFormatException ignored) { } if (wandData.equals(templateData)) { wandConfig.set(key, null); } } } } // Remove icon if matches template if (version <= 3) { ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(wandConfig.getString("template")); String templateIcon = templateConfig == null ? null : templateConfig.getString("icon"); if (templateIcon != null && templateIcon.equals(wandConfig.getString("icon", ""))) { wandConfig.set("icon", null); } } // Migration: remove level from spell inventory if (version <= 4) { Object spellInventoryRaw = wandConfig.get("spell_inventory"); if (spellInventoryRaw != null) { Map<String, ? extends Object> spellInventory = null; Map<String, Integer> newSpellInventory = new HashMap<>(); if (spellInventoryRaw instanceof Map) { spellInventory = (Map<String, ? extends Object>)spellInventoryRaw; } else if (spellInventoryRaw instanceof ConfigurationSection) { spellInventory = NMSUtils.getMap((ConfigurationSection)spellInventoryRaw); } if (spellInventory != null) { for (Map.Entry<String, ? extends Object> spellEntry : spellInventory.entrySet()) { Object slot = spellEntry.getValue(); if (slot != null && slot instanceof Integer) { SpellKey spellKey = new SpellKey(spellEntry.getKey()); // Prefer to use the base spell if present since that is what we'd be // using on load. Object testSlot = spellInventory.get(spellKey.getBaseKey()); if (testSlot != null) { slot = testSlot; } newSpellInventory.put(spellKey.getBaseKey(), (Integer)slot); } } wandConfig.set("spell_inventory", newSpellInventory); } } } // Migration: move attributes to item_attributes if (version <= 5) { ConfigurationSection attributes = wandConfig.getConfigurationSection("attributes"); wandConfig.set("attributes", null); wandConfig.set("item_attributes", attributes); } super.migrate(version, wandConfig); } @Override public void load(ConfigurationSection configuration) { if (configuration != null) { setTemplate(configuration.getString("template")); } super.load(configuration); } protected void updateHotbarCount() { int hotbarCount = Math.max(1, getInt("hotbar_count", 1)); if (hotbarCount != hotbars.size()) { if (isInventoryOpen()) { closeInventory(); } hotbars.clear(); while (hotbars.size() < hotbarCount) { hotbars.add(CompatibilityUtils.createInventory(null, HOTBAR_INVENTORY_SIZE, "Wand")); } while (hotbars.size() > hotbarCount) { hotbars.remove(0); } } } @Override public void unenchant() { controller.cleanItem(item); clear(); } public void updateItemIcon() { setIcon(icon); } protected void updateIcon() { if (icon != null && icon.getMaterial() != null && icon.getMaterial() != Material.AIR) { String iconKey = icon.getKey(); if (iconKey != null && iconKey.isEmpty()) { iconKey = null; } WandTemplate template = getTemplate(); String templateIcon = template != null ? template.getProperty("icon", "") : null; if (templateIcon == null || !templateIcon.equals(iconKey)) { setProperty("icon", iconKey); } } } @Override public void setInactiveIcon(com.elmakers.mine.bukkit.api.block.MaterialAndData materialData) { if (materialData == null) { inactiveIcon = null; } else if (materialData instanceof MaterialAndData) { inactiveIcon = ((MaterialAndData)materialData); } else { inactiveIcon = new MaterialAndData(materialData); } String inactiveIconKey = null; if (inactiveIcon != null && inactiveIcon.getMaterial() != null && inactiveIcon.getMaterial() != Material.AIR) { inactiveIconKey = inactiveIcon.getKey(); if (inactiveIconKey != null && inactiveIconKey.isEmpty()) { inactiveIconKey = null; } } setProperty("inactive_icon", inactiveIconKey); updateItemIcon(); } public void setIcon(Material material, byte data) { setIcon(material == null ? null : new MaterialAndData(material, data)); updateIcon(); } @Override public void setIcon(com.elmakers.mine.bukkit.api.block.MaterialAndData materialData) { if (materialData instanceof MaterialAndData) { setIcon((MaterialAndData)materialData); } else { setIcon(new MaterialAndData(materialData)); } updateIcon(); } public void setIcon(MaterialAndData materialData) { if (materialData == null || !materialData.isValid()) return; if (materialData.getMaterial() == Material.AIR || materialData.getMaterial() == null) { materialData.setMaterial(DefaultWandMaterial); } icon = materialData; if (item == null) { item = InventoryUtils.makeReal(this.icon.getItemStack(1)); } Short durability = null; if (!indestructible && !isUpgrade && icon.getMaterial().getMaxDurability() > 0) { durability = item.getDurability(); } try { if (inactiveIcon == null || (mage != null && getMode() == WandMode.INVENTORY && isInventoryOpen())) { icon.applyToItem(item); } else { inactiveIcon.applyToItem(item); } } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Unable to apply wand icon", ex); item.setType(DefaultWandMaterial); } if (durability != null) { item.setDurability(durability); } // Make indestructible // The isUpgrade checks here and above are for using custom icons in 1.9, this is a bit hacky. if ((indestructible || Unbreakable || isUpgrade) && !manaMode.useDurability()) { CompatibilityUtils.makeUnbreakable(item); } else { CompatibilityUtils.removeUnbreakable(item); } CompatibilityUtils.hideFlags(item, getProperty("hide_flags", HIDE_FLAGS)); } @Override public void makeUpgrade() { if (!isUpgrade) { isUpgrade = true; String oldName = wandName; String newName = getMessage("upgrade_name"); newName = newName.replace("$name", oldName); String newDescription = controller.getMessages().get("wand.upgrade_default_description"); if (template != null && template.length() > 0) { newDescription = controller.getMessages().get("wands." + template + ".upgrade_description", description); } setIcon(DefaultUpgradeMaterial, (byte) 0); setName(newName); setDescription(newDescription); InventoryUtils.removeMeta(item, WAND_KEY); saveState(); updateName(true); updateLore(); } } public void newId() { id = UUID.randomUUID().toString(); setProperty("id", id); } public boolean checkId() { if (id == null || id.length() == 0) { newId(); return true; } return false; } @Override public String getId() { return id; } public boolean isModifiable() { return !locked; } @Override public boolean isIndestructible() { return indestructible; } @Override public boolean isUndroppable() { return undroppable; } public boolean isUpgrade() { return isUpgrade; } public static boolean isUpgrade(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, UPGRADE_KEY); } @Override public boolean usesMana() { if (isCostFree()) return false; return getManaMax() > 0 || (isHeroes && mage != null); } @Override public void removeMana(float amount) { if (isHeroes && mage != null) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { heroes.removeMana(mage.getPlayer(), (int)Math.ceil(amount)); } } super.removeMana(amount); updateMana(); } @Override public float getCostReduction() { if (mage != null) { float reduction = mage.getCostReduction(); return passive ? reduction : stackPassiveProperty(reduction, costReduction); } return costReduction; } @Override public float getCooldownReduction() { if (mage != null) { float reduction = mage.getCooldownReduction(); return passive ? reduction : stackPassiveProperty(reduction, cooldownReduction); } return cooldownReduction; } @Override public float getConsumeReduction() { if (mage != null) { float reduction = mage.getConsumeReduction(); return passive ? reduction : stackPassiveProperty(reduction, consumeReduction); } return consumeReduction; } @Override public float getCostScale() { return 1; } @Override public boolean hasInventory() { return hasInventory; } @Override public float getPower() { return power; } @Override public boolean isSuperProtected() { return superProtected; } @Override public boolean isSuperPowered() { return superPowered; } @Override public boolean isConsumeFree() { return consumeReduction >= 1; } @Override public boolean isCooldownFree() { return cooldownReduction > 1; } @Override public String getName() { return ChatColor.translateAlternateColorCodes('&', wandName); } public String getDescription() { return description; } public String getOwner() { return owner == null ? "" : owner; } public String getOwnerId() { return ownerId; } @Override public long getWorth() { long worth = 0; // TODO: Item properties, brushes, etc Set<String> spells = getSpells(); for (String spellKey : spells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); if (spell != null) { worth = (long)(worth + spell.getWorth()); } } return worth; } @Override public void setName(String name) { wandName = ChatColor.stripColor(name); setProperty("name", wandName); updateName(); } public void setTemplate(String templateName) { this.template = templateName; WandTemplate wandTemplate = controller.getWandTemplate(templateName); if (wandTemplate != null) { setWandTemplate(wandTemplate); } setProperty("template", template); } @Override public String getTemplateKey() { return this.template; } @Override public boolean hasTag(String tag) { WandTemplate template = getTemplate(); return template != null && template.hasTag(tag); } @Override public WandUpgradePath getPath() { String pathKey = path; if (pathKey == null || pathKey.length() == 0) { pathKey = controller.getDefaultWandPath(); } return WandUpgradePath.getPath(pathKey); } public boolean hasPath() { return path != null && path.length() > 0; } @Override public void setDescription(String description) { this.description = description; setProperty("description", description); updateLore(); } public boolean tryToOwn(Player player) { if (ownerId == null || ownerId.length() == 0) { takeOwnership(player); return true; } return false; } public void takeOwnership(Player player) { Mage mage = this.mage; if (mage == null) { mage = controller.getMage(player); } if ((ownerId == null || ownerId.length() == 0) && quietLevel < 2) { mage.sendMessage(getMessage("bound_instructions", "").replace("$wand", getName())); String spellKey = getActiveSpellKey(); SpellTemplate spellTemplate = spellKey != null && !spellKey.isEmpty() ? controller.getSpellTemplate(spellKey) : null; if (spellTemplate != null) { String message = getMessage("spell_instructions", "").replace("$wand", getName()); mage.sendMessage(message.replace("$spell", spellTemplate.getName())); } if (spells.size() > 1) { String controlKey = getControlKey(WandAction.TOGGLE); if (controlKey != null) { controlKey = controller.getMessages().get("controls." + controlKey); mage.sendMessage(getMessage("inventory_instructions", "") .replace("$wand", getName()).replace("$toggle", controlKey)); } } com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); if (path != null) { String message = getMessage("enchant_instructions", "").replace("$wand", getName()); mage.sendMessage(message); } } owner = ChatColor.stripColor(player.getDisplayName()); ownerId = mage.getId(); setProperty("owner", owner); setProperty("owner_id", ownerId); updateLore(); saveState(); } @Nullable public String getControlKey(WandAction action) { String controlKey = null; if (rightClickAction == action) { controlKey = "right_click"; } else if (dropAction == action) { controlKey = "drop"; } else if (leftClickAction == action) { controlKey = "left_click"; } else if (swapAction == action) { controlKey = "swap"; } return controlKey; } @Nullable @Override public ItemStack getItem() { return item; } public void setItem(ItemStack item) { this.item = item; } @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getIcon() { return icon; } @Override public com.elmakers.mine.bukkit.api.block.MaterialAndData getInactiveIcon() { return inactiveIcon; } protected List<Inventory> getAllInventories() { int hotbarCount = getHotbarCount(); List<Inventory> allInventories = new ArrayList<>(inventories.size() + hotbarCount); if (hotbarCount > 0) { allInventories.addAll(hotbars); } allInventories.addAll(inventories); return allInventories; } @Override public Set<String> getBaseSpells() { return spells; } @Override protected @Nonnull Map<String, Integer> getSpellLevels() { return spellLevels; } @Override public Set<String> getSpells() { Set<String> spellSet = new HashSet<>(); for (String key : spells) { Integer level = spellLevels.get(key); if (level != null) { spellSet.add(new SpellKey(key, level).getKey()); } else { spellSet.add(key); } } return spellSet; } @Override public Set<String> getBrushes() { return brushes; } @Nullable protected Integer parseSlot(String[] pieces) { Integer slot = null; if (pieces.length > 1) { try { slot = Integer.parseInt(pieces[1]); } catch (Exception ex) { slot = null; } if (slot != null && slot < 0) { slot = null; } } return slot; } protected void addToInventory(ItemStack itemStack, Integer slot) { if (slot == null) { addToInventory(itemStack); return; } Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); ItemStack existing = inventory.getItem(slot); inventory.setItem(slot, itemStack); if (existing != null && existing.getType() != Material.AIR) { addToInventory(existing); } } public void addToInventory(ItemStack itemStack) { if (itemStack == null || itemStack.getType() == Material.AIR) { return; } if (getBrushMode() != WandMode.INVENTORY && isBrush(itemStack)) { String brushKey = getBrush(itemStack); if (!MaterialBrush.isSpecialMaterialKey(brushKey) || MaterialBrush.isSchematic(brushKey)) { return; } } List<Inventory> checkInventories = getAllInventories(); boolean added = false; WandMode mode = getMode(); int fullSlot = 0; for (Inventory inventory : checkInventories) { int inventorySize = inventory.getSize(); Integer slot = null; int freeSpace = 0; for (int i = 0; i < inventorySize && freeSpace < INVENTORY_ORGANIZE_BUFFER; i++) { ItemStack existing = inventory.getItem(i); if (InventoryUtils.isEmpty(existing)) { if (slot == null) { slot = i; } freeSpace++; } } // Don't leave free space in hotbars if (slot != null && (freeSpace >= INVENTORY_ORGANIZE_BUFFER || inventorySize == HOTBAR_INVENTORY_SIZE || mode == WandMode.CHEST)) { added = true; inventory.setItem(slot, itemStack); fullSlot += slot; break; } fullSlot += inventory.getSize(); } if (!added) { fullSlot = getHotbarSize() + getInventorySize() * inventories.size(); Inventory newInventory = CompatibilityUtils.createInventory(null, getInventorySize(), "Wand"); newInventory.addItem(itemStack); inventories.add(newInventory); } updateSlot(fullSlot, itemStack); } protected @Nonnull Inventory getInventoryByIndex(int inventoryIndex) { // Auto create while (inventoryIndex >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, getInventorySize(), "Wand")); } return inventories.get(inventoryIndex); } protected int getHotbarSize() { if (getMode() != WandMode.INVENTORY) return 0; return hotbars.size() * HOTBAR_INVENTORY_SIZE; } protected @Nonnull Inventory getInventory(int slot) { int hotbarSize = getHotbarSize(); if (slot < hotbarSize) { return hotbars.get(slot / HOTBAR_INVENTORY_SIZE); } int inventoryIndex = (slot - hotbarSize) / getInventorySize(); return getInventoryByIndex(inventoryIndex); } protected int getInventorySlot(int slot) { int hotbarSize = getHotbarSize(); if (slot < hotbarSize) { return slot % HOTBAR_INVENTORY_SIZE; } return ((slot - hotbarSize) % getInventorySize()); } protected void buildInventory() { // Force an update of the display inventory since chest mode is a different size displayInventory = null; updateHotbarCount(); for (Inventory hotbar : hotbars) { hotbar.clear(); } inventories.clear(); List<ItemStack> unsorted = new ArrayList<>(); for (String key : spells) { int spellLevel = getSpellLevel(key); SpellKey spellKey = new SpellKey(key, spellLevel); SpellTemplate spell = controller.getSpellTemplate(spellKey.getKey()); ItemStack itemStack = createSpellItem(spell, "", controller, getActiveMage(), this, false); if (itemStack != null) { Integer slot = spellInventory.get(spell.getSpellKey().getBaseKey()); if (slot == null) { unsorted.add(itemStack); } else { addToInventory(itemStack, slot); } } } WandMode brushMode = getBrushMode(); for (String brushKey : brushes) { boolean addToInventory = brushMode == WandMode.INVENTORY || (MaterialBrush.isSpecialMaterialKey(brushKey) && !MaterialBrush.isSchematic(brushKey)); if (addToInventory) { ItemStack itemStack = createBrushIcon(brushKey); if (itemStack == null) { controller.getPlugin().getLogger().warning("Unable to create brush icon for key " + brushKey); continue; } Integer slot = brushInventory.get(brushKey); if (activeBrush == null || activeBrush.length() == 0) activeBrush = brushKey; addToInventory(itemStack, slot); } } for (ItemStack unsortedItem : unsorted) { addToInventory(unsortedItem); } updateHasInventory(); if (openInventoryPage >= inventories.size() && openInventoryPage != 0 && hasInventory) { setOpenInventoryPage(0); } } protected void parseSpells(String spellString) { // Support YML-List-As-String format // Maybe don't need this anymore since loading lists is now a separate path spellString = spellString.replaceAll("[\\]\\[]", ""); String[] spellNames = StringUtils.split(spellString, ','); loadSpells(Arrays.asList(spellNames)); } protected void clearSpells() { spellLevels.clear(); spells.clear(); } protected void loadSpells(Collection<String> spellKeys) { clearSpells(); WandUpgradePath path = getPath(); for (String spellName : spellKeys) { String[] pieces = StringUtils.split(spellName, '@'); Integer slot = parseSlot(pieces); // Handle aliases and upgrades smoothly String loadedKey = pieces[0].trim(); SpellKey spellKey = new SpellKey(loadedKey); SpellTemplate spell = controller.getSpellTemplate(loadedKey); if (limitSpellsToPath && path != null && !path.containsSpell(spellKey.getBaseKey())) continue; // Downgrade spells if higher levels have gone missing while (spell == null && spellKey.getLevel() > 0) { spellKey = new SpellKey(spellKey.getBaseKey(), spellKey.getLevel() - 1); spell = controller.getSpellTemplate(spellKey.getKey()); } if (spell != null) { spellKey = spell.getSpellKey(); Integer currentLevel = spellLevels.get(spellKey.getBaseKey()); if (spellKey.getLevel() > 1 && (currentLevel == null || currentLevel < spellKey.getLevel())) { setSpellLevel(spellKey.getBaseKey(), spellKey.getLevel()); } if (slot != null) { spellInventory.put(spellKey.getBaseKey(), slot); } spells.add(spellKey.getBaseKey()); if (activeSpell == null || activeSpell.length() == 0) { activeSpell = spellKey.getBaseKey(); } } } } private void loadSpells() { Object wandSpells = getObject("spells"); if (wandSpells != null) { if (wandSpells instanceof String) { parseSpells((String)wandSpells); } else if (wandSpells instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> spellList = (Collection<String>)wandSpells; loadSpells(spellList); } else { clearSpells(); } } else { clearSpells(); } } protected void parseBrushes(String brushString) { // Support YML-List-As-String format // Maybe don't need this anymore since loading lists is now a separate path brushString = brushString.replaceAll("[\\]\\[]", ""); String[] brushNames = StringUtils.split(brushString, ','); loadBrushes(Arrays.asList(brushNames)); } protected void clearBrushes() { brushes.clear(); } protected void loadBrushes(Collection<String> brushKeys) { WandUpgradePath path = getPath(); clearBrushes(); for (String materialName : brushKeys) { String[] pieces = StringUtils.split(materialName, '@'); Integer slot = parseSlot(pieces); String materialKey = pieces[0].trim(); if (limitBrushesToPath && path != null && !path.containsBrush(materialKey)) continue; if (slot != null) { brushInventory.put(materialKey, slot); } brushes.add(materialKey); } } private void loadBrushes() { Object wandBrushes = getObject("brushes", getObject("materials")); if (wandBrushes != null) { if (wandBrushes instanceof String) { parseBrushes((String)wandBrushes); } else if (wandBrushes instanceof Collection) { @SuppressWarnings("unchecked") Collection<String> brushList = (Collection<String>)wandBrushes; loadBrushes(brushList); } else { clearBrushes(); } } else { clearBrushes(); } } protected void loadBrushInventory(Map<String, ? extends Object> inventory) { if (inventory == null) return; WandUpgradePath path = getPath(); for (Map.Entry<String, ?> brushEntry : inventory.entrySet()) { Object slot = brushEntry.getValue(); String brushKey = brushEntry.getKey(); if (limitBrushesToPath && path != null && !path.containsBrush(brushKey)) continue; if (slot != null && slot instanceof Integer) { brushInventory.put(brushKey, (Integer)slot); } } } protected void loadSpellInventory(Map<String, ? extends Object> inventory) { if (inventory == null) return; WandUpgradePath path = getPath(); for (Map.Entry<String, ? extends Object> spellEntry : inventory.entrySet()) { String spellKey = spellEntry.getKey(); if (limitSpellsToPath && path != null && !path.containsSpell(spellKey)) continue; Object slot = spellEntry.getValue(); if (slot != null && slot instanceof Integer) { spellInventory.put(spellKey, (Integer)slot); } } } protected void loadSpellLevels(Map<String, ? extends Object> levels) { if (levels == null) return; for (Map.Entry<String, ? extends Object> spellEntry : levels.entrySet()) { Object level = spellEntry.getValue(); if (level != null && level instanceof Integer) { setSpellLevel(spellEntry.getKey(), (Integer)level); } } } @Nullable protected ItemStack createSpellIcon(SpellTemplate spell) { return createSpellItem(spell, "", controller, getActiveMage(), this, false); } @Nullable public static ItemStack createSpellItem(String spellKey, MagicController controller, Wand wand, boolean isItem) { String[] split = spellKey.split(" ", 2); return createSpellItem(controller.getSpellTemplate(split[0]), split.length > 1 ? split[1] : "", controller, wand == null ? null : wand.getActiveMage(), wand, isItem); } @Nullable public static ItemStack createSpellItem(String spellKey, MagicController controller, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, boolean isItem) { String[] split = spellKey.split(" ", 2); return createSpellItem(controller.getSpellTemplate(split[0]), split.length > 1 ? split[1] : "", controller, mage, wand, isItem); } @Nullable public static ItemStack createSpellItem(SpellTemplate spell, String args, MagicController controller, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, boolean isItem) { if (spell == null) return null; String iconURL = spell.getIconURL(); ItemStack itemStack = null; if (iconURL != null && (controller.isUrlIconsEnabled() || spell.getIcon() == null || !spell.getIcon().isValid() || spell.getIcon().getMaterial() == Material.AIR)) { itemStack = controller.getURLSkull(iconURL); } if (itemStack == null) { ItemStack originalItemStack = null; com.elmakers.mine.bukkit.api.block.MaterialAndData icon = spell.getIcon(); if (icon == null) { controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material"); return null; } try { originalItemStack = new ItemStack(icon.getMaterial(), 1, icon.getData()); itemStack = InventoryUtils.makeReal(originalItemStack); } catch (Exception ex) { itemStack = null; } if (itemStack == null) { if (icon.getMaterial() != Material.AIR) { String iconName = icon.getName(); controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getKey() + " with material " + iconName); } return originalItemStack; } } InventoryUtils.makeUnbreakable(itemStack); InventoryUtils.hideFlags(itemStack, (byte)63); updateSpellItem(controller.getMessages(), itemStack, spell, args, mage, wand, wand == null ? null : wand.activeBrush, isItem); if (wand != null && wand.getMode() == WandMode.SKILLS && !isItem) { String mageClassKey = wand.getMageClassKey(); ConfigurationSection skillsConfig = wand.getConfigurationSection("skills"); InventoryUtils.configureSkillItem(itemStack, mageClassKey, skillsConfig); } return itemStack; } @Nullable protected ItemStack createBrushIcon(String materialKey) { return createBrushItem(materialKey, controller, this, false); } @Nullable public static ItemStack createBrushItem(String materialKey, com.elmakers.mine.bukkit.api.magic.MageController controller, Wand wand, boolean isItem) { MaterialBrush brushData = MaterialBrush.parseMaterialKey(materialKey); if (brushData == null) return null; ItemStack itemStack = brushData.getItem(controller, isItem); if (BrushGlow || (isItem && BrushItemGlow)) { CompatibilityUtils.addGlow(itemStack); } InventoryUtils.makeUnbreakable(itemStack); InventoryUtils.hideFlags(itemStack, (byte)63); updateBrushItem(controller.getMessages(), itemStack, brushData, wand); return itemStack; } protected boolean findItem() { if (mage != null && item != null) { Player player = mage.getPlayer(); if (player != null) { ItemStack itemInHand = player.getInventory().getItemInMainHand(); if (itemInHand != null && !InventoryUtils.isSameInstance(itemInHand, item) && itemInHand.equals(item)) { item = itemInHand; isInOffhand = false; return true; } itemInHand = player.getInventory().getItemInOffHand(); if (itemInHand != null && !InventoryUtils.isSameInstance(itemInHand, item) && itemInHand.equals(item)) { item = itemInHand; isInOffhand = true; return true; } itemInHand = player.getInventory().getItem(heldSlot); if (itemInHand != null && !InventoryUtils.isSameInstance(itemInHand, item) && itemInHand.equals(item)) { item = itemInHand; isInOffhand = true; return true; } } } return false; } @Override public void saveState() { // Make sure we're on the current item instance if (findItem()) { updateItemIcon(); updateName(); updateLore(); } if (item == null || item.getType() == Material.AIR) return; // Check for upgrades that still have wand data if (isUpgrade && isWand(item)) { InventoryUtils.removeMeta(item, WAND_KEY); } Object wandNode = InventoryUtils.createNode(item, isUpgrade ? UPGRADE_KEY : WAND_KEY); if (wandNode == null) { controller.getLogger().warning("Failed to save wand state for wand to : " + item); } else { InventoryUtils.saveTagsToNBT(getConfiguration(), wandNode); } } @Nullable public static ConfigurationSection itemToConfig(ItemStack item, ConfigurationSection stateNode) { Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) { wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); if (wandNode == null) { return null; } } ConfigurationUtils.loadAllTagsFromNBT(stateNode, wandNode); return stateNode; } public static void configToItem(ConfigurationSection itemSection, ItemStack item) { ConfigurationSection stateNode = itemSection.getConfigurationSection("wand"); Object wandNode = InventoryUtils.createNode(item, Wand.WAND_KEY); if (wandNode != null) { InventoryUtils.saveTagsToNBT(stateNode, wandNode); } } @Nullable protected String getPotionEffectString() { return getPotionEffectString(potionEffects); } @Override public void save(ConfigurationSection node, boolean filtered) { ConfigurationUtils.addConfigurations(node, getConfiguration()); // Filter out some fields if (filtered) { node.set("id", null); node.set("owner_id", null); node.set("owner", null); node.set("template", null); node.set("mana_timestamp", null); node.set("enchant_count", null); } if (isUpgrade) { node.set("upgrade", true); } if (template != null && !template.isEmpty()) { node.set("template", null); node.set("inherit", template); } } public void save() { saveState(); updateName(); updateLore(); } public void updateBrushInventory() { if (brushInventory.isEmpty()) { setProperty("brush_inventory", null); } else { setProperty("brush_inventory", new HashMap<>(brushInventory)); } } protected void updateBrushInventory(Map<String, Integer> updateBrushes) { for (Map.Entry<String, Integer> brushEntry : brushInventory.entrySet()) { String brushKey = brushEntry.getKey(); Integer slot = updateBrushes.get(brushKey); if (slot != null) { brushEntry.setValue(slot); } } } public void updateSpellInventory() { if (spellInventory.isEmpty()) { setProperty("spell_inventory", null); } else { setProperty("spell_inventory", new HashMap<>(spellInventory)); } } protected void updateSpellInventory(Map<String, Integer> updateSpells) { for (Map.Entry<String, Integer> spellEntry : spellInventory.entrySet()) { String spellKey = spellEntry.getKey(); Integer slot = updateSpells.get(spellKey); if (slot != null) { spellEntry.setValue(slot); } } } public void setEffectColor(String hexColor) { // Annoying config conversion issue :\ if (hexColor.contains(".")) { hexColor = hexColor.substring(0, hexColor.indexOf('.')); } if (hexColor == null || hexColor.length() == 0 || hexColor.equals("none")) { effectColor = null; return; } effectColor = new ColorHD(hexColor); if (hexColor.equals("random")) { setProperty("effect_color", effectColor.toString()); } } private void migrateProtection(String legacy, String migrateTo) { if (hasProperty(legacy)) { double protection = getDouble(legacy); clearProperty(legacy); setProperty("protection." + migrateTo, protection); } } @Override public void loadProperties() { super.loadProperties(); locked = getBoolean("locked", locked); lockedAllowUpgrades = getBoolean("locked_allow_upgrades", false); consumeReduction = getFloat("consume_reduction"); cooldownReduction = getFloat("cooldown_reduction"); costReduction = getFloat("cost_reduction"); power = getFloat("power"); ConfigurationSection protectionConfig = getConfigurationSection("protection"); if (protectionConfig == null && hasProperty("protection")) { migrateProtection("protection", "overall"); migrateProtection("protection_physical", "physical"); migrateProtection("protection_projectiles", "projectile"); migrateProtection("protection_falling", "fall"); migrateProtection("protection_fire", "fire"); migrateProtection("protection_explosions", "explosion"); protectionConfig = getConfigurationSection("protection"); } if (protectionConfig != null) { protection = new HashMap<>(); for (String protectionKey : protectionConfig.getKeys(false)) { protection.put(protectionKey, protectionConfig.getDouble(protectionKey)); } } hasId = getBoolean("unique", false); blockChance = getFloat("block_chance"); blockReflectChance = getFloat("block_reflect_chance"); blockFOV = getFloat("block_fov"); blockMageCooldown = getInt("block_mage_cooldown"); blockCooldown = getInt("block_cooldown"); manaPerDamage = getFloat("mana_per_damage"); spMultiplier = getFloat("sp_multiplier", 1); String singleClass = getString("class"); if (singleClass != null && !singleClass.isEmpty()) { mageClassKeys = new ArrayList<>(); mageClassKeys.add(singleClass); } else { mageClassKeys = getStringList("classes"); } // Check for single-use wands uses = getInt("uses"); hasUses = uses > 0; // Convert some legacy properties to potion effects float healthRegeneration = getFloat("health_regeneration", 0); float hungerRegeneration = getFloat("hunger_regeneration", 0); float speedIncrease = getFloat("haste", 0); if (speedIncrease > 0) { potionEffects.put(PotionEffectType.SPEED, 1); } if (healthRegeneration > 0) { potionEffects.put(PotionEffectType.REGENERATION, 1); } if (hungerRegeneration > 0) { potionEffects.put(PotionEffectType.SATURATION, 1); } // This overrides the value loaded in CasterProperties if (!regenWhileInactive) { setProperty("mana_timestamp", System.currentTimeMillis()); } if (hasProperty("effect_color")) { setEffectColor(getString("effect_color")); } id = getString("id"); isUpgrade = getBoolean("upgrade"); quietLevel = getInt("quiet"); effectBubbles = getBoolean("effect_bubbles"); keep = getBoolean("keep"); passive = getBoolean("passive"); indestructible = getBoolean("indestructible"); superPowered = getBoolean("powered"); superProtected = getBoolean("protected"); glow = getBoolean("glow"); undroppable = getBoolean("undroppable"); isHeroes = getBoolean("heroes"); bound = getBoolean("bound"); forceUpgrade = getBoolean("force"); autoOrganize = getBoolean("organize"); autoAlphabetize = getBoolean("alphabetize"); autoFill = getBoolean("fill"); rename = getBoolean("rename"); renameDescription = getBoolean("rename_description"); enchantCount = getInt("enchant_count"); maxEnchantCount = getInt("max_enchant_count"); inventoryRows = getInt("inventory_rows", 5); if (inventoryRows <= 0) inventoryRows = 1; if (hasProperty("effect_particle")) { effectParticle = ConfigurationUtils.toParticleEffect(getString("effect_particle")); effectParticleData = 0; } else { effectParticle = null; } if (hasProperty("effect_sound")) { effectSound = ConfigurationUtils.toSoundEffect(getString("effect_sound")); } else { effectSound = null; } activeEffectsOnly = getBoolean("active_effects"); effectParticleData = getFloat("effect_particle_data"); effectParticleCount = getInt("effect_particle_count"); effectParticleRadius = getDouble("effect_particle_radius"); effectParticleOffset = getDouble("effect_particle_offset"); effectParticleInterval = getInt("effect_particle_interval"); effectParticleMinVelocity = getDouble("effect_particle_min_velocity"); effectSoundInterval = getInt("effect_sound_interval"); castLocation = getVector("cast_location"); castInterval = getInt("cast_interval"); castMinVelocity = getDouble("cast_min_velocity"); castVelocityDirection = getVector("cast_velocity_direction"); castSpell = getString("cast_spell"); String castParameterString = getString("cast_parameters", null); if (castParameterString != null && !castParameterString.isEmpty()) { castParameters = new MemoryConfiguration(); ConfigurationUtils.addParameters(StringUtils.split(castParameterString, ' '), castParameters); } else { castParameters = null; } WandMode newMode = parseWandMode(getString("mode"), controller.getDefaultWandMode()); if (newMode != mode) { if (isInventoryOpen()) { closeInventory(); } mode = newMode; } brushMode = parseWandMode(getString("brush_mode"), controller.getDefaultBrushMode()); // Backwards compatibility if (getBoolean("mode_drop", false)) { dropAction = WandAction.TOGGLE; swapAction = WandAction.CYCLE_HOTBAR; rightClickAction = WandAction.NONE; quickCast = true; // This is to turn the redundant spell lore off quickCastDisabled = true; manualQuickCastDisabled = false; } else if (mode == WandMode.CAST) { leftClickAction = WandAction.CAST; rightClickAction = WandAction.CAST; swapAction = WandAction.NONE; dropAction = WandAction.NONE; } else if (mode == WandMode.CYCLE) { leftClickAction = WandAction.CAST; rightClickAction = WandAction.NONE; swapAction = WandAction.NONE; dropAction = WandAction.CYCLE; } else { leftClickAction = WandAction.NONE; rightClickAction = WandAction.NONE; dropAction = WandAction.NONE; swapAction = WandAction.NONE; quickCast = false; quickCastDisabled = false; manualQuickCastDisabled = false; } String quickCastType = getString("quick_cast", getString("mode_cast")); if (quickCastType != null) { if (quickCastType.equalsIgnoreCase("true")) { quickCast = true; // This is to turn the redundant spell lore off quickCastDisabled = true; manualQuickCastDisabled = false; } else if (quickCastType.equalsIgnoreCase("manual")) { quickCast = false; quickCastDisabled = true; manualQuickCastDisabled = false; } else if (quickCastType.equalsIgnoreCase("disable")) { quickCast = false; quickCastDisabled = true; manualQuickCastDisabled = true; } else { quickCast = false; quickCastDisabled = false; manualQuickCastDisabled = false; } } leftClickAction = parseWandAction(getString("left_click"), leftClickAction); rightClickAction = parseWandAction(getString("right_click"), rightClickAction); dropAction = parseWandAction(getString("drop"), dropAction); swapAction = parseWandAction(getString("swap"), swapAction); owner = getString("owner"); ownerId = getString("owner_id"); template = getString("template"); upgradeTemplate = getString("upgrade_template"); path = getString("path"); activeSpell = getString("active_spell"); if (activeSpell != null && activeSpell.contains("|")) { SpellKey activeKey = new SpellKey(activeSpell); activeSpell = activeKey.getBaseKey(); setProperty("active_spell", activeSpell); } alternateSpell = getString("alternate_spell"); alternateSpell2 = getString("alternate_spell2"); activeBrush = getString("active_brush", getString("active_material")); if (hasProperty("hotbar")) { currentHotbar = getInt("hotbar"); } if (hasProperty("page")) { int page = getInt("page"); if (page != openInventoryPage) { openInventoryPage = page; } } // Default to template names, override with localizations and finally with wand data wandName = controller.getMessages().get("wand.default_name"); description = ""; // Check for migration information in the template config ConfigurationSection templateConfig = null; if (template != null && !template.isEmpty()) { templateConfig = controller.getWandTemplateConfiguration(template); if (templateConfig != null) { wandName = templateConfig.getString("name", wandName); description = templateConfig.getString("description", description); int templateUses = templateConfig.getInt("uses"); isSingleUse = templateUses == 1; hasUses = hasUses || templateUses > 0; } wandName = controller.getMessages().get("wands." + template + ".name", wandName); description = controller.getMessages().get("wands." + template + ".description", description); } wandName = getString("name", wandName); description = getString("description", description); WandTemplate wandTemplate = getTemplate(); if (hasProperty("icon_inactive")) { String iconKey = getString("icon_inactive"); if (wandTemplate != null) { iconKey = wandTemplate.migrateIcon(iconKey); } if (iconKey != null) { inactiveIcon = new MaterialAndData(iconKey); } } else { inactiveIcon = null; } if (inactiveIcon != null && (inactiveIcon.getMaterial() == null || inactiveIcon.getMaterial() == Material.AIR)) { inactiveIcon = null; } inactiveIconDelay = getInt("icon_inactive_delay"); randomizeOnActivate = randomizeOnActivate && hasProperty("randomize_icon"); if (randomizeOnActivate) { String randomizeIcon = getString("randomize_icon"); setIcon(new MaterialAndData(randomizeIcon)); if (item == null) { controller.getLogger().warning("Invalid randomize_icon in wand '" + template + "' config: " + randomizeIcon); } } else if (hasProperty("icon")) { String iconKey = getString("icon"); if (wandTemplate != null) { iconKey = wandTemplate.migrateIcon(iconKey); } if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; } // Port old custom wand icons if (templateConfig != null && iconKey.contains("i.imgur.com")) { iconKey = templateConfig.getString("icon"); } setIcon(new MaterialAndData(iconKey)); if (item == null) { controller.getLogger().warning("Invalid icon in wand '" + template + "' config: " + iconKey); } updateIcon(); } else if (isUpgrade) { setIcon(new MaterialAndData(DefaultUpgradeMaterial)); } else { setIcon(new MaterialAndData(DefaultWandMaterial)); } if (hasProperty("upgrade_icon")) { upgradeIcon = new MaterialAndData(getString("upgrade_icon")); } // Add vanilla attributes InventoryUtils.applyAttributes(item, getConfigurationSection("item_attributes"), getString("item_attribute_slot", getString("attribute_slot"))); // Add unstashable and unmoveable tags if (getBoolean("unstashable") || (undroppable && Unstashable)) { InventoryUtils.setMetaBoolean(item, "unstashable", true); } else { InventoryUtils.removeMeta(item, "unstashable"); } if (getBoolean("unmoveable")) { InventoryUtils.setMetaBoolean(item, "unmoveable", true); } else { InventoryUtils.removeMeta(item, "unmoveable"); } if (undroppable) { InventoryUtils.setMetaBoolean(item, "undroppable", true); } else { InventoryUtils.removeMeta(item, "undroppable"); } if (keep) { InventoryUtils.setMetaBoolean(item, "keep", true); } else { InventoryUtils.removeMeta(item, "keep"); } // Add vanilla enchantments ConfigurationSection enchantments = getConfigurationSection("enchantments"); InventoryUtils.applyEnchantments(item, enchantments); // Add enchantment glow if (enchantments == null || enchantments.getKeys(false).isEmpty()) { if (glow) { CompatibilityUtils.addGlow(item); } else { CompatibilityUtils.removeGlow(item); } } // Check for path-based migration, may update icons com.elmakers.mine.bukkit.api.wand.WandUpgradePath upgradePath = getPath(); if (upgradePath != null) { hasSpellProgression = upgradePath.getSpells().size() > 0 || upgradePath.getExtraSpells().size() > 0 || upgradePath.getRequiredSpells().size() > 0; upgradePath.checkMigration(this); } else { hasSpellProgression = false; } if (isHeroes) { hasSpellProgression = true; } brushInventory.clear(); spellInventory.clear(); limitSpellsToPath = getBoolean("limit_spells_to_path"); limitBrushesToPath = getBoolean("limit_brushes_to_path"); loadSpells(); // Load spell levels Object spellLevelsRaw = getObject("spell_levels"); if (spellLevelsRaw != null) { // Not sure this will ever appear as a Map, but just in case if (spellLevelsRaw instanceof Map) { @SuppressWarnings("unchecked") Map<String, Integer> spellLevels = (Map<String, Integer>)spellLevelsRaw; loadSpellLevels(spellLevels); } else if (spellLevelsRaw instanceof ConfigurationSection) { loadSpellLevels(NMSUtils.getMap((ConfigurationSection)spellLevelsRaw)); } } checkActiveSpell(); loadBrushes(); Object brushInventoryRaw = getObject("brush_inventory"); if (brushInventoryRaw != null) { // Not sure this will ever appear as a Map, but just in case if (brushInventoryRaw instanceof Map) { @SuppressWarnings("unchecked") Map<String, Integer> brushInventory = (Map<String, Integer>)brushInventoryRaw; loadBrushInventory(brushInventory); } else if (brushInventoryRaw instanceof ConfigurationSection) { loadBrushInventory(NMSUtils.getMap((ConfigurationSection)brushInventoryRaw)); } } Object spellInventoryRaw = getObject("spell_inventory"); if (spellInventoryRaw != null) { // Not sure this will ever appear as a Map, but just in case if (spellInventoryRaw instanceof Map) { @SuppressWarnings("unchecked") Map<String, Integer> spellInventory = (Map<String, Integer>)spellInventoryRaw; loadSpellInventory(spellInventory); } else if (spellInventoryRaw instanceof ConfigurationSection) { loadSpellInventory(NMSUtils.getMap((ConfigurationSection)spellInventoryRaw)); } } else { // Spells may have contained an inventory from migration or templates with a spell@slot format. updateSpellInventory(); } castOverrides = null; if (hasProperty("overrides")) { castOverrides = null; Object overridesGeneric = getObject("overrides"); if (overridesGeneric != null) { castOverrides = new HashMap<>(); if (overridesGeneric instanceof String) { String overrides = (String) overridesGeneric; if (!overrides.isEmpty()) { // Support YML-List-As-String format // May not really need this anymore. overrides = overrides.replaceAll("[\\]\\[]", ""); String[] pairs = StringUtils.split(overrides, ','); for (String override : pairs) { parseOverride(override); } } } else if (overridesGeneric instanceof List) { @SuppressWarnings("unchecked") List<String> overrideList = (List<String>)overridesGeneric; for (String override : overrideList) { parseOverride(override); } } else if (overridesGeneric instanceof ConfigurationSection) { ConfigurationSection overridesSection = (ConfigurationSection)overridesGeneric; Set<String> keys = overridesSection.getKeys(true); for (String key : keys) { Object leaf = overridesSection.get(key); if (!(leaf instanceof ConfigurationSection) && !(leaf instanceof Map)) { castOverrides.put(key, leaf.toString()); } } } } } potionEffects.clear(); if (hasProperty("potion_effects")) { addPotionEffects(potionEffects, getString("potion_effects", null)); } // Some cleanup and sanity checks. In theory we don't need to store any non-zero value (as it is with the traders) // so try to keep defaults as 0/0.0/false. if (effectSound == null) { effectSoundInterval = 0; } else { effectSoundInterval = (effectSoundInterval == 0) ? 5 : effectSoundInterval; } if (effectParticle == null) { effectParticleInterval = 0; } checkActiveMaterial(); } private void parseOverride(String override) { // Unescape commas override = override.replace("\\|", ","); String[] keyValue = StringUtils.split(override, ' '); if (keyValue.length > 0) { String value = keyValue.length > 1 ? keyValue[1] : ""; castOverrides.put(keyValue[0], value); } } @Override public void describe(CommandSender sender, @Nullable Set<String> ignoreProperties) { ChatColor wandColor = isModifiable() ? ChatColor.AQUA : ChatColor.RED; sender.sendMessage(wandColor + getName()); if (isUpgrade) { sender.sendMessage(ChatColor.YELLOW + "(Upgrade)"); } if (description.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)"); } if (owner != null && owner.length() > 0 && ownerId != null && ownerId.length() > 0) { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner + " (" + ChatColor.GRAY + ownerId + ChatColor.WHITE + ")"); } else { sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)"); } super.describe(sender, ignoreProperties); WandTemplate template = getTemplate(); if (template != null) { sender.sendMessage("" + ChatColor.BOLD + ChatColor.GREEN + "Template Configuration:"); ConfigurationSection itemConfig = getConfiguration(); Set<String> ownKeys = itemConfig.getKeys(false); template.describe(sender, ignoreProperties, ownKeys); } } private static String getBrushDisplayName(Messages messages, com.elmakers.mine.bukkit.api.block.MaterialBrush brush) { String materialName = brush == null ? null : brush.getName(messages); if (materialName == null) { materialName = "none"; } String brushPrefix = ChatColor.translateAlternateColorCodes('&', messages.get("wand.brush_prefix")); return brushPrefix + materialName; } private static String getSpellDisplayName(Messages messages, SpellTemplate spell, com.elmakers.mine.bukkit.api.block.MaterialBrush brush) { String name = ""; if (spell != null) { String spellPrefix = ChatColor.translateAlternateColorCodes('&', messages.get("wand.spell_prefix")); if (brush != null && spell.usesBrush()) { name = spellPrefix + spell.getName() + " " + getBrushDisplayName(messages, brush) + ChatColor.WHITE; } else { name = spellPrefix + spell.getName() + ChatColor.WHITE; } } return name; } private String getActiveWandName(SpellTemplate spell, com.elmakers.mine.bukkit.api.block.MaterialBrush brush) { // Build wand name int remaining = getRemainingUses(); String wandColorPrefix = (hasUses && remaining <= 1) ? "single_use_prefix" : isModifiable() ? (bound ? "bound_prefix" : "unbound_prefix") : (path != null && path.length() > 0 ? "has_path_prefix" : "unmodifiable_prefix"); String name = ChatColor.translateAlternateColorCodes('&', getMessage(wandColorPrefix)) + getDisplayName(); if (randomizeOnActivate) return name; Set<String> spells = getSpells(); // Add active spell to description Messages messages = controller.getMessages(); boolean showSpell = isModifiable() && hasSpellProgression(); showSpell = !quickCast && (spells.size() > 1 || showSpell) && getMode() != WandMode.SKILLS; if (spell != null && showSpell) { name = getSpellDisplayName(messages, spell, brush) + " (" + name + ChatColor.WHITE + ")"; } if (remaining > 1) { String message = getMessage("uses_remaining_brief"); name = name + ChatColor.DARK_RED + " (" + message.replace("$count", Integer.toString(remaining)) + ChatColor.DARK_RED + ")"; } return name; } private String getActiveWandName(SpellTemplate spell) { return getActiveWandName(spell, mage == null ? MaterialBrush.parseMaterialKey(activeBrush) : mage.getBrush()); } private String getActiveWandName(MaterialBrush brush) { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell, brush); } private String getActiveWandName() { SpellTemplate spell = null; if (activeSpell != null && activeSpell.length() > 0) { spell = controller.getSpellTemplate(activeSpell); } return getActiveWandName(spell); } protected String getDisplayName() { return ChatColor.translateAlternateColorCodes('&', randomizeOnActivate ? getMessage("randomized_name") : wandName); } public void updateName(boolean isActive) { if (isActive) { CompatibilityUtils.setDisplayName(item, !isUpgrade ? getActiveWandName() : ChatColor.translateAlternateColorCodes('&', getMessage("upgrade_prefix")) + getDisplayName()); } else { CompatibilityUtils.setDisplayName(item, ChatColor.stripColor(getDisplayName())); } } private void updateName() { updateName(true); } protected static String convertToHTML(String line) { int tagCount = 1; line = "<span style=\"color:white\">" + line; for (ChatColor c : ChatColor.values()) { tagCount += StringUtils.countMatches(line, c.toString()); String replaceStyle = ""; if (c == ChatColor.ITALIC) { replaceStyle = "font-style: italic"; } else if (c == ChatColor.BOLD) { replaceStyle = "font-weight: bold"; } else if (c == ChatColor.UNDERLINE) { replaceStyle = "text-decoration: underline"; } else { String color = c.name().toLowerCase().replace("_", ""); if (c == ChatColor.LIGHT_PURPLE) { color = "mediumpurple"; } replaceStyle = "color:" + color; } line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">"); } for (int i = 0; i < tagCount; i++) { line += "</span>"; } return line; } public String getHTMLDescription() { Collection<String> rawLore = getLore(); Collection<String> lore = new ArrayList<>(); lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>"); for (String line : rawLore) { lore.add(convertToHTML(line)); } return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>"; } protected void addPropertyLore(List<String> lore, boolean isSingleSpell) { if (usesMana() && effectiveManaMax > 0) { int manaMax = getManaMax(); if (effectiveManaMax != manaMax) { String fullMessage = getLevelString("mana_amount_boosted", manaMax, controller.getMaxMana()); ConfigurationUtils.addIfNotEmpty(fullMessage.replace("$mana", Integer.toString(effectiveManaMax)), lore); } else { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_amount", manaMax, controller.getMaxMana()), lore); } int manaRegeneration = getManaRegeneration(); if (manaRegeneration > 0 && effectiveManaRegeneration > 0) { if (effectiveManaRegeneration != manaRegeneration) { String fullMessage = getLevelString("mana_regeneration_boosted", manaRegeneration, controller.getMaxManaRegeneration()); ConfigurationUtils.addIfNotEmpty(fullMessage.replace("$mana", Integer.toString(effectiveManaRegeneration)), lore); } else { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_regeneration", manaRegeneration, controller.getMaxManaRegeneration()), lore); } } if (manaPerDamage > 0) { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_per_damage", manaPerDamage, controller.getMaxManaRegeneration()), lore); } } if (superPowered) { ConfigurationUtils.addIfNotEmpty(getMessage("super_powered"), lore); } if (blockReflectChance > 0) { ConfigurationUtils.addIfNotEmpty(getLevelString("reflect_chance", blockReflectChance), lore); } else if (blockChance != 0) { ConfigurationUtils.addIfNotEmpty(getLevelString("block_chance", blockChance), lore); } float manaMaxBoost = getManaMaxBoost(); if (manaMaxBoost != 0) { ConfigurationUtils.addIfNotEmpty(getPropertyString("mana_boost", manaMaxBoost), lore); } float manaRegenerationBoost = getManaRegenerationBoost(); if (manaRegenerationBoost != 0) { ConfigurationUtils.addIfNotEmpty(getPropertyString("mana_regeneration_boost", manaRegenerationBoost), lore); } if (castSpell != null) { SpellTemplate spell = controller.getSpellTemplate(castSpell); if (spell != null) { ConfigurationUtils.addIfNotEmpty(getMessage("spell_aura").replace("$spell", spell.getName()), lore); } } for (Map.Entry<PotionEffectType, Integer> effect : potionEffects.entrySet()) { ConfigurationUtils.addIfNotEmpty(describePotionEffect(effect.getKey(), effect.getValue()), lore); } // If this is a passive wand, then reduction properties stack onto the mage when worn. // In this case we should show it as such in the lore. if (passive) isSingleSpell = false; if (consumeReduction != 0 && !isSingleSpell) ConfigurationUtils.addIfNotEmpty(getPropertyString("consume_reduction", consumeReduction), lore); if (costReduction != 0 && !isSingleSpell) ConfigurationUtils.addIfNotEmpty(getPropertyString("cost_reduction", costReduction), lore); if (cooldownReduction != 0 && !isSingleSpell) ConfigurationUtils.addIfNotEmpty(getPropertyString("cooldown_reduction", cooldownReduction), lore); if (power > 0) ConfigurationUtils.addIfNotEmpty(getLevelString("power", power), lore); if (superProtected) { ConfigurationUtils.addIfNotEmpty(getMessage("super_protected"), lore); } else if (protection != null) { for (Map.Entry<String, Double> entry : protection.entrySet()) { String protectionType = entry.getKey(); double amount = entry.getValue(); addDamageTypeLore("protection", protectionType, amount, lore); } } ConfigurationSection weaknessConfig = getConfigurationSection("weakness"); if (weaknessConfig != null) { Set<String> keys = weaknessConfig.getKeys(false); for (String key : keys) { addDamageTypeLore("weakness", key, weaknessConfig.getDouble(key), lore); } } ConfigurationSection strengthConfig = getConfigurationSection("strength"); if (strengthConfig != null) { Set<String> keys = strengthConfig.getKeys(false); for (String key : keys) { addDamageTypeLore("strength", key, strengthConfig.getDouble(key), lore); } } if (spMultiplier > 1) { ConfigurationUtils.addIfNotEmpty(getPropertyString("sp_multiplier", spMultiplier - 1), lore); } ConfigurationSection attributes = getConfigurationSection("attributes"); if (attributes != null) { // Don't bother with the lore at all if the template has been blanked out String template = getMessage("attributes"); if (!template.isEmpty()) { Set<String> keys = attributes.getKeys(false); for (String key : keys) { String label = controller.getMessages().get("attributes." + key + ".name", key); // We are only display attributes as integers for now int value = attributes.getInt(key); if (value == 0) continue; float max = 1; MagicAttribute attribute = controller.getAttribute(key); if (attribute != null) { Double maxValue = attribute.getMax(); if (maxValue != null) { max = (float)(double)maxValue; } } label = getPropertyString("attributes", value, max).replace("$attribute", label); lore.add(label); } } } } private String getPropertyString(String templateName, float value) { return getPropertyString(templateName, value, 1); } private String getPropertyString(String templateName, float value, float max) { String propertyTemplate = getBoolean("stack") ? "property_stack" : "property_value"; if (value < 0) { propertyTemplate = propertyTemplate + "_negative"; } return controller.getMessages().getPropertyString(getMessageKey(templateName), value, max, getMessageKey(propertyTemplate)); } private String formatPropertyString(String template, float value) { return formatPropertyString(template, value, 1); } private String formatPropertyString(String template, float value, float max) { String propertyTemplate = getBoolean("stack") ? "property_stack" : "property_value"; if (value < 0) { propertyTemplate = propertyTemplate + "_negative"; } return controller.getMessages().formatPropertyString(template, value, max, getMessage(propertyTemplate)); } private void addDamageTypeLore(String property, String propertyType, double amount, List<String> lore) { if (amount != 0) { String templateKey = getMessageKey(property + "." + propertyType); String template; if (controller.getMessages().containsKey(templateKey)) { template = controller.getMessages().get(templateKey); } else { templateKey = getMessageKey("protection.unknown"); template = controller.getMessages().get(templateKey); String pretty = propertyType.substring(0, 1).toUpperCase() + propertyType.substring(1); template = template.replace("$type", pretty); } template = formatPropertyString(template, (float)amount); ConfigurationUtils.addIfNotEmpty(template, lore); } } public String getLevelString(String templateName, float amount) { return controller.getMessages().getLevelString(getMessageKey(templateName), amount); } public String getLevelString(String templateName, float amount, float max) { return controller.getMessages().getLevelString(getMessageKey(templateName), amount, max); } protected List<String> getCustomLore(Collection<String> loreTemplate) { List<String> lore = new ArrayList<>(); for (String line : loreTemplate) { if (line.startsWith("$")) { switch (line) { case "$description": addDescriptionLore(lore); break; case "$path": String pathTemplate = getMessage("path_lore", ""); String pathName = getPathName(); if (pathName != null && !pathTemplate.isEmpty()) { lore.add(pathTemplate.replace("$path", pathName)); } break; case "$owner": addOwnerDescription(lore); break; case "$spells": int spellCount = getSpells().size(); if (spellCount > 0) { ConfigurationUtils.addIfNotEmpty(getMessage("spell_count").replace("$count", Integer.toString(spellCount)), lore); } break; case "$brushes": int materialCount = getBrushes().size(); if (materialCount > 0) { ConfigurationUtils.addIfNotEmpty(getMessage("material_count").replace("$count", Integer.toString(materialCount)), lore); } break; case "$uses": addUseLore(lore); break; case "$mana_max": if (usesMana()) { int manaMax = getManaMax(); if (effectiveManaMax != manaMax) { String fullMessage = getLevelString("mana_amount_boosted", manaMax, controller.getMaxMana()); ConfigurationUtils.addIfNotEmpty(fullMessage.replace("$mana", Integer.toString(effectiveManaMax)), lore); } else { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_amount", manaMax, controller.getMaxMana()), lore); } } break; case "$mana_regeneration": if (usesMana()) { int manaRegeneration = getManaRegeneration(); if (manaRegeneration > 0) { if (effectiveManaRegeneration != manaRegeneration) { String fullMessage = getLevelString("mana_regeneration_boosted", manaRegeneration, controller.getMaxManaRegeneration()); ConfigurationUtils.addIfNotEmpty(fullMessage.replace("$mana", Integer.toString(effectiveManaRegeneration)), lore); } else { ConfigurationUtils.addIfNotEmpty(getLevelString("mana_regeneration", manaRegeneration, controller.getMaxManaRegeneration()), lore); } } } break; default: lore.add(ChatColor.translateAlternateColorCodes('&', line)); } } else { lore.add(ChatColor.translateAlternateColorCodes('&', line)); } } return lore; } protected void addDescriptionLore(List<String> lore) { String descriptionTemplate = controller.getMessages().get(getMessageKey("description_lore"), ""); if (!description.isEmpty() && !descriptionTemplate.isEmpty()) { if (description.contains("$path")) { String pathName = getPathName(); String description = ChatColor.translateAlternateColorCodes('&', this.description); description = description.replace("$path", pathName == null ? "Unknown" : pathName); InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore); } else { String description = ChatColor.translateAlternateColorCodes('&', this.description); InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore); } } } @Nullable protected String getPathName() { String pathName = null; com.elmakers.mine.bukkit.api.wand.WandUpgradePath path = getPath(); if (path != null) { pathName = path.getName(); } else if (mageClassKeys != null && !mageClassKeys.isEmpty()) { MageClassTemplate classTemplate = controller.getMageClassTemplate(mageClassKeys.get(0)); if (classTemplate != null) { String pathKey = classTemplate.getProperty("path", ""); if (!pathKey.isEmpty()) { path = controller.getPath(pathKey); } if (path != null) { pathName = path.getName(); } else { pathName = classTemplate.getName(); } } } return pathName; } protected void addOwnerDescription(List<String> lore) { if (owner != null && owner.length() > 0) { if (bound) { String ownerDescription = getMessage("bound_description", "$name").replace("$name", owner); ConfigurationUtils.addIfNotEmpty(ownerDescription, lore); } else { String ownerDescription = getMessage("owner_description", "$name").replace("$name", owner); ConfigurationUtils.addIfNotEmpty(ownerDescription, lore); } } } @SuppressWarnings("unchecked") protected List<String> getLore() { Object customLore = getProperty("lore"); if (customLore != null && customLore instanceof Collection) { return getCustomLore((Collection<String>)customLore); } List<String> lore = new ArrayList<>(); int spellCount = getSpells().size(); int materialCount = getBrushes().size(); String pathName = getPathName(); if (description.length() > 0) { if (randomizeOnActivate) { String randomDescription = getMessage("randomized_lore"); String randomTemplate = controller.getMessages().get(getMessageKey("randomized_description"), ""); if (randomDescription.length() > 0 && !randomTemplate.isEmpty()) { InventoryUtils.wrapText(randomTemplate.replace("$description", randomDescription), lore); return lore; } } if (description.contains("$") && !description.contains("$path")) { String newDescription = controller.getMessages().escape(description); if (!newDescription.equals(description)) { this.description = newDescription; setProperty("description", description); } } String descriptionTemplate = controller.getMessages().get(getMessageKey("description_lore"), ""); if (description.contains("$path") && !descriptionTemplate.isEmpty()) { String description = ChatColor.translateAlternateColorCodes('&', this.description); description = description.replace("$path", pathName == null ? "Unknown" : pathName); InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore); } else if (description.contains("$")) { String randomDescription = getMessage("randomized_lore"); String randomTemplate = controller.getMessages().get(getMessageKey("randomized_description"), ""); if (randomDescription.length() > 0 && !randomTemplate.isEmpty()) { randomDescription = ChatColor.translateAlternateColorCodes('&', randomDescription); InventoryUtils.wrapText(randomTemplate.replace("$description", randomDescription), lore); return lore; } } else if (!descriptionTemplate.isEmpty()) { String description = ChatColor.translateAlternateColorCodes('&', this.description); InventoryUtils.wrapText(descriptionTemplate.replace("$description", description), lore); } } String pathTemplate = getMessage("path_lore", ""); if (pathName != null && !pathTemplate.isEmpty()) { lore.add(pathTemplate.replace("$path", pathName)); } if (!isUpgrade) { addOwnerDescription(lore); } SpellTemplate spell = controller.getSpellTemplate(getActiveSpellKey()); Messages messages = controller.getMessages(); // This is here specifically for a wand that only has // one spell now, but may get more later. Since you // can't open the inventory in this state, you can not // otherwise see the spell lore. boolean isSingleSpell = spell != null && spellCount == 1 && !hasInventory && !isUpgrade; if (isSingleSpell) { addSpellLore(messages, spell, lore, getActiveMage(), this); } if (materialCount == 1 && activeBrush != null && activeBrush.length() > 0) { lore.add(getBrushDisplayName(messages, MaterialBrush.parseMaterialKey(activeBrush))); } if (spellCount > 0) { if (isUpgrade) { ConfigurationUtils.addIfNotEmpty(getMessage("upgrade_spell_count").replace("$count", Integer.toString(spellCount)), lore); } else if (spellCount > 1) { ConfigurationUtils.addIfNotEmpty(getMessage("spell_count").replace("$count", Integer.toString(spellCount)), lore); } } if (materialCount > 0) { if (isUpgrade) { ConfigurationUtils.addIfNotEmpty(getMessage("upgrade_material_count").replace("$count", Integer.toString(materialCount)), lore); } else if (materialCount > 1) { ConfigurationUtils.addIfNotEmpty(getMessage("material_count").replace("$count", Integer.toString(materialCount)), lore); } } addUseLore(lore); addPropertyLore(lore, isSingleSpell); if (isUpgrade) { ConfigurationUtils.addIfNotEmpty(getMessage("upgrade_item_description"), lore); } return lore; } protected void addUseLore(List<String> lore) { int remaining = getRemainingUses(); if (!isSingleUse && remaining > 0) { if (isUpgrade) { String message = (remaining == 1) ? getMessage("upgrade_uses_singular") : getMessage("upgrade_uses"); ConfigurationUtils.addIfNotEmpty(message.replace("$count", Integer.toString(remaining)), lore); } else { String message = (remaining == 1) ? getMessage("uses_remaining_singular") : getMessage("uses_remaining_brief"); ConfigurationUtils.addIfNotEmpty(message.replace("$count", Integer.toString(remaining)), lore); } } } protected void updateLore() { CompatibilityUtils.setLore(item, getLore()); } public int getRemainingUses() { return uses; } public void makeEnchantable(boolean enchantable) { if (EnchantableWandMaterial == null) return; if (!enchantable) { item.setType(icon.getMaterial()); item.setDurability(icon.getData()); } else { MaterialSet enchantableMaterials = controller.getMaterialSetManager().getMaterialSetEmpty("enchantable"); if (!enchantableMaterials.testItem(item)) { item.setType(EnchantableWandMaterial); item.setDurability((short) 0); } } updateName(); } public static boolean hasActiveWand(Player player) { if (player == null) return false; ItemStack activeItem = player.getInventory().getItemInMainHand(); return isWand(activeItem); } @Nullable public static Wand getActiveWand(MagicController controller, Player player) { ItemStack activeItem = player.getInventory().getItemInMainHand(); if (isWand(activeItem)) { return controller.getWand(activeItem); } return null; } public static boolean isWand(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, WAND_KEY); } public static boolean isWandOrUpgrade(ItemStack item) { return isWand(item) || isUpgrade(item); } public static boolean isSpecial(ItemStack item) { return isWand(item) || isUpgrade(item) || isSpell(item) || isBrush(item) || isSP(item); } public static boolean isSelfDestructWand(ItemStack item) { return item != null && WAND_SELF_DESTRUCT_KEY != null && InventoryUtils.hasMeta(item, WAND_SELF_DESTRUCT_KEY); } public static boolean isSP(ItemStack item) { return InventoryUtils.hasMeta(item, "sp"); } @Nullable public static Integer getSP(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; String spNode = InventoryUtils.getMetaString(item, "sp"); if (spNode == null) return null; Integer sp = null; try { sp = Integer.parseInt(spNode); } catch (Exception ex) { sp = null; } return sp; } public static boolean isSpell(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "spell"); } public static boolean isSkill(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "skill"); } public static boolean isBrush(ItemStack item) { return item != null && InventoryUtils.hasMeta(item, "brush"); } @Nullable protected static Object getWandOrUpgradeNode(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) { wandNode = InventoryUtils.getNode(item, UPGRADE_KEY); } return wandNode; } @Nullable public static String getWandTemplate(ItemStack item) { Object wandNode = getWandOrUpgradeNode(item); if (wandNode == null) return null; return InventoryUtils.getMetaString(wandNode, "template"); } @Nullable public static String getWandId(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object wandNode = InventoryUtils.getNode(item, WAND_KEY); if (wandNode == null) return null; return InventoryUtils.getMetaString(wandNode, "id"); } @Nullable public static String getSpell(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "key"); } @Nullable @Override public Spell getSpell(String spellKey, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage == null) { return null; } if (!hasSpell(spellKey)) return null; SpellKey key = new SpellKey(spellKey); spellKey = key.getBaseKey(); Integer level = spellLevels.get(spellKey); if (level != null) { spellKey = new SpellKey(spellKey, level).getKey(); } return mage.getSpell(spellKey); } @Nullable @Override public Spell getSpell(String spellKey) { return getSpell(spellKey, mage); } @Nullable public static String getSpellClass(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "class"); } public static boolean isQuickCastSkill(ItemStack item) { if (InventoryUtils.isEmpty(item)) return false; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return false; Boolean quickCast = InventoryUtils.containsNode(spellNode, "quick_cast") ? InventoryUtils.getMetaBoolean(spellNode, "quick_cast") : null; return quickCast == null ? true : quickCast; } @Nullable public static String getSpellArgs(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object spellNode = InventoryUtils.getNode(item, "spell"); if (spellNode == null) return null; return InventoryUtils.getMetaString(spellNode, "args"); } @Nullable public static String getBrush(ItemStack item) { if (InventoryUtils.isEmpty(item)) return null; Object brushNode = InventoryUtils.getNode(item, "brush"); if (brushNode == null) return null; return InventoryUtils.getMetaString(brushNode, "key"); } protected void updateInventoryName(ItemStack item, boolean activeName) { if (isSpell(item)) { Spell spell = mage.getSpell(getSpell(item)); if (spell != null) { updateSpellName(controller.getMessages(), item, spell, activeName ? this : null, activeBrush); } } else if (isBrush(item)) { updateBrushName(controller.getMessages(), item, getBrush(item), activeName ? this : null); } } public static void updateSpellItem(Messages messages, ItemStack itemStack, SpellTemplate spell, String args, Wand wand, String activeMaterial, boolean isItem) { updateSpellItem(messages, itemStack, spell, args, wand == null ? null : wand.getActiveMage(), wand, activeMaterial, isItem); } public static void updateSpellItem(Messages messages, ItemStack itemStack, SpellTemplate spell, String args, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand, String activeMaterial, boolean isItem) { updateSpellName(messages, itemStack, spell, wand, activeMaterial); List<String> lore = new ArrayList<>(); addSpellLore(messages, spell, lore, mage, wand); if (isItem) { ConfigurationUtils.addIfNotEmpty(messages.get("wand.spell_item_description"), lore); } CompatibilityUtils.setLore(itemStack, lore); Object spellNode = CompatibilityUtils.createNode(itemStack, "spell"); CompatibilityUtils.setMeta(spellNode, "key", spell.getKey()); CompatibilityUtils.setMeta(spellNode, "args", args); if (SpellGlow) { CompatibilityUtils.addGlow(itemStack); } } public static void updateSpellName(Messages messages, ItemStack itemStack, SpellTemplate spell, Wand wand, String activeMaterial) { String displayName; if (wand != null && !wand.isQuickCast()) { displayName = wand.getActiveWandName(spell); } else { displayName = getSpellDisplayName(messages, spell, MaterialBrush.parseMaterialKey(activeMaterial)); } CompatibilityUtils.setDisplayName(itemStack, displayName); } public static void updateBrushName(Messages messages, ItemStack itemStack, String materialKey, Wand wand) { updateBrushName(messages, itemStack, MaterialBrush.parseMaterialKey(materialKey), wand); } public static void updateBrushName(Messages messages, ItemStack itemStack, MaterialBrush brush, Wand wand) { String displayName; if (wand != null) { Spell activeSpell = wand.getActiveSpell(); if (activeSpell != null && activeSpell.usesBrush()) { displayName = wand.getActiveWandName(brush); } else { displayName = ChatColor.RED + brush.getName(messages); } } else { displayName = brush.getName(messages); } CompatibilityUtils.setDisplayName(itemStack, displayName); } public static void updateBrushItem(Messages messages, ItemStack itemStack, String materialKey, Wand wand) { updateBrushItem(messages, itemStack, MaterialBrush.parseMaterialKey(materialKey), wand); } public static void updateBrushItem(Messages messages, ItemStack itemStack, MaterialBrush brush, Wand wand) { updateBrushName(messages, itemStack, brush, wand); Object brushNode = CompatibilityUtils.createNode(itemStack, "brush"); CompatibilityUtils.setMeta(brushNode, "key", brush.getKey()); } public void updateHotbar() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; if (!hasStoredInventory()) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { PlayerInventory inventory = player.getInventory(); updateHotbar(inventory); DeprecatedUtils.updateInventory(player); } } private boolean updateHotbar(PlayerInventory playerInventory) { if (getMode() != WandMode.INVENTORY) return false; Inventory hotbar = getHotbar(); if (hotbar == null) return false; // Make sure the wand is still in the held slot ItemStack currentItem = playerInventory.getItem(heldSlot); if (currentItem == null || !currentItem.getItemMeta().equals(item.getItemMeta())) { controller.getLogger().warning("Trying to update hotbar but the wand has gone missing"); return false; } // Set hotbar items from remaining list int targetOffset = 0; for (int hotbarSlot = 0; hotbarSlot < HOTBAR_INVENTORY_SIZE; hotbarSlot++) { if (hotbarSlot == heldSlot) { targetOffset = 1; } ItemStack hotbarItem = hotbar.getItem(hotbarSlot); updateInventoryName(hotbarItem, true); playerInventory.setItem(hotbarSlot + targetOffset, hotbarItem); } return true; } private void updateInventory() { if (mage == null) return; if (!isInventoryOpen()) return; Player player = mage.getPlayer(); if (player == null) return; WandMode wandMode = getMode(); if (wandMode == WandMode.INVENTORY) { if (!hasStoredInventory()) return; PlayerInventory inventory = player.getInventory(); if (!updateHotbar(inventory)) { for (int i = 0; i < HOTBAR_SIZE; i++) { if (i != inventory.getHeldItemSlot()) { inventory.setItem(i, null); } } } updateInventory(inventory); updateName(); } else if (wandMode == WandMode.CHEST || wandMode == WandMode.SKILLS) { Inventory inventory = getDisplayInventory(); inventory.clear(); updateInventory(inventory); } } private void updateInventory(Inventory targetInventory) { // Set inventory from current page, taking into account hotbar offset int currentOffset = getHotbarSize() > 0 ? HOTBAR_SIZE : 0; List<Inventory> inventories = this.inventories; if (openInventoryPage < inventories.size()) { Inventory inventory = inventories.get(openInventoryPage); ItemStack[] contents = inventory.getContents(); for (int i = 0; i < contents.length; i++) { ItemStack inventoryItem = contents[i]; updateInventoryName(inventoryItem, false); targetInventory.setItem(currentOffset, inventoryItem); currentOffset++; } } for (;currentOffset < targetInventory.getSize() && currentOffset < PLAYER_INVENTORY_SIZE; currentOffset++) { targetInventory.setItem(currentOffset, null); } } protected static void addSpellLore(Messages messages, SpellTemplate spell, List<String> lore, com.elmakers.mine.bukkit.api.magic.Mage mage, Wand wand) { spell.addLore(messages, mage, wand, lore); } protected Inventory getOpenInventory() { while (openInventoryPage >= inventories.size()) { inventories.add(CompatibilityUtils.createInventory(null, getInventorySize(), "Wand")); } return inventories.get(openInventoryPage); } protected Inventory getDisplayInventory() { if (displayInventory == null || displayInventory.getSize() != getInventorySize()) { displayInventory = CompatibilityUtils.createInventory(null, getInventorySize(), "Wand"); } return displayInventory; } public void saveChestInventory() { if (displayInventory == null) return; Inventory openInventory = getOpenInventory(); Map<String, Integer> previousSlots = new HashMap<>(); Set<String> addedBack = new HashSet<>(); for (int i = 0; i < displayInventory.getSize(); i++) { ItemStack playerItem = displayInventory.getItem(i); String itemSpellKey = getSpell(playerItem); if (!updateSlot(i + openInventoryPage * getInventorySize(), playerItem)) { playerItem = new ItemStack(Material.AIR); displayInventory.setItem(i, playerItem); } else if (itemSpellKey != null) { addedBack.add(itemSpellKey); } // We don't want to clear items that were taken out, so save them to check later ItemStack current = openInventory.getItem(i); String spellKey = getSpell(current); if (spellKey != null) { previousSlots.put(spellKey, i); } openInventory.setItem(i, playerItem); } // Put back any items that were taken out for (Map.Entry<String, Integer> entry : previousSlots.entrySet()) { if (!addedBack.contains(entry.getKey())) { ItemStack current = openInventory.getItem(entry.getValue()); ItemStack itemStack = createSpellItem(controller.getSpellTemplate(entry.getKey()), "", controller, getActiveMage(), this, false); if (current == null || current.getType() == Material.AIR) { openInventory.setItem(entry.getValue(), itemStack); } else { openInventory.addItem(itemStack); } } } } public void saveInventory() { if (mage == null) return; if (getMode() == WandMode.SKILLS) { saveChestInventory(); return; } if (!isInventoryOpen()) return; if (mage.getPlayer() == null) return; if (getMode() != WandMode.INVENTORY) return; if (!hasStoredInventory()) return; // Work-around glitches that happen if you're dragging an item on death if (mage.isDead()) return; // Fill in the hotbar Player player = mage.getPlayer(); PlayerInventory playerInventory = player.getInventory(); Inventory hotbar = getHotbar(); if (hotbar != null) { int saveOffset = 0; for (int i = 0; i < HOTBAR_SIZE; i++) { ItemStack playerItem = playerInventory.getItem(i); if (isWand(playerItem)) { saveOffset = -1; continue; } int hotbarOffset = i + saveOffset; if (hotbarOffset >= hotbar.getSize()) { // This can happen if there is somehow no wand in the wand inventory. break; } if (!updateSlot(i + saveOffset + currentHotbar * HOTBAR_INVENTORY_SIZE, playerItem)) { playerItem = new ItemStack(Material.AIR); playerInventory.setItem(i, playerItem); } hotbar.setItem(i + saveOffset, playerItem); } } // Fill in the active inventory page int hotbarOffset = getHotbarSize(); Inventory openInventory = getOpenInventory(); for (int i = 0; i < openInventory.getSize(); i++) { ItemStack playerItem = playerInventory.getItem(i + HOTBAR_SIZE); if (!updateSlot(i + hotbarOffset + openInventoryPage * getInventorySize(), playerItem)) { playerItem = new ItemStack(Material.AIR); playerInventory.setItem(i + HOTBAR_SIZE, playerItem); } openInventory.setItem(i, playerItem); } } protected boolean updateSlot(int slot, ItemStack item) { if (item == null || item.getType() == Material.AIR) return true; String spellKey = getSpell(item); if (spellKey != null) { SpellKey key = new SpellKey(spellKey); spellInventory.put(key.getBaseKey(), slot); } else { String brushKey = getBrush(item); if (brushKey != null) { brushInventory.put(brushKey, slot); } else if (mage != null) { // Must have been an item inserted directly into player's inventory? mage.giveItem(item); return false; } } return true; } @Override public int enchant(int totalLevels, com.elmakers.mine.bukkit.api.magic.Mage mage, boolean addSpells) { return randomize(totalLevels, true, mage, addSpells); } @Override public int enchant(int totalLevels, com.elmakers.mine.bukkit.api.magic.Mage mage) { return randomize(totalLevels, true, mage, true); } @Override public int enchant(int totalLevels) { return randomize(totalLevels, true, null, true); } protected int randomize(int totalLevels, boolean additive, com.elmakers.mine.bukkit.api.magic.Mage enchanter, boolean addSpells) { if (enchanter == null && mage != null) { enchanter = mage; } if (maxEnchantCount > 0 && enchantCount >= maxEnchantCount) { if (enchanter != null && addSpells) { enchanter.sendMessage(getMessage("max_enchanted").replace("$wand", getName())); } return 0; } WandUpgradePath path = getPath(); if (path == null) { if (enchanter != null && addSpells) { enchanter.sendMessage(getMessage("no_path").replace("$wand", getName())); } return 0; } int minLevel = path.getMinLevel(); if (totalLevels < minLevel) { if (enchanter != null && addSpells) { String levelMessage = getMessage("need_more_levels"); levelMessage = levelMessage.replace("$levels", Integer.toString(minLevel)); enchanter.sendMessage(levelMessage); } return 0; } // Just a hard-coded sanity check int maxLevel = path.getMaxLevel(); totalLevels = Math.min(totalLevels, maxLevel * 50); int addLevels = Math.min(totalLevels, maxLevel); int levels = 0; boolean modified = true; while (addLevels >= minLevel && modified) { boolean hasUpgrade = path.hasUpgrade(); WandLevel level = path.getLevel(addLevels); if (!path.canEnchant(this) && (path.hasSpells() || path.hasMaterials())) { // Check for level up WandUpgradePath nextPath = path.getUpgrade(); if (nextPath != null) { if (path.checkUpgradeRequirements(this, addSpells ? enchanter : null)) { path.upgrade(this, enchanter); } break; } else { if (enchanter != null && addSpells) { enchanter.sendMessage(getMessage("fully_enchanted").replace("$wand", getName())); } break; } } modified = level.randomizeWand(enchanter, this, additive, hasUpgrade, addSpells); totalLevels -= maxLevel; if (modified) { if (enchanter != null) { path.enchanted(enchanter); } levels += addLevels; // Check for level up WandUpgradePath nextPath = path.getUpgrade(); if (nextPath != null && path.checkUpgradeRequirements(this, null) && !path.canEnchant(this)) { path.upgrade(this, enchanter); path = nextPath; } } else if (path.canEnchant(this)) { if (enchanter != null && levels == 0 && addSpells) { String message = getMessage("require_more_levels"); enchanter.sendMessage(message); } } else if (hasUpgrade) { if (path.checkUpgradeRequirements(this, addSpells ? enchanter : null)) { path.upgrade(this, enchanter); levels += addLevels; } } else if (enchanter != null && addSpells) { enchanter.sendMessage(getMessage("fully_enchanted").replace("$wand", getName())); } addLevels = Math.min(totalLevels, maxLevel); additive = true; } if (levels > 0) { enchantCount++; setProperty("enchant_count", enchantCount); } saveState(); updateName(); updateLore(); return levels; } protected void randomize() { if (template != null && template.length() > 0) { ConfigurationSection wandConfig = controller.getWandTemplateConfiguration(template); if (wandConfig != null && wandConfig.contains("icon")) { String iconKey = wandConfig.getString("icon"); if (iconKey.contains(",")) { Random r = new Random(); String[] keys = StringUtils.split(iconKey, ','); iconKey = keys[r.nextInt(keys.length)]; } setIcon(ConfigurationUtils.toMaterialAndData(iconKey)); updateIcon(); playEffects("randomize"); } } } @Nullable public static ItemStack createItem(MagicController controller, String templateName) { ItemStack item = createSpellItem(templateName, controller, null, true); if (item == null) { item = createBrushItem(templateName, controller, null, true); if (item == null) { Wand wand = createWand(controller, templateName); if (wand != null) { item = wand.getItem(); } } } return item; } @Nullable public static Wand createWand(MagicController controller, String templateName) { if (controller == null) return null; Wand wand = null; try { wand = new Wand(controller, templateName); } catch (UnknownWandException ignore) { // the Wand constructor throws an exception on an unknown template } catch (Exception ex) { ex.printStackTrace(); } return wand; } @Nullable public static Wand createWand(MagicController controller, ItemStack itemStack) { if (controller == null) return null; Wand wand = null; try { wand = controller.getWand(InventoryUtils.makeReal(itemStack)); wand.saveState(); wand.updateName(); } catch (Exception ex) { ex.printStackTrace(); } return wand; } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other) { if (other instanceof Wand) { return add((Wand)other); } return false; } public boolean add(Wand other) { return add(other, this.mage); } @Override public boolean add(com.elmakers.mine.bukkit.api.wand.Wand other, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (other instanceof Wand) { return add((Wand)other, mage); } return false; } public boolean add(Wand other, com.elmakers.mine.bukkit.api.magic.Mage mage) { if (!isModifiable()) { // Only allow upgrading a modifiable wand via an upgrade item // and only if the paths match. if (!other.isUpgrade() || other.path == null || path == null || other.path.isEmpty() || path.isEmpty() || !other.path.equals(path)) { return false; } } // Can't combine limited-use wands if (hasUses || other.hasUses) { return false; } if (isHeroes || other.isHeroes) { return false; } ConfigurationSection templateConfig = controller.getWandTemplateConfiguration(other.getTemplateKey()); // Check for forced upgrades if (other.isForcedUpgrade()) { if (templateConfig == null) { return false; } templateConfig = ConfigurationUtils.cloneConfiguration(templateConfig); templateConfig.set("name", templateConfig.getString("upgrade_name")); templateConfig.set("description", templateConfig.getString("upgrade_description")); templateConfig.set("force", null); templateConfig.set("upgrade", null); templateConfig.set("icon", templateConfig.getString("upgrade_icon")); templateConfig.set("indestructible", null); templateConfig.set("upgrade_icon", null); configure(templateConfig); return true; } // Don't allow upgrades from an item on a different path if (other.isUpgrade() && other.path != null && !other.path.isEmpty() && (this.path == null || !this.path.equals(other.path))) { return false; } ConfigurationSection upgradeConfig = ConfigurationUtils.cloneConfiguration(other.getEffectiveConfiguration()); upgradeConfig.set("id", null); upgradeConfig.set("indestructible", null); upgradeConfig.set("upgrade", null); upgradeConfig.set("icon", other.upgradeIcon == null ? null : other.upgradeIcon.getKey()); upgradeConfig.set("upgrade_icon", null); upgradeConfig.set("template", other.upgradeTemplate); Messages messages = controller.getMessages(); if (other.rename && templateConfig != null) { String newName = messages.get("wands." + other.template + ".name"); newName = templateConfig.getString("name", newName); upgradeConfig.set("name", newName); } else { upgradeConfig.set("name", null); } if (other.renameDescription && templateConfig != null) { String newDescription = messages.get("wands." + other.template + ".description"); newDescription = templateConfig.getString("description", newDescription); upgradeConfig.set("description", newDescription); } else { upgradeConfig.set("description", null); } return upgrade(upgradeConfig); } public boolean isForcedUpgrade() { return isUpgrade && forceUpgrade; } public boolean keepOnDeath() { return keep; } public static WandMode parseWandMode(String modeString, WandMode defaultValue) { if (modeString != null && !modeString.isEmpty()) { try { defaultValue = WandMode.valueOf(modeString.toUpperCase()); } catch (Exception ignored) { } } return defaultValue; } public static WandAction parseWandAction(String actionString, WandAction defaultValue) { if (actionString != null && !actionString.isEmpty()) { try { defaultValue = WandAction.valueOf(actionString.toUpperCase()); } catch (Exception ignored) { } } return defaultValue; } private void updateActiveMaterial() { if (mage == null) return; if (activeBrush == null) { mage.clearBuildingMaterial(); } else { com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); brush.update(activeBrush); } } public void cycleActive(int direction) { Player player = mage != null ? mage.getPlayer() : null; if (player != null && player.isSneaking()) { com.elmakers.mine.bukkit.api.spell.Spell activeSpell = getActiveSpell(); boolean cycleMaterials = false; if (activeSpell != null) { cycleMaterials = activeSpell.usesBrushSelection(); } if (cycleMaterials) { cycleMaterials(direction); } else { cycleSpells(direction); } } else { cycleSpells(direction); } } public void toggleInventory() { if (mage != null && mage.cancelSelection()) { mage.playSoundEffect(noActionSound); return; } Player player = mage == null ? null : mage.getPlayer(); boolean isSneaking = player != null && player.isSneaking(); Spell currentSpell = getActiveSpell(); if (getBrushMode() == WandMode.CHEST && brushSelectSpell != null && !brushSelectSpell.isEmpty() && isSneaking && currentSpell != null && currentSpell.usesBrushSelection()) { Spell brushSelect = mage.getSpell(brushSelectSpell); if (brushSelect != null) { brushSelect.cast(); return; } } if (!hasInventory) { if (activeSpell == null || activeSpell.length() == 0) { // Sanity check, so it'll switch to inventory next time updateHasInventory(); if (spells.size() > 0) { setActiveSpell(spells.iterator().next()); } } updateName(); return; } if (!isInventoryOpen()) { openInventory(); } else { closeInventory(); } } public void updateHasInventory() { int inventorySize = getSpells().size() + getBrushes().size(); hasInventory = inventorySize > 1 || (inventorySize == 1 && hasSpellProgression) || autoFill; } public void cycleInventory() { cycleInventory(1); } public void cycleInventory(int direction) { if (!hasInventory) { return; } if (isInventoryOpen()) { saveInventory(); int inventoryCount = inventories.size(); setOpenInventoryPage(inventoryCount == 0 ? 0 : (openInventoryPage + inventoryCount + direction) % inventoryCount); updateInventory(); if (mage != null && inventories.size() > 1) { if (!playPassiveEffects("cycle") && inventoryCycleSound != null) { mage.playSoundEffect(inventoryCycleSound); } DeprecatedUtils.updateInventory(mage.getPlayer()); } } } @Override public void cycleHotbar() { cycleHotbar(1); } public void cycleHotbar(int direction) { if (!hasInventory || getMode() != WandMode.INVENTORY) { return; } if (isInventoryOpen() && mage != null && hotbars.size() > 1) { saveInventory(); int hotbarCount = hotbars.size(); setCurrentHotbar(hotbarCount == 0 ? 0 : (currentHotbar + hotbarCount + direction) % hotbarCount); updateHotbar(); if (!playPassiveEffects("cycle") && inventoryCycleSound != null) { mage.playSoundEffect(inventoryCycleSound); } sendMessage("hotbar_changed"); updateHotbarStatus(); DeprecatedUtils.updateInventory(mage.getPlayer()); } } public void openInventory() { if (mage == null) return; if (System.currentTimeMillis() < mage.getWandDisableTime()) return; WandMode wandMode = getMode(); if (wandMode == WandMode.CHEST || wandMode == WandMode.SKILLS) { inventoryIsOpen = true; if (!playPassiveEffects("open") && inventoryOpenSound != null) { mage.playSoundEffect(inventoryOpenSound); } updateInventory(); mage.getPlayer().openInventory(getDisplayInventory()); } else if (wandMode == WandMode.INVENTORY) { if (hasStoredInventory()) return; if (storeInventory()) { inventoryIsOpen = true; showActiveIcon(true); if (!playPassiveEffects("open") && inventoryOpenSound != null) { mage.playSoundEffect(inventoryOpenSound); } updateInventory(); updateHotbarStatus(); } } } @Override public void closeInventory() { if (!isInventoryOpen()) return; controller.disableItemSpawn(); inventoryWasOpen = true; WandMode mode = getMode(); try { saveInventory(); updateSpellInventory(); updateBrushInventory(); inventoryIsOpen = false; if (mage != null) { if (!playPassiveEffects("close") && inventoryCloseSound != null) { mage.playSoundEffect(inventoryCloseSound); } if (mode == WandMode.INVENTORY) { restoreInventory(); showActiveIcon(false); } else { mage.getPlayer().closeInventory(); } // Check for items the player might've glitched onto their body... PlayerInventory inventory = mage.getPlayer().getInventory(); ItemStack testItem = inventory.getHelmet(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setHelmet(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getBoots(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setBoots(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getLeggings(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setLeggings(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } testItem = inventory.getChestplate(); if (isSpell(testItem) || isBrush(testItem)) { inventory.setChestplate(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } // This is kind of a hack :( testItem = inventory.getItemInOffHand(); if ((isSpell(testItem) && !isSkill(testItem)) || isBrush(testItem)) { inventory.setItemInOffHand(new ItemStack(Material.AIR)); DeprecatedUtils.updateInventory(mage.getPlayer()); } } } catch (Throwable ex) { restoreInventory(); } if (mode == WandMode.INVENTORY && mage != null) { try { mage.getPlayer().closeInventory(); } catch (Throwable ex) { ex.printStackTrace(); } } controller.enableItemSpawn(); inventoryWasOpen = false; } @Override public boolean fill(Player player) { return fill(player, 0); } @Override public boolean fill(Player player, int maxLevel) { String mageId = mage.getId(); closeInventory(); Collection<String> currentSpells = new ArrayList<>(getSpells()); for (String spellKey : currentSpells) { SpellTemplate spell = controller.getSpellTemplate(spellKey); boolean removeSpell = !spell.hasCastPermission(player); String creatorId = spell.getCreatorId(); removeSpell = removeSpell || (FILL_CREATOR && (creatorId == null || !mageId.equals(creatorId))); if (removeSpell) { removeSpell(spellKey); } } Collection<SpellTemplate> allSpells = controller.getPlugin().getSpellTemplates(); // Hack to prevent messaging Mage mage = this.mage; this.mage = null; for (SpellTemplate spell : allSpells) { String key = spell.getKey(); if (maxLevel > 0 && spell.getSpellKey().getLevel() > maxLevel) { continue; } if (key.startsWith("heroes*")) { continue; } String creatorId = spell.getCreatorId(); if (FILL_CREATOR && (creatorId == null || !mageId.equals(creatorId))) { continue; } if (spell.hasCastPermission(player) && spell.hasIcon() && !spell.isHidden()) { addSpell(key); } } this.mage = mage; if (!FILL_CREATOR) { if (autoFill) setProperty("fill", false); autoFill = false; } saveState(); return true; } protected void checkActiveMaterial() { if (activeBrush == null || activeBrush.length() == 0) { Set<String> materials = getBrushes(); if (materials.size() > 0) { activeBrush = materials.iterator().next(); } } } @Override public boolean addItem(ItemStack item) { if (isUpgrade) return false; if (isModifiable() && isSpell(item) && !isSkill(item)) { String spell = getSpell(item); SpellKey spellKey = new SpellKey(spell); Integer currentLevel = spellLevels.get(spellKey.getBaseKey()); if ((currentLevel == null || currentLevel < spellKey.getLevel()) && addSpell(spell)) { return true; } } else if (isModifiable() && isBrush(item)) { String materialKey = getBrush(item); Set<String> materials = getBrushes(); if (!materials.contains(materialKey) && addBrush(materialKey)) { return true; } } else if (isUpgrade(item)) { Wand wand = controller.getWand(item); return this.add(wand); } if (mage != null && !mage.isAtMaxSkillPoints() && controller.skillPointItemsEnabled()) { Integer sp = getSP(item); if (sp != null) { int amount = (int)Math.floor(mage.getSPMultiplier() * sp * item.getAmount()); mage.addSkillPoints(amount); return true; } } return false; } protected void updateEffects() { updateEffects(mage); } public void updateEffects(Mage mage) { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; // Update Bubble effects effects if (effectBubbles && effectColor != null) { Location potionEffectLocation = player.getLocation(); potionEffectLocation.setX(potionEffectLocation.getX() + random.nextDouble() - 0.5); potionEffectLocation.setY(potionEffectLocation.getY() + random.nextDouble() * player.getEyeHeight()); potionEffectLocation.setZ(potionEffectLocation.getZ() + random.nextDouble() - 0.5); EffectPlayer.displayParticle(Particle.SPELL_MOB, potionEffectLocation, 0, 0, 0, 0, 0, 1, effectColor.getColor(), null, (byte)0, 24); } Location location = mage.getLocation(); long now = System.currentTimeMillis(); boolean playEffects = !activeEffectsOnly || inventoryIsOpen || isInOffhand; if (playEffects && effectParticle != null && effectParticleInterval > 0 && effectParticleCount > 0) { boolean velocityCheck = true; if (effectParticleMinVelocity > 0) { double velocitySquared = effectParticleMinVelocity * effectParticleMinVelocity; Vector velocity = mage.getVelocity().clone(); velocity.setY(0); double speedSquared = velocity.lengthSquared(); velocityCheck = (speedSquared > velocitySquared); } if (velocityCheck && (lastParticleEffect == 0 || now > lastParticleEffect + effectParticleInterval)) { lastParticleEffect = now; Location effectLocation = player.getLocation(); Location eyeLocation = player.getEyeLocation(); effectLocation.setY(eyeLocation.getY() + effectParticleOffset); if (effectPlayer == null) { effectPlayer = new EffectRing(controller.getPlugin()); effectPlayer.setParticleCount(1); effectPlayer.setIterations(1); effectPlayer.setParticleOffset(0, 0, 0); } effectPlayer.setMaterial(location.getBlock().getRelative(BlockFace.DOWN)); if (effectParticleData == 0) { effectPlayer.setColor(getEffectColor()); } else { effectPlayer.setColor(null); } effectPlayer.setParticleType(effectParticle); effectPlayer.setParticleData(effectParticleData); effectPlayer.setSize(effectParticleCount); effectPlayer.setRadius((float)effectParticleRadius); effectPlayer.start(effectLocation, null); } } if (castSpell != null && castInterval > 0) { if (lastSpellCast == 0 || now > lastSpellCast + castInterval) { boolean velocityCheck = true; if (castMinVelocity > 0) { double velocitySquared = castMinVelocity * castMinVelocity; Vector velocity = mage.getVelocity(); if (castVelocityDirection != null) { velocity = velocity.clone().multiply(castVelocityDirection); // This is kind of a hack to make jump-detection work. if (castVelocityDirection.getY() < 0) { velocityCheck = velocity.getY() < 0; } else { velocityCheck = velocity.getY() > 0; } } if (velocityCheck) { double speedSquared = velocity.lengthSquared(); velocityCheck = (speedSquared > velocitySquared); } } if (velocityCheck) { lastSpellCast = now; Spell spell = mage.getSpell(castSpell); if (spell != null) { if (castParameters == null) { castParameters = new MemoryConfiguration(); } castParameters.set("passive", true); mage.setCostFree(true); mage.setQuiet(true); try { spell.cast(castParameters); } catch (Exception ex) { controller.getLogger().log(Level.WARNING, "Error casting aura spell " + spell.getKey(), ex); } mage.setCostFree(false); mage.setQuiet(false); } } } } if (playEffects && effectSound != null && controller.soundsEnabled() && effectSoundInterval > 0) { if (lastSoundEffect == 0 || now > lastSoundEffect + effectSoundInterval) { lastSoundEffect = now; effectSound.play(controller.getPlugin(), mage.getPlayer()); } } } protected void updateDurability() { int maxDurability = item.getType().getMaxDurability(); if (maxDurability > 0 && effectiveManaMax > 0) { int durability = (short)(getMana() * maxDurability / effectiveManaMax); durability = maxDurability - durability; if (durability >= maxDurability) { durability = maxDurability - 1; } else if (durability < 0) { durability = 0; } item.setDurability((short)durability); } } public boolean usesXPBar() { return (usesSP() && spMode.useXP()) || (usesMana() && manaMode.useXP()); } public boolean usesXPNumber() { return (usesSP() && spMode.useXPNumber() && controller.isSPEnabled()) || (usesMana() && manaMode.useXP()); } public boolean hasSpellProgression() { return hasSpellProgression; } public boolean usesXPDisplay() { return usesXPBar() || usesXPNumber(); } @Override public void updateMana() { Player player = mage == null ? null : mage.getPlayer(); if (player == null) return; float mana = getMana(); if (usesMana()) { if (manaMode.useGlow()) { if (mana == effectiveManaMax) { CompatibilityUtils.addGlow(item); } else { CompatibilityUtils.removeGlow(item); } } if (manaMode.useDurability()) { updateDurability(); } } if (usesXPDisplay()) { int playerLevel = player.getLevel(); float playerProgress = player.getExp(); if (usesMana() && manaMode.useXPNumber()) { playerLevel = (int) mana; } if (usesMana() && manaMode.useXPBar()) { playerProgress = Math.max(0, mana / effectiveManaMax); } if (usesSP() && spMode.useXPNumber()) { playerLevel = mage.getSkillPoints(); } mage.sendExperience(playerProgress, playerLevel); } } @Override public boolean isInventoryOpen() { return mage != null && inventoryIsOpen; } // Somewhat hacky method to handle inventory close event knowing that this was a wand inventory that just closed. public boolean wasInventoryOpen() { return inventoryWasOpen; } @Override public void unbind() { if (!bound) return; com.elmakers.mine.bukkit.api.magic.Mage owningMage = this.mage; deactivate(); if (ownerId != null) { if (owningMage == null || !owningMage.getId().equals(ownerId)) { owningMage = controller.getRegisteredMage(ownerId); } if (owningMage != null) { owningMage.unbind(this); } ownerId = null; } bound = false; owner = null; setProperty("bound", false); setProperty("owner", null); setProperty("owner_id", null); saveState(); updateLore(); updateName(); } @Override public void bind() { if (bound) return; Mage holdingMage = mage; deactivate(); bound = true; setProperty("bound", true); saveState(); if (holdingMage != null) { holdingMage.checkWand(); } } @Override public void deactivate() { if (mage == null) return; // Play deactivate FX playPassiveEffects("deactivate"); // Cancel effects if (effectContext != null) { int cancelDelay = getInt("cancel_effects_delay", 0); if (cancelDelay == 0) { effectContext.cancelEffects(); } else { Plugin plugin = controller.getPlugin(); final WandEffectContext context = effectContext; plugin.getServer().getScheduler().runTaskLater(plugin, new Runnable() { @Override public void run() { context.cancelEffects(); } }, cancelDelay * 20 / 1000); } } Mage mage = this.mage; if (isInventoryOpen()) { closeInventory(); } showActiveIcon(false); storedInventory = null; if (usesXPNumber() || usesXPBar()) { mage.resetSentExperience(); } saveState(); mage.deactivateWand(this); this.mage = null; updateMaxMana(true); } @Nullable @Override public Spell getActiveSpell() { if (mage == null) return null; String activeSpellKey = getActiveSpellKey(); if (activeSpellKey == null || activeSpellKey.length() == 0) return null; return mage.getSpell(activeSpellKey); } @Nullable public Spell getAlternateSpell() { if (mage == null || alternateSpell == null || alternateSpell.length() == 0) return null; return mage.getSpell(alternateSpell); } @Nullable public Spell getAlternateSpell2() { if (mage == null || alternateSpell2 == null || alternateSpell2.length() == 0) return null; return mage.getSpell(alternateSpell2); } @Nullable @Override public SpellTemplate getBaseSpell(String spellName) { return getBaseSpell(new SpellKey(spellName)); } @Nullable public SpellTemplate getBaseSpell(SpellKey key) { if (!spells.contains(key.getBaseKey())) return null; SpellKey baseKey = new SpellKey(key.getBaseKey(), getSpellLevel(key.getBaseKey())); return controller.getSpellTemplate(baseKey.getKey()); } @Override public String getActiveSpellKey() { String activeSpellKey = activeSpell; Integer level = spellLevels.get(activeSpellKey); if (level != null) { activeSpellKey = new SpellKey(activeSpellKey, level).getKey(); } return activeSpellKey; } @Override public String getActiveBrushKey() { return activeBrush; } @Override public void damageDealt(double damage, Entity target) { if (manaPerDamage > 0) { int manaMax = getEffectiveManaMax(); float mana = getMana(); if (manaMax > 0 && mana < manaMax) { setMana(Math.min(manaMax, mana + (float)damage * manaPerDamage)); updateMana(); } } } public boolean alternateCast() { return cast(getAlternateSpell()); } public boolean alternateCast2() { return cast(getAlternateSpell2()); } @Override public boolean cast() { return cast(getActiveSpell(), null); } @Override public boolean cast(String[] parameters) { return cast(getActiveSpell(), parameters); } public boolean cast(Spell spell) { return cast(spell, null); } public boolean cast(Spell spell, String[] parameters) { if (spell != null) { Collection<String> castParameters = null; if (castOverrides != null && castOverrides.size() > 0) { castParameters = new ArrayList<>(); for (Map.Entry<String, String> entry : castOverrides.entrySet()) { String[] key = StringUtils.split(entry.getKey(), '.'); if (key.length == 0) continue; if (key.length == 2 && !key[0].equals("default") && !key[0].equals(spell.getSpellKey().getBaseKey()) && !key[0].equals(spell.getSpellKey().getKey())) { continue; } castParameters.add(key.length == 2 ? key[1] : key[0]); castParameters.add(entry.getValue()); } } if (parameters != null) { if (castParameters == null) { castParameters = new ArrayList<>(); } for (String parameter : parameters) { castParameters.add(parameter); } } if (spell.cast(castParameters == null ? null : castParameters.toArray(EMPTY_PARAMETERS))) { Color spellColor = spell.getColor(); use(); if (spellColor != null && this.effectColor != null) { this.effectColor = this.effectColor.mixColor(spellColor, effectColorSpellMixWeight); setProperty("effect_color", effectColor.toString()); // Note that we don't save this change. // The hope is that the wand will get saved at some point later // And we don't want to trigger NBT writes every spell cast. // And the effect color morphing isn't all that important if a few // casts get lost. } updateHotbarStatus(); return true; } } return false; } protected void use() { if (hasUses) { findItem(); ItemStack item = getItem(); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { if (uses > 0) { uses--; } if (uses <= 0 && mage != null) { // If the wand is not currently active it will be destroyed on next activate Player player = mage.getPlayer(); deactivate(); PlayerInventory playerInventory = player.getInventory(); if (item.getAmount() > 1) { item.setAmount(item.getAmount() - 1); } else { if (isInOffhand) { playerInventory.setItemInOffHand(new ItemStack(Material.AIR, 1)); } else { playerInventory.setItemInMainHand(new ItemStack(Material.AIR, 1)); } } DeprecatedUtils.updateInventory(player); } setProperty("uses", uses); saveState(); updateName(); updateLore(); } } } // Taken from NMS HumanEntity public static int getExpToLevel(int expLevel) { return expLevel >= 30 ? 112 + (expLevel - 30) * 9 : (expLevel >= 15 ? 37 + (expLevel - 15) * 5 : 7 + expLevel * 2); } public static int getExperience(int expLevel, float expProgress) { int xp = 0; for (int level = 0; level < expLevel; level++) { xp += Wand.getExpToLevel(level); } return xp + (int) (expProgress * Wand.getExpToLevel(expLevel)); } protected void updateHotbarStatus() { Player player = mage == null ? null : mage.getPlayer(); if (player != null && LiveHotbar && getMode() == WandMode.INVENTORY && isInventoryOpen()) { mage.updateHotbarStatus(); } } @Override public boolean tickMana() { if (isHeroes) { HeroesManager heroes = controller.getHeroes(); if (heroes != null && mage != null && mage.isPlayer()) { Player player = mage.getPlayer(); effectiveManaMax = heroes.getMaxMana(player); effectiveManaRegeneration = heroes.getManaRegen(player); setManaMax(effectiveManaMax); setManaRegeneration(effectiveManaRegeneration); setMana(heroes.getMana(player)); return true; } return false; } return super.tickMana(); } @Override public void tick() { if (mage == null) return; Player player = mage.getPlayer(); if (player == null) return; super.tick(); if (usesMana() && !isInOffhand) { updateMana(); } if (player.isBlocking() && blockMageCooldown > 0) { mage.setRemainingCooldown(blockMageCooldown); } // Update hotbar glow if (!isInOffhand) { updateHotbarStatus(); } if (!passive) { updateEffects(); } } @Override public void armorUpdated() { updateMaxMana(true); } protected void updateMaxMana(boolean updateLore) { if (isHeroes) return; if (!hasOwnMana() && mageClass != null) { if (mageClass.updateMaxMana(mage) && updateLore) { updateLore(); } effectiveManaMax = mageClass.getEffectiveManaMax(); effectiveManaRegeneration = mageClass.getEffectiveManaRegeneration(); } else if (super.updateMaxMana(mage) && updateLore) { updateLore(); } } public void cycleSpells(int direction) { ArrayList<String> spells = new ArrayList<>(this.spells); if (spells.size() == 0) return; if (activeSpell == null) { setActiveSpell(spells.get(0)); return; } int spellIndex = 0; for (int i = 0; i < spells.size(); i++) { if (spells.get(i).equals(activeSpell)) { spellIndex = i; break; } } spellIndex = (spellIndex + direction) % spells.size(); setActiveSpell(spells.get(spellIndex)); } public void cycleMaterials(int direction) { Set<String> materialsSet = getBrushes(); ArrayList<String> materials = new ArrayList<>(materialsSet); if (materials.size() == 0) return; if (activeBrush == null) { setActiveBrush(StringUtils.split(materials.get(0), '@')[0]); return; } int materialIndex = 0; for (int i = 0; i < materials.size(); i++) { if (StringUtils.split(materials.get(i),'@')[0].equals(activeBrush)) { materialIndex = i; break; } } materialIndex = (materialIndex + direction) % materials.size(); setActiveBrush(StringUtils.split(materials.get(materialIndex), '@')[0]); } @Nullable public Mage getActiveMage() { // TODO: Duplicate of #getMage() return mage; } public void setActiveMage(com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage instanceof Mage) { this.mage = (Mage)mage; armorUpdated(); } } @Nullable @Override public Color getEffectColor() { return effectColor == null ? null : effectColor.getColor(); } public Particle getEffectParticle() { return effectParticle; } @Nullable @Override public String getEffectParticleName() { return effectParticle == null ? null : effectParticle.name(); } @Nullable public Inventory getHotbar() { if (this.hotbars.size() == 0) return null; if (currentHotbar < 0 || currentHotbar >= this.hotbars.size()) { setCurrentHotbar(0); } return this.hotbars.get(currentHotbar); } public int getHotbarCount() { if (getMode() != WandMode.INVENTORY) return 0; return hotbars.size(); } public List<Inventory> getHotbars() { return hotbars; } @Override public boolean isQuickCastDisabled() { return quickCastDisabled; } public boolean isManualQuickCastDisabled() { return manualQuickCastDisabled; } @Override public boolean isQuickCast() { return quickCast; } public WandMode getMode() { return mode; } public WandMode getBrushMode() { return brushMode; } public void setMode(WandMode mode) { this.mode = mode; } public void setBrushMode(WandMode mode) { this.brushMode = mode; } @Override public boolean showCastMessages() { return quietLevel == 0; } @Override public boolean showMessages() { return quietLevel < 2; } public boolean isStealth() { return quietLevel > 2; } @Override public void setPath(String path) { String oldPath = this.path; this.path = path; setProperty("path", path); // Handle the case of a path upgrade meaning there are suddenly more spells or brushes available boolean updateInventory = limitBrushesToPath || limitSpellsToPath; if (!oldPath.equals(path) && updateInventory) { closeInventory(); if (limitSpellsToPath) { loadSpells(); } if (limitBrushesToPath) { loadBrushes(); } buildInventory(); } } /* * Public API Implementation */ @Override public boolean isLost(com.elmakers.mine.bukkit.api.wand.LostWand lostWand) { return this.id != null && this.id.equals(lostWand.getId()); } @Override public LostWand makeLost(Location location) { checkId(); saveState(); return new LostWand(this, location); } protected void showActiveIcon(boolean show) { if (this.icon == null || this.inactiveIcon == null || this.inactiveIcon.getMaterial() == Material.AIR || this.inactiveIcon.getMaterial() == null) return; if (this.icon.getMaterial() == Material.AIR || this.icon.getMaterial() == null) { this.icon.setMaterial(DefaultWandMaterial); } if (show) { if (inactiveIconDelay > 0) { Plugin plugin = controller.getPlugin(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { findItem(); icon.applyToItem(item); } }, inactiveIconDelay * 20 / 1000); } else { findItem(); icon.applyToItem(item); } } else { findItem(); inactiveIcon.applyToItem(this.item); } } public boolean activateOffhand(Mage mage) { return activate(mage, true); } @Override @Deprecated public void activate(com.elmakers.mine.bukkit.api.magic.Mage mage) { if (mage instanceof Mage) { activate((Mage)mage); } } public boolean activate(Mage mage) { return activate(mage, false); } public boolean activate(Mage mage, boolean offhand) { if (mage == null) return false; Player player = mage.getPlayer(); if (player == null) return false; if (!controller.hasWandPermission(player, this)) return false; InventoryView openInventory = player.getOpenInventory(); InventoryType inventoryType = openInventory.getType(); if (inventoryType == InventoryType.ENCHANTING || inventoryType == InventoryType.ANVIL) return false; if (hasUses && uses <= 0) { if (offhand) { player.getInventory().setItemInOffHand(new ItemStack(Material.AIR, 1)); } else { player.getInventory().setItemInMainHand(new ItemStack(Material.AIR, 1)); } return false; } if (!canUse(player)) { mage.sendMessage(getMessage("bound").replace("$name", getOwner())); return false; } if (this.isUpgrade) { controller.getLogger().warning("Activated an upgrade item- this shouldn't happen"); return false; } WandPreActivateEvent preActivateEvent = new WandPreActivateEvent(mage, this); Bukkit.getPluginManager().callEvent(preActivateEvent); if (preActivateEvent.isCancelled()) { return false; } boolean needsSave = false; if (hasId) { needsSave = this.checkId() || needsSave; } else { setProperty("id", null); } this.mage = mage; this.isInOffhand = offhand; this.heldSlot = offhand ? OFFHAND_SLOT : player.getInventory().getHeldItemSlot(); if (mageClassKeys != null && !mageClassKeys.isEmpty()) { MageClass mageClass = null; for (String mageClassKey : mageClassKeys) { mageClass = mage.getClass(mageClassKey); if (mageClass != null) break; } if (mageClass == null) { Integer lastSlot = mage.getLastActivatedSlot(); if (!offhand && (lastSlot == null || lastSlot != player.getInventory().getHeldItemSlot())) { mage.setLastActivatedSlot(player.getInventory().getHeldItemSlot()); mage.sendMessage(controller.getMessages().get("mage.no_class").replace("$name", getName())); } return false; } setMageClass(mageClass); if (!offhand) { mage.setActiveClass(mageClass.getKey()); } // This double-load here is not really ideal. // Seems hard to prevent without merging Wand construction and activation, though. loadProperties(); } mage.setLastActivatedSlot(player.getInventory().getHeldItemSlot()); // Check for replacement template String replacementTemplate = getString("replace_on_activate", ""); if (!replacementTemplate.isEmpty() && !replacementTemplate.equals(template)) { playEffects("replace"); setTemplate(replacementTemplate); loadProperties(); saveState(); return activate(mage, offhand); } // Since these wands can't be opened we will just show them as open when held // We have to delay this 1 tick so it happens after the Mage has accepted the Wand if (getMode() != WandMode.INVENTORY || offhand) { Plugin plugin = controller.getPlugin(); plugin.getServer().getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() { @Override public void run() { showActiveIcon(true); playPassiveEffects("open"); } }, 1); } // Check for an empty wand and auto-fill if (!isUpgrade && (controller.fillWands() || autoFill)) { fill(mage.getPlayer(), controller.getMaxWandFillLevel()); needsSave = true; } if (isHeroes) { HeroesManager heroes = controller.getHeroes(); if (heroes != null) { Set<String> skills = heroes.getSkills(player); Collection<String> currentSpells = new ArrayList<>(getSpells()); for (String spellKey : currentSpells) { if (spellKey.startsWith("heroes*") && !skills.contains(spellKey.substring(7))) { removeSpell(spellKey); } } // Hack to prevent messaging this.mage = null; for (String skillKey : skills) { String heroesKey = "heroes*" + skillKey; if (!spells.contains(heroesKey)) { addSpell(heroesKey); } } this.mage = mage; } } // Check for auto-organize if (autoOrganize && !isUpgrade) { organizeInventory(mage); needsSave = true; } // Check for auto-alphabetize if (autoAlphabetize && !isUpgrade) { alphabetizeInventory(); needsSave = true; } boolean forceUpdate = false; if (checkInventoryForUpgrades()) { forceUpdate = true; needsSave = true; } // Check for auto-bind if (bound) { String mageName = ChatColor.stripColor(mage.getPlayer().getDisplayName()); String mageId = mage.getId(); boolean ownerRenamed = owner != null && ownerId != null && ownerId.equals(mageId) && !owner.equals(mageName); if (ownerId == null || ownerId.length() == 0 || owner == null || ownerRenamed) { takeOwnership(mage.getPlayer()); needsSave = true; } } // Check for randomized wands if (randomizeOnActivate) { randomize(); randomizeOnActivate = false; forceUpdate = true; needsSave = true; } // Don't build the inventory until activated so we can take Mage boosts into account if (offhand) { mage.setOffhandWand(this); } else { mage.setActiveWand(this); } buildInventory(); updateMaxMana(false); tick(); if (!isInOffhand) { updateMana(); } checkActiveMaterial(); if (needsSave) { saveState(); } updateActiveMaterial(); updateName(); updateLore(); // Play activate FX playPassiveEffects("activate"); lastSoundEffect = 0; lastParticleEffect = 0; lastSpellCast = 0; if (forceUpdate) { DeprecatedUtils.updateInventory(player); } return true; } public boolean checkInventoryForUpgrades() { boolean updated = false; Player player = mage == null ? null : mage.getPlayer(); if (player == null || mage.hasStoredInventory()) return false; // Check for spell or other special icons in the player's inventory Inventory inventory = player.getInventory(); ItemStack[] items = inventory.getContents(); for (int i = 0; i < items.length; i++) { ItemStack item = items[i]; if (addItem(item)) { inventory.setItem(i, null); updated = true; } } return updated; } private void setOpenInventoryPage(int page) { this.openInventoryPage = page; this.setProperty("page", page); } @Override public boolean organizeInventory() { if (mage != null) { return organizeInventory(mage); } return false; } @Override public boolean organizeInventory(com.elmakers.mine.bukkit.api.magic.Mage mage) { WandOrganizer organizer = new WandOrganizer(this, mage); closeInventory(); organizer.organize(); setOpenInventoryPage(0); setCurrentHotbar(currentHotbar); if (autoOrganize) setProperty("organize", false); autoOrganize = false; updateSpellInventory(); updateBrushInventory(); if (this.mage != null) { buildInventory(); } return true; } @Override public boolean alphabetizeInventory() { WandOrganizer organizer = new WandOrganizer(this); closeInventory(); organizer.alphabetize(); setOpenInventoryPage(0); setCurrentHotbar(0); if (autoAlphabetize) setProperty("alphabetize", false); autoAlphabetize = false; updateSpellInventory(); updateBrushInventory(); if (mage != null) { buildInventory(); } return true; } @Override public com.elmakers.mine.bukkit.api.wand.Wand duplicate() { ItemStack newItem = InventoryUtils.getCopy(item); Wand newWand = controller.getWand(newItem); newWand.saveState(); return newWand; } @Override @Deprecated public boolean configure(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); configure(ConfigurationUtils.toConfigurationSection(convertedProperties)); return true; } @Override public void updated() { loadProperties(); if (mage != null) { buildInventory(); } saveState(); updateMaxMana(false); updateName(); updateLore(); } @Override public boolean isLocked() { return this.locked; } @Override public boolean upgradesAllowed() { return !this.locked || this.lockedAllowUpgrades; } @Override public void unlock() { locked = false; setProperty("locked", false); } public boolean isPassive() { return passive; } @Override public boolean canUse(Player player) { if (!bound || ownerId == null || ownerId.length() == 0) return true; if (controller.hasPermission(player, "Magic.wand.override_bind", false)) return true; String playerId = controller.getMageIdentifier().fromEntity(player); if (ownerId.equalsIgnoreCase(playerId)) { return true; } // Fall back to checking the UUID rather than the mage ID // This can be removed when all AMC wands have been migrated return ownerId.equals(player.getUniqueId().toString()); } @Override public boolean addSpell(String spellName) { if (!isModifiable()) return false; return forceAddSpell(spellName); } @Override public boolean forceAddSpell(String spellName) { SpellTemplate template = controller.getSpellTemplate(spellName); if (template == null) { return false; } SpellKey spellKey = template.getSpellKey(); if (limitSpellsToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsSpell(spellKey.getBaseKey())) return false; } if (!super.addSpell(spellName)) { return false; } saveInventory(); ItemStack spellItem = createSpellIcon(template); if (spellItem == null) { return false; } int level = spellKey.getLevel(); int inventoryCount = inventories.size(); int spellCount = spells.size(); // Look for existing spells for spell upgrades Integer inventorySlot = spellInventory.get(spellKey.getBaseKey()); SpellTemplate currentSpell = getBaseSpell(spellKey); clearSlot(inventorySlot); setSpellLevel(spellKey.getBaseKey(), level); spells.add(spellKey.getBaseKey()); if (activeSpell == null || activeSpell.isEmpty()) { setActiveSpell(spellKey.getBaseKey()); } addToInventory(spellItem, inventorySlot); checkSpellLevelsAndInventory(); updateInventory(); updateHasInventory(); saveState(); updateLore(); if (mage != null) { if (spells.size() != spellCount) { if (spellCount == 0) { if (leftClickAction == WandAction.CAST) { String message = getMessage("spell_instructions", "").replace("$wand", getName()); mage.sendMessage(message.replace("$spell", template.getName())); } } else if (spellCount == 1) { String controlKey = getControlKey(WandAction.TOGGLE); String inventoryMessage = null; switch (getMode()) { case INVENTORY: inventoryMessage = "inventory_instructions"; break; case CHEST: inventoryMessage = "chest_instructions"; break; case SKILLS: inventoryMessage = "skills_instructions"; break; case CYCLE: inventoryMessage = "cycle_instructions"; if (controlKey == null) { controlKey = getControlKey(WandAction.CYCLE); } break; case CAST: case NONE: // Ignore break; } if (controlKey != null && inventoryMessage != null) { controlKey = controller.getMessages().get("controls." + controlKey); mage.sendMessage(getMessage(inventoryMessage, "") .replace("$wand", getName()).replace("$toggle", controlKey).replace("$cycle", controlKey)); } } if (inventoryCount == 1 && inventories.size() > 1) { mage.sendMessage(getMessage("page_instructions", "").replace("$wand", getName())); } } } return true; } /** * Covers the special case of a wand having spell levels and inventory slots that came from configs, * but now we've modified the spells list and need to figure out if we also need to pesist the levels and * slots separately. * * <p>This should all be moved to CasterProperties at some point to handle the same sort of issues with mage class * configs. */ private void checkSpellLevelsAndInventory() { if (!spellLevels.isEmpty()) { MagicProperties storage = getStorage("spell_levels"); if (storage == null || storage == this) { if (!configuration.contains("spell_levels")) { configuration.set("spell_levels", spellLevels); } } } if (!spellInventory.isEmpty()) { MagicProperties storage = getStorage("spell_inventory"); if (storage == null || storage == this) { if (!configuration.contains("spell_inventory")) { configuration.set("spell_inventory", spellInventory); } } } } private void clearSlot(Integer slot) { if (slot != null) { Inventory inventory = getInventory(slot); slot = getInventorySlot(slot); inventory.setItem(slot, null); } } @Override public String getMessage(String messageKey, String defaultValue) { String message = super.getMessage(messageKey, defaultValue); // Some special-casing here, not sure how to avoid. if (messageKey.equals("hotbar_count_usage")) { String controlKey = getControlKey(WandAction.CYCLE_HOTBAR); if (controlKey != null) { controlKey = controller.getMessages().get("controls." + controlKey); message = message.replace("$cycle_hotbar", controlKey); } else { return ""; } } return message; } @Override protected String getMessageKey(String key) { String wandKey = "wands." + template + "." + key; if (template != null && !template.isEmpty() && controller.getMessages().containsKey(wandKey)) { return wandKey; } return "wand." + key; } @Override protected String parameterizeMessage(String message) { return message.replace("$wand", getName()); } @Override public boolean hasBrush(String materialKey) { if (limitBrushesToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsBrush(materialKey)) return false; } return getBrushes().contains(materialKey); } @Override public boolean hasSpell(String spellName) { return hasSpell(new SpellKey(spellName)); } @Override public boolean hasSpell(SpellKey spellKey) { if (!spells.contains(spellKey.getBaseKey())) return false; if (limitSpellsToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsSpell(spellKey.getBaseKey())) return false; } int level = getSpellLevel(spellKey.getBaseKey()); return (level >= spellKey.getLevel()); } @Override public boolean addBrush(String materialKey) { if (!isModifiable()) return false; if (limitBrushesToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsBrush(materialKey)) return false; } if (!super.addBrush(materialKey)) return false; saveInventory(); ItemStack itemStack = createBrushIcon(materialKey); if (itemStack == null) return false; int inventoryCount = inventories.size(); int brushCount = brushes.size(); brushInventory.put(materialKey, null); brushes.add(materialKey); addToInventory(itemStack); if (activeBrush == null || activeBrush.length() == 0) { activateBrush(materialKey); } else { updateInventory(); } updateHasInventory(); saveState(); updateLore(); if (mage != null) { if (brushCount == 0) { String controlKey = getControlKey(WandAction.TOGGLE); if (controlKey != null) { controlKey = controller.getMessages().get("controls." + controlKey); mage.sendMessage(getMessage("brush_instructions") .replace("$wand", getName()).replace("$toggle", controlKey)); } } if (inventoryCount == 1 && inventories.size() > 1) { mage.sendMessage(getMessage("page_instructions").replace("$wand", getName())); } } return true; } @Override public void setActiveBrush(String materialKey) { activateBrush(materialKey); if (materialKey == null || mage == null) { return; } com.elmakers.mine.bukkit.api.block.MaterialBrush brush = mage.getBrush(); if (brush == null) { return; } boolean eraseWasActive = brush.isEraseModifierActive(); brush.activate(mage.getLocation(), materialKey); BrushMode mode = brush.getMode(); if (mode == BrushMode.CLONE) { mage.sendMessage(getMessage("clone_material_activated")); } else if (mode == BrushMode.REPLICATE) { mage.sendMessage(getMessage("replicate_material_activated")); } if (!eraseWasActive && brush.isEraseModifierActive()) { mage.sendMessage(getMessage("erase_modifier_activated")); } } public void setActiveBrush(ItemStack itemStack) { if (!isBrush(itemStack)) return; setActiveBrush(getBrush(itemStack)); } public void activateBrush(String materialKey) { this.activeBrush = materialKey; setProperty("active_brush", this.activeBrush); saveState(); updateActiveMaterial(); updateName(); updateHotbar(); } @Override public void setActiveSpell(String activeSpell) { if (activeSpell != null) { SpellKey spellKey = new SpellKey(activeSpell); this.activeSpell = spellKey.getBaseKey(); } else { this.activeSpell = null; } checkActiveSpell(); setProperty("active_spell", this.activeSpell); saveState(); updateName(); } protected void checkActiveSpell() { // Support wands with just an active spell and no spells list if (activeSpell != null && !spells.isEmpty() && !spells.contains(activeSpell)) { activeSpell = null; } } @Override public boolean removeBrush(String materialKey) { if (!isModifiable() || materialKey == null) return false; if (limitBrushesToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsBrush(materialKey)) return false; } if (!removeBrush(materialKey)) return false; saveInventory(); if (materialKey.equals(activeBrush)) { activeBrush = null; } clearSlot(brushInventory.get(materialKey)); brushInventory.remove(materialKey); boolean found = brushes.remove(materialKey); if (activeBrush == null && brushes.size() > 0) { activeBrush = brushes.iterator().next(); } updateActiveMaterial(); updateInventory(); updateBrushInventory(); saveState(); updateName(); updateLore(); return found; } @Override public boolean removeSpell(String spellName) { if (!isModifiable()) return false; SpellKey spellKey = new SpellKey(spellName); if (limitSpellsToPath) { WandUpgradePath path = getPath(); if (path != null && !path.containsSpell(spellKey.getBaseKey())) return false; } if (!super.removeSpell(spellName)) return false; saveInventory(); if (activeSpell != null) { SpellKey activeKey = new SpellKey(activeSpell); if (spellKey.getBaseKey().equals(activeKey.getBaseKey())) { setActiveSpell(null); } } clearSlot(spellInventory.get(spellKey.getBaseKey())); spells.remove(spellKey.getBaseKey()); spellLevels.remove(spellKey.getBaseKey()); spellInventory.remove(spellKey.getBaseKey()); if (activeSpell == null && spells.size() > 0) { setActiveSpell(spells.iterator().next()); } checkSpellLevelsAndInventory(); updateInventory(); updateHasInventory(); updateSpellInventory(); saveState(); updateName(); updateLore(); return true; } @Override public Map<String, String> getOverrides() { return castOverrides == null ? new HashMap<String, String>() : new HashMap<>(castOverrides); } @Override public void setOverrides(Map<String, String> overrides) { if (overrides == null) { this.castOverrides = null; } else { this.castOverrides = new HashMap<>(overrides); } updateOverrides(); } @Override public void removeOverride(String key) { if (castOverrides != null) { castOverrides.remove(key); updateOverrides(); } } @Override public void setOverride(String key, String value) { if (castOverrides == null) { castOverrides = new HashMap<>(); } if (value == null || value.length() == 0) { castOverrides.remove(key); } else { castOverrides.put(key, value); } updateOverrides(); } @Override public boolean addOverride(String key, String value) { if (castOverrides == null) { castOverrides = new HashMap<>(); } boolean modified = false; if (value == null || value.length() == 0) { modified = castOverrides.containsKey(key); castOverrides.remove(key); } else { String current = castOverrides.get(key); modified = current == null || !current.equals(value); castOverrides.put(key, value); } if (modified) { updateOverrides(); } return modified; } protected void updateOverrides() { if (castOverrides != null && !castOverrides.isEmpty()) { setProperty("overrides", castOverrides); } else { setProperty("overrides", null); } } public boolean hasStoredInventory() { return storedInventory != null; } public Inventory getStoredInventory() { return storedInventory; } public boolean addToStoredInventory(ItemStack item) { if (storedInventory == null) { return false; } HashMap<Integer, ItemStack> remainder = storedInventory.addItem(item); return remainder.size() == 0; } public void setHeldSlot(int slot) { this.heldSlot = slot; } public boolean storeInventory() { if (storedInventory != null) { if (mage != null) { mage.sendMessage("Your wand contains a previously stored inventory and will not activate, let go of it to clear."); } controller.getLogger().warning("Tried to store an inventory with one already present: " + (mage == null ? "?" : mage.getName())); return false; } Player player = mage.getPlayer(); if (player == null) { return false; } PlayerInventory inventory = player.getInventory(); storedInventory = CompatibilityUtils.createInventory(null, PLAYER_INVENTORY_SIZE, "Stored Inventory"); for (int i = 0; i < PLAYER_INVENTORY_SIZE; i++) { ItemStack item = inventory.getItem(i); storedInventory.setItem(i, item); if (i != heldSlot) { inventory.setItem(i, null); } } return true; } public boolean restoreInventory() { if (storedInventory == null) { return false; } Player player = mage.getPlayer(); if (player == null) { return false; } PlayerInventory inventory = player.getInventory(); for (int i = 0; i < storedInventory.getSize(); i++) { if (i != heldSlot) { inventory.setItem(i, storedInventory.getItem(i)); } } storedInventory = null; inventory.setHeldItemSlot(heldSlot); return true; } @Override @Deprecated public boolean isSoul() { return false; } public static boolean isBound(ItemStack item) { Object wandSection = InventoryUtils.getNode(item, WAND_KEY); if (wandSection == null) return false; String boundValue = InventoryUtils.getMetaString(wandSection, "owner_id"); return boundValue != null; } @Override public boolean isBound() { return bound; } @Nullable @Override public SpellTemplate getSpellTemplate(String spellKey) { SpellKey key = new SpellKey(spellKey); spellKey = key.getBaseKey(); if (!spells.contains(spellKey)) return null; Integer level = spellLevels.get(spellKey); if (level != null) { spellKey = new SpellKey(spellKey, level).getKey(); } return controller.getSpellTemplate(spellKey); } private void setSpellLevel(String spellKey, int level) { if (level <= 1) { spellLevels.remove(spellKey); } else { spellLevels.put(spellKey, level); } } @Override public int getSpellLevel(String spellKey) { Integer level = spellLevels.get(spellKey); return level == null ? 1 : level; } @Override public MageController getController() { return controller; } protected Map<String, Integer> getSpellInventory() { return new HashMap<>(spellInventory); } protected Map<String, Integer> getBrushInventory() { return new HashMap<>(brushInventory); } public Map<PotionEffectType, Integer> getPotionEffects() { return potionEffects; } @Override public float getHealthRegeneration() { Integer level = potionEffects.get(PotionEffectType.REGENERATION); return level != null && level > 0 ? (float)level : 0; } @Override public float getHungerRegeneration() { Integer level = potionEffects.get(PotionEffectType.SATURATION); return level != null && level > 0 ? (float)level : 0; } @Nullable @Override public WandTemplate getTemplate() { if (template == null || template.isEmpty()) return null; return controller.getWandTemplate(template); } public boolean playPassiveEffects(String effects) { WandTemplate wandTemplate = getTemplate(); if (wandTemplate != null && mage != null) { boolean offhandActive = mage.setOffhandActive(isInOffhand); boolean result = false; try { result = wandTemplate.playEffects(this, effects); } catch (Exception ex) { result = false; controller.getLogger().log(Level.WARNING, "Error playing effects " + effects + " from wand " + template, ex); } mage.setOffhandActive(offhandActive); return result; } return false; } @Override public boolean playEffects(String effects) { if (activeEffectsOnly && !inventoryIsOpen) { return false; } return playPassiveEffects(effects); } @Override public WandAction getDropAction() { return dropAction; } @Override public WandAction getRightClickAction() { return rightClickAction; } @Override public WandAction getLeftClickAction() { return leftClickAction; } @Override public WandAction getSwapAction() { return swapAction; } @Override public boolean performAction(WandAction action) { WandMode mode = getMode(); switch (action) { case CAST: cast(); break; case ALT_CAST: alternateCast(); break; case ALT_CAST2: alternateCast2(); break; case TOGGLE: if (mode == WandMode.CYCLE) { cycleActive(1); return true; } if (mode != WandMode.CHEST && mode != WandMode.INVENTORY && mode != WandMode.SKILLS) return false; toggleInventory(); break; case CYCLE: cycleActive(1); break; case CYCLE_REVERSE: cycleActive(-1); break; case CYCLE_HOTBAR: if (mode != WandMode.INVENTORY || !isInventoryOpen()) return false; if (getHotbarCount() > 1) { cycleHotbar(1); } else { closeInventory(); } break; case CYCLE_HOTBAR_REVERSE: if (mode != WandMode.INVENTORY) return false; if (getHotbarCount() > 1) { cycleHotbar(-1); } else if (isInventoryOpen()) { closeInventory(); } else { return false; } break; default: return false; } return true; } @Override public boolean checkAndUpgrade(boolean quiet) { WandUpgradePath path = getPath(); WandUpgradePath nextPath = path != null ? path.getUpgrade() : null; if (nextPath == null) { return true; } if (canProgress()) { return true; } if (!path.checkUpgradeRequirements(this, quiet ? null : mage)) { return false; } path.upgrade(this, mage); return true; } @Override public boolean hasUpgrade() { WandUpgradePath path = getPath(); return path != null && path.hasUpgrade(); } @Override public boolean checkUpgrade(boolean quiet) { WandUpgradePath path = getPath(); return path == null || !path.hasUpgrade() ? false : path.checkUpgradeRequirements(this, quiet ? null : mage); } @Override @Deprecated public boolean upgrade(Map<String, Object> properties) { Map<Object, Object> convertedProperties = new HashMap<Object, Object>(properties); return upgrade(ConfigurationUtils.toConfigurationSection(convertedProperties)); } @Override public boolean upgrade(boolean quiet) { WandUpgradePath path = getPath(); if (path == null) return false; path.upgrade(this, quiet ? null : mage); return true; } @Override public boolean isBlocked(double angle) { if (mage == null) return false; if (blockChance == 0) return false; if (blockFOV > 0 && angle > blockFOV) return false; long lastBlock = mage.getLastBlockTime(); if (blockCooldown > 0 && lastBlock > 0 && lastBlock + blockCooldown > System.currentTimeMillis()) return false; boolean isBlocked = Math.random() <= blockChance; if (isBlocked) { playEffects("spell_blocked"); mage.setLastBlockTime(System.currentTimeMillis()); } return isBlocked; } @Override public boolean isReflected(double angle) { if (mage == null) return false; if (blockReflectChance == 0) return false; if (blockFOV > 0 && angle > blockFOV) return false; long lastBlock = mage.getLastBlockTime(); if (blockCooldown > 0 && lastBlock > 0 && lastBlock + blockCooldown > System.currentTimeMillis()) return false; boolean isReflected = Math.random() <= blockReflectChance; if (isReflected) { playEffects("spell_reflected"); if (mage != null) mage.setLastBlockTime(System.currentTimeMillis()); } return isReflected; } @Nullable @Override public Location getLocation() { if (mage == null) { return null; } Location wandLocation = mage.getEyeLocation(); wandLocation = mage.getOffsetLocation(wandLocation, isInOffhand, castLocation == null ? DEFAULT_CAST_OFFSET : castLocation); return wandLocation; } @Nullable @Override public Mage getMage() { return mage; } @Override public @Nullable MageClass getMageClass() { return mageClass; } @Override public @Nullable String getMageClassKey() { if (mageClass != null) { return mageClass.getKey(); } return mageClassKeys == null || mageClassKeys.isEmpty() ? null : mageClassKeys.get(0); } public void setCurrentHotbar(int hotbar) { this.currentHotbar = hotbar; setProperty("hotbar", currentHotbar); } public int getInventorySize() { WandMode mode = getMode(); if (mode == WandMode.CHEST || mode == WandMode.SKILLS) { return 9 * inventoryRows; } return INVENTORY_SIZE; } public float getSPMultiplier() { return spMultiplier; } public boolean usesSP() { return hasSpellProgression && controller.isSPEnabled() && controller.isSPEarnEnabled() && spMultiplier > 0; } @Override public int getHeldSlot() { return heldSlot; } @Nullable @Override protected BaseMagicConfigurable getStorage(MagicPropertyType propertyType) { switch (propertyType) { case WAND: return this; case SUBCLASS: return mageClass; case CLASS: if (mageClass == null) { if (mage == null) { controller.getLogger().warning("Something is trying to modify a wand when it's not held, this may not work out"); } else { controller.getLogger().warning("Something is trying to modify a wand that has no class, this may not work out"); } Thread.dumpStack(); } return mageClass == null ? null : mageClass.getRoot(); case MAGE: if (mage == null) { controller.getLogger().warning("Something is trying to modify a wand when it's not held, this may not work out"); Thread.dumpStack(); } return mage == null ? null : mage.getProperties(); } return null; } @Override public boolean isPlayer() { return mage == null ? false : mage.isPlayer(); } @Nullable @Override public Player getPlayer() { return mage == null ? null : mage.getPlayer(); } @Override @Nonnull public WandEffectContext getEffectContext() { if (effectContext == null || (effectContext.getMage() != mage)) { // Lazy load or mage has changed effectContext = new WandEffectContext(mage, this); } return verifyNotNull(effectContext); } @Override public Wand getWand() { return this; } }
Remove unused variable
Magic/src/main/java/com/elmakers/mine/bukkit/wand/Wand.java
Remove unused variable
<ide><path>agic/src/main/java/com/elmakers/mine/bukkit/wand/Wand.java <ide> <ide> // Look for existing spells for spell upgrades <ide> Integer inventorySlot = spellInventory.get(spellKey.getBaseKey()); <del> SpellTemplate currentSpell = getBaseSpell(spellKey); <ide> clearSlot(inventorySlot); <ide> <ide> setSpellLevel(spellKey.getBaseKey(), level);
Java
apache-2.0
4e884f3c19ffa2e5e19c42a9dd9b7256e1b715ae
0
apache/qpid-jms,gemmellr/qpid-jms,gemmellr/qpid-jms,avranju/qpid-jms,tabish121/qpid-jms,tabish121/qpid-jms,andrew-buckley/qpid-jms,apache/qpid-jms,andrew-buckley/qpid-jms,avranju/qpid-jms
/** * 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.qpid.jms.provider.failover; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import javax.jms.JMSException; import org.apache.qpid.jms.message.JmsInboundMessageDispatch; import org.apache.qpid.jms.message.JmsMessageFactory; import org.apache.qpid.jms.message.JmsOutboundMessageDispatch; import org.apache.qpid.jms.meta.JmsConnectionInfo; import org.apache.qpid.jms.meta.JmsConsumerId; import org.apache.qpid.jms.meta.JmsResource; import org.apache.qpid.jms.meta.JmsSessionId; import org.apache.qpid.jms.provider.AsyncResult; import org.apache.qpid.jms.provider.DefaultProviderListener; import org.apache.qpid.jms.provider.Provider; import org.apache.qpid.jms.provider.ProviderConstants.ACK_TYPE; import org.apache.qpid.jms.provider.ProviderFactory; import org.apache.qpid.jms.provider.ProviderFuture; import org.apache.qpid.jms.provider.ProviderListener; import org.apache.qpid.jms.util.IOExceptionSupport; import org.apache.qpid.jms.util.ThreadPoolUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A Provider Facade that provides services for detection dropped Provider connections * and attempting to reconnect to a different remote peer. Upon establishment of a new * connection the FailoverProvider will initiate state recovery of the active JMS * framework resources. */ public class FailoverProvider extends DefaultProviderListener implements Provider { private static final Logger LOG = LoggerFactory.getLogger(FailoverProvider.class); private static final int UNLIMITED = -1; private ProviderListener listener; private Provider provider; private final FailoverUriPool uris; private final ExecutorService serializer; private final ScheduledExecutorService connectionHub; private final AtomicBoolean closed = new AtomicBoolean(); private final AtomicBoolean failed = new AtomicBoolean(); private final AtomicLong requestId = new AtomicLong(); private final Map<Long, FailoverRequest> requests = new LinkedHashMap<Long, FailoverRequest>(); private final DefaultProviderListener closedListener = new DefaultProviderListener(); private final AtomicReference<JmsMessageFactory> messageFactory = new AtomicReference<JmsMessageFactory>(); // Current state of connection / reconnection private boolean firstConnection = true; private long reconnectAttempts; private long reconnectDelay = TimeUnit.SECONDS.toMillis(5); private IOException failureCause; private URI connectedURI; // Timeout values configured via JmsConnectionInfo private long connectTimeout = JmsConnectionInfo.DEFAULT_CONNECT_TIMEOUT; private long closeTimeout = JmsConnectionInfo.DEFAULT_CLOSE_TIMEOUT; private long sendTimeout = JmsConnectionInfo.DEFAULT_SEND_TIMEOUT; private long requestTimeout = JmsConnectionInfo.DEFAULT_REQUEST_TIMEOUT; // Configuration values. private long initialReconnectDelay = 0L; private long maxReconnectDelay = TimeUnit.SECONDS.toMillis(30); private boolean useExponentialBackOff = true; private double backOffMultiplier = 2d; private int maxReconnectAttempts = UNLIMITED; private int startupMaxReconnectAttempts = UNLIMITED; private int warnAfterReconnectAttempts = 10; public FailoverProvider(Map<String, String> nestedOptions) { this(null, nestedOptions); } public FailoverProvider(URI[] uris) { this(uris, null); } public FailoverProvider(URI[] uris, Map<String, String> nestedOptions) { this.uris = new FailoverUriPool(uris, nestedOptions); this.serializer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable runner) { Thread serial = new Thread(runner); serial.setDaemon(true); serial.setName("FailoverProvider: serialization thread"); return serial; } }); // All Connection attempts happen in this schedulers thread. Once a connection // is established it will hand the open connection back to the serializer thread // for state recovery. this.connectionHub = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable runner) { Thread serial = new Thread(runner); serial.setDaemon(true); serial.setName("FailoverProvider: connect thread"); return serial; } }); } @Override public void connect() throws IOException { checkClosed(); LOG.debug("Initiating initial connection attempt task"); triggerReconnectionAttempt(); } @Override public void start() throws IOException, IllegalStateException { checkClosed(); if (listener == null) { throw new IllegalStateException("No ProviderListener registered."); } } @Override public void close() { if (closed.compareAndSet(false, true)) { final ProviderFuture request = new ProviderFuture(); serializer.execute(new Runnable() { @Override public void run() { try { IOException error = failureCause != null ? failureCause : new IOException("Connection closed"); List<FailoverRequest> pending = new ArrayList<FailoverRequest>(requests.values()); for (FailoverRequest request : pending) { request.onFailure(error); } if (provider != null) { provider.close(); } } catch (Exception e) { LOG.debug("Caught exception while closing connection"); } finally { ThreadPoolUtils.shutdownGraceful(connectionHub); if (serializer != null) { serializer.shutdown(); } request.onSuccess(); } } }); try { if (this.closeTimeout < 0) { request.sync(); } else { request.sync(closeTimeout, TimeUnit.MILLISECONDS); } } catch (IOException e) { LOG.warn("Error caught while closing Provider: ", e.getMessage()); } } } @Override public void create(final JmsResource resource, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); FailoverRequest pending = null; if (resource instanceof JmsConnectionInfo) { pending = new CreateConnectionRequest(request) { @Override public void doTask() throws Exception { if (resource instanceof JmsConnectionInfo) { JmsConnectionInfo connectionInfo = (JmsConnectionInfo) resource; connectTimeout = connectionInfo.getConnectTimeout(); closeTimeout = connectionInfo.getCloseTimeout(); sendTimeout = connectionInfo.getSendTimeout(); requestTimeout = connectionInfo.getRequestTimeout(); } provider.create(resource, this); } }; } else { pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.create(resource, this); } }; } serializer.execute(pending); } @Override public void start(final JmsResource resource, final AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.start(resource, this); } }; serializer.execute(pending); } @Override public void stop(final JmsResource resource, final AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.stop(resource, this); } }; serializer.execute(pending); } @Override public void destroy(final JmsResource resourceId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws IOException, JMSException, UnsupportedOperationException { provider.destroy(resourceId, this); } @Override public boolean succeedsWhenOffline() { // Allow this to succeed, resource won't get recreated on reconnect. return true; } }; serializer.execute(pending); } @Override public void send(final JmsOutboundMessageDispatch envelope, AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.send(envelope, this); } }; serializer.execute(pending); } @Override public void acknowledge(final JmsSessionId sessionId, AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.acknowledge(sessionId, this); } @Override public boolean succeedsWhenOffline() { // Allow this to succeed, acks would be stale. return true; } }; serializer.execute(pending); } @Override public void acknowledge(final JmsInboundMessageDispatch envelope, final ACK_TYPE ackType, AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.acknowledge(envelope, ackType, this); } @Override public boolean succeedsWhenOffline() { // Allow this to succeed, acks would be stale. return true; } }; serializer.execute(pending); } @Override public void commit(final JmsSessionId sessionId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.commit(sessionId, this); } @Override public boolean failureWhenOffline() { return true; } }; serializer.execute(pending); } @Override public void rollback(final JmsSessionId sessionId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.rollback(sessionId, this); } @Override public boolean failureWhenOffline() { return true; } }; serializer.execute(pending); } @Override public void recover(final JmsSessionId sessionId, final AsyncResult request) throws IOException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.recover(sessionId, this); } @Override public boolean succeedsWhenOffline() { return true; } }; serializer.execute(pending); } @Override public void unsubscribe(final String subscription, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.unsubscribe(subscription, this); } }; serializer.execute(pending); } @Override public void pull(final JmsConsumerId consumerId, final long timeout, final AsyncResult request) throws IOException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.pull(consumerId, timeout, this); } }; serializer.execute(pending); } @Override public JmsMessageFactory getMessageFactory() { return messageFactory.get(); } //--------------- Connection Error and Recovery methods ------------------// /** * This method is always called from within the FailoverProvider's serialization thread. * * When a failure is encountered either from an outgoing request or from an error fired * from the underlying Provider instance this method is called to determine if a reconnect * is allowed and if so a new reconnect cycle is triggered on the connection thread. * * @param cause * the error that triggered the failure of the provider. */ private void handleProviderFailure(final IOException cause) { LOG.debug("handling Provider failure: {}", cause.getMessage()); LOG.trace("stack", cause); this.provider.setProviderListener(closedListener); URI failedURI = this.provider.getRemoteURI(); try { this.provider.close(); } catch (Throwable error) { LOG.trace("Caught exception while closing failed provider: {}", error.getMessage()); } this.provider = null; if (reconnectAllowed()) { ProviderListener listener = this.listener; if (listener != null) { listener.onConnectionInterrupted(failedURI); } triggerReconnectionAttempt(); } else { ProviderListener listener = this.listener; if (listener != null) { listener.onConnectionFailure(cause); } } } /** * Called from the reconnection thread. This method enqueues a new task that * will attempt to recover connection state, once successful, normal operations * will resume. If an error occurs while attempting to recover the JMS framework * state then a reconnect cycle is again triggered on the connection thread. * * @param provider * The newly connect Provider instance that will become active. */ private void initializeNewConnection(final Provider provider) { this.serializer.execute(new Runnable() { @Override public void run() { try { if (firstConnection) { FailoverProvider.this.provider = provider; provider.setProviderListener(FailoverProvider.this); // The only pending request here should be a Connection create request. List<FailoverRequest> pending = new ArrayList<FailoverRequest>(requests.values()); for (FailoverRequest request : pending) { request.run(); } } else { LOG.debug("Signalling connection recovery: {}", provider); FailoverProvider.this.provider = provider; provider.setProviderListener(FailoverProvider.this); // Stage 1: Recovery all JMS Framework resources listener.onConnectionRecovery(provider); // Stage 2: Connection state recovered, get newly configured message factory. FailoverProvider.this.messageFactory.set(provider.getMessageFactory()); // Stage 3: Restart consumers, send pull commands, etc. listener.onConnectionRecovered(provider); // Stage 4: Let the client know that connection has restored. listener.onConnectionRestored(provider.getRemoteURI()); // Stage 5: Send pending actions. List<FailoverRequest> pending = new ArrayList<FailoverRequest>(requests.values()); for (FailoverRequest request : pending) { request.run(); } reconnectDelay = initialReconnectDelay; reconnectAttempts = 0; connectedURI = provider.getRemoteURI(); uris.connected(); } } catch (Throwable error) { handleProviderFailure(IOExceptionSupport.create(error)); } } }); } /** * Called when the Provider was either first created or when a connection failure has * been reported. A reconnection attempt is immediately executed on the connection * thread. If a new Provider is able to be created and connected then a recovery task * is scheduled on the main serializer thread. If the connect attempt fails another * attempt is scheduled based on the configured delay settings until a max attempts * limit is hit, if one is set. * * Since the initialize is put on the serializer thread this thread stops and does * not queue another connect task. This allows for the reconnect delay to be reset * and a failure to initialize a new connection restarts the connect process from the * point of view that connection was lost and an immediate attempt cycle should start. */ private void triggerReconnectionAttempt() { if (closed.get() || failed.get()) { return; } connectionHub.execute(new Runnable() { @Override public void run() { if (provider != null || closed.get() || failed.get()) { return; } int reconnectLimit = reconnectAttemptLimit(); if (reconnectLimit != UNLIMITED && reconnectAttempts >= reconnectLimit) { return; } reconnectAttempts++; Throwable failure = null; URI target = uris.getNext(); if (target != null) { try { LOG.debug("Connection attempt:[{}] to: {} in-progress", reconnectAttempts, target); Provider provider = ProviderFactory.create(target); provider.connect(); initializeNewConnection(provider); return; } catch (Throwable e) { LOG.info("Connection attempt:[{}] to: {} failed", reconnectAttempts, target); failure = e; } } if (reconnectLimit != UNLIMITED && reconnectAttempts >= reconnectLimit) { LOG.error("Failed to connect after: " + reconnectAttempts + " attempt(s)"); failed.set(true); failureCause = IOExceptionSupport.create(failure); if (listener != null) { listener.onConnectionFailure(failureCause); }; return; } int warnInterval = getWarnAfterReconnectAttempts(); if (warnInterval > 0 && (reconnectAttempts % warnInterval) == 0) { LOG.warn("Failed to connect after: {} attempt(s) continuing to retry.", reconnectAttempts); } long delay = nextReconnectDelay(); LOG.trace("Next reconnect attempt will be in {} milliseconds", delay); connectionHub.schedule(this, delay, TimeUnit.MILLISECONDS); } }); } private boolean reconnectAllowed() { return reconnectAttemptLimit() != 0; } private int reconnectAttemptLimit() { int maxReconnectValue = this.maxReconnectAttempts; if (firstConnection && this.startupMaxReconnectAttempts != UNLIMITED) { maxReconnectValue = this.startupMaxReconnectAttempts; } return maxReconnectValue; } private long nextReconnectDelay() { if (useExponentialBackOff) { // Exponential increment of reconnect delay. reconnectDelay *= backOffMultiplier; if (reconnectDelay > maxReconnectDelay) { reconnectDelay = maxReconnectDelay; } } return reconnectDelay; } protected void checkClosed() throws IOException { if (closed.get()) { throw new IOException("The Provider is already closed"); } } //--------------- DefaultProviderListener overrides ----------------------// @Override public void onInboundMessage(final JmsInboundMessageDispatch envelope) { if (closed.get() || failed.get()) { return; } serializer.execute(new Runnable() { @Override public void run() { if (!closed.get()) { listener.onInboundMessage(envelope); } } }); } @Override public void onConnectionFailure(final IOException ex) { if (closed.get() || failed.get()) { return; } serializer.execute(new Runnable() { @Override public void run() { if (!closed.get() && !failed.get()) { LOG.debug("Failover: the provider reports failure: {}", ex.getMessage()); handleProviderFailure(ex); } } }); } //--------------- URI update and rebalance methods -----------------------// public void add(final URI uri) { serializer.execute(new Runnable() { @Override public void run() { uris.add(uri); } }); } public void remove(final URI uri) { serializer.execute(new Runnable() { @Override public void run() { uris.remove(uri); } }); } //--------------- Property Getters and Setters ---------------------------// @Override public URI getRemoteURI() { Provider provider = this.provider; if (provider != null) { return provider.getRemoteURI(); } return null; } @Override public void setProviderListener(ProviderListener listener) { this.listener = listener; } @Override public ProviderListener getProviderListener() { return listener; } public boolean isRandomize() { return uris.isRandomize(); } public void setRandomize(boolean value) { this.uris.setRandomize(value); } public long getInitialReconnectDealy() { return initialReconnectDelay; } public void setInitialReconnectDealy(long initialReconnectDealy) { this.initialReconnectDelay = initialReconnectDealy; } public long getMaxReconnectDelay() { return maxReconnectDelay; } public void setMaxReconnectDelay(long maxReconnectDelay) { this.maxReconnectDelay = maxReconnectDelay; } public int getMaxReconnectAttempts() { return maxReconnectAttempts; } public void setMaxReconnectAttempts(int maxReconnectAttempts) { this.maxReconnectAttempts = maxReconnectAttempts; } public int getStartupMaxReconnectAttempts() { return startupMaxReconnectAttempts; } public void setStartupMaxReconnectAttempts(int startupMaxReconnectAttempts) { this.startupMaxReconnectAttempts = startupMaxReconnectAttempts; } /** * Gets the current setting controlling how many Connect / Reconnect attempts must occur * before a warn message is logged. A value of {@code <= 0} indicates that there will be * no warn message logged regardless of how many reconnect attempts occur. * * @return the current number of connection attempts before warn logging is triggered. */ public int getWarnAfterReconnectAttempts() { return warnAfterReconnectAttempts; } /** * Sets the number of Connect / Reconnect attempts that must occur before a warn message * is logged indicating that the transport is not connected. This can be useful when the * client is running inside some container or service as it gives an indication of some * problem with the client connection that might not otherwise be visible. To disable the * log messages this value should be set to a value @{code attempts <= 0} * * @param warnAfterReconnectAttempts * The number of failed connection attempts that must happen before a warning is logged. */ public void setWarnAfterReconnectAttempts(int warnAfterReconnectAttempts) { this.warnAfterReconnectAttempts = warnAfterReconnectAttempts; } public double getReconnectDelayExponent() { return backOffMultiplier; } public void setReconnectDelayExponent(double reconnectDelayExponent) { this.backOffMultiplier = reconnectDelayExponent; } public boolean isUseExponentialBackOff() { return useExponentialBackOff; } public void setUseExponentialBackOff(boolean useExponentialBackOff) { this.useExponentialBackOff = useExponentialBackOff; } public long getConnectTimeout() { return this.connectTimeout; } public long getCloseTimeout() { return this.closeTimeout; } public long getSendTimeout() { return this.sendTimeout; } public long getRequestTimeout() { return this.requestTimeout; } @Override public String toString() { return "FailoverProvider: " + (connectedURI == null ? "unconnected" : connectedURI.toString()); } //--------------- FailoverProvider Asynchronous Request --------------------// /** * For all requests that are dispatched from the FailoverProvider to a connected * Provider instance an instance of FailoverRequest is used to handle errors that * occur during processing of that request and trigger a reconnect. */ protected abstract class FailoverRequest extends ProviderFuture implements Runnable { private final long id = requestId.incrementAndGet(); public FailoverRequest(AsyncResult watcher) { super(watcher); } @Override public void run() { requests.put(id, this); if (provider == null) { if (failureWhenOffline()) { requests.remove(id); getWrappedRequest().onFailure(new IOException("Provider disconnected")); } else if (succeedsWhenOffline()) { onSuccess(); } } else { try { LOG.debug("Executing Failover Task: {}", this); doTask(); } catch (UnsupportedOperationException e) { requests.remove(id); getWrappedRequest().onFailure(e); } catch (JMSException jmsEx) { //TODO: should we remove the request as above? getWrappedRequest().onFailure(jmsEx); } catch (Throwable e) { LOG.debug("Caught exception while executing task: {}", e.getMessage()); triggerReconnectionAttempt(); } } } @Override public void onFailure(final Throwable result) { if (closed.get() || failed.get()) { requests.remove(id); super.onFailure(result); } else { LOG.debug("Request received error: {}", result.getMessage()); serializer.execute(new Runnable() { @Override public void run() { handleProviderFailure(IOExceptionSupport.create(result)); } }); } } @Override public void onSuccess() { requests.remove(id); super.onSuccess(); } /** * Called to execute the specific task that was requested. * * @throws Exception if an error occurs during task execution. */ public abstract void doTask() throws Exception; /** * Should the request just succeed when the Provider is not connected. * * @return true if the request is marked as successful when not connected. */ public boolean succeedsWhenOffline() { return false; } /** * When the transport is not connected should this request automatically fail. * * @return true if the task should fail when the Provider is not connected. */ public boolean failureWhenOffline() { return false; } } /** * Captures the initial request to create a JmsConnectionInfo based resources and ensures * that if the connection is successfully established that the connection established event * is triggered once before moving on to sending only connection interrupted and restored * events. */ protected abstract class CreateConnectionRequest extends FailoverRequest { /** * @param watcher */ public CreateConnectionRequest(AsyncResult watcher) { super(watcher); } @Override public void onSuccess() { serializer.execute(new Runnable() { @Override public void run() { if (firstConnection) { LOG.trace("First connection requst has completed:"); FailoverProvider.this.messageFactory.set(provider.getMessageFactory()); listener.onConnectionEstablished(provider.getRemoteURI()); firstConnection = false; } else { LOG.warn("A second call to a CreateConnectionRequest not expected."); } CreateConnectionRequest.this.signalConnected(); } }); } public void signalConnected() { super.onSuccess(); } } }
qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProvider.java
/** * 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.qpid.jms.provider.failover; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import javax.jms.JMSException; import org.apache.qpid.jms.message.JmsInboundMessageDispatch; import org.apache.qpid.jms.message.JmsMessageFactory; import org.apache.qpid.jms.message.JmsOutboundMessageDispatch; import org.apache.qpid.jms.meta.JmsConnectionInfo; import org.apache.qpid.jms.meta.JmsConsumerId; import org.apache.qpid.jms.meta.JmsResource; import org.apache.qpid.jms.meta.JmsSessionId; import org.apache.qpid.jms.provider.AsyncResult; import org.apache.qpid.jms.provider.DefaultProviderListener; import org.apache.qpid.jms.provider.Provider; import org.apache.qpid.jms.provider.ProviderConstants.ACK_TYPE; import org.apache.qpid.jms.provider.ProviderFactory; import org.apache.qpid.jms.provider.ProviderFuture; import org.apache.qpid.jms.provider.ProviderListener; import org.apache.qpid.jms.util.IOExceptionSupport; import org.apache.qpid.jms.util.ThreadPoolUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A Provider Facade that provides services for detection dropped Provider connections * and attempting to reconnect to a different remote peer. Upon establishment of a new * connection the FailoverProvider will initiate state recovery of the active JMS * framework resources. */ public class FailoverProvider extends DefaultProviderListener implements Provider { private static final Logger LOG = LoggerFactory.getLogger(FailoverProvider.class); private static final int UNLIMITED = -1; private ProviderListener listener; private Provider provider; private final FailoverUriPool uris; private final ExecutorService serializer; private final ScheduledExecutorService connectionHub; private final AtomicBoolean closed = new AtomicBoolean(); private final AtomicBoolean failed = new AtomicBoolean(); private final AtomicLong requestId = new AtomicLong(); private final Map<Long, FailoverRequest> requests = new LinkedHashMap<Long, FailoverRequest>(); private final DefaultProviderListener closedListener = new DefaultProviderListener(); private final AtomicReference<JmsMessageFactory> messageFactory = new AtomicReference<JmsMessageFactory>(); // Current state of connection / reconnection private boolean firstConnection = true; private long reconnectAttempts; private long reconnectDelay = TimeUnit.SECONDS.toMillis(5); private IOException failureCause; private URI connectedURI; // Timeout values configured via JmsConnectionInfo private long connectTimeout = JmsConnectionInfo.DEFAULT_CONNECT_TIMEOUT; private long closeTimeout = JmsConnectionInfo.DEFAULT_CLOSE_TIMEOUT; private long sendTimeout = JmsConnectionInfo.DEFAULT_SEND_TIMEOUT; private long requestTimeout = JmsConnectionInfo.DEFAULT_REQUEST_TIMEOUT; // Configuration values. private long initialReconnectDelay = 0L; private long maxReconnectDelay = TimeUnit.SECONDS.toMillis(30); private boolean useExponentialBackOff = true; private double backOffMultiplier = 2d; private int maxReconnectAttempts = UNLIMITED; private int startupMaxReconnectAttempts = UNLIMITED; private int warnAfterReconnectAttempts = 10; public FailoverProvider(Map<String, String> nestedOptions) { this(null, nestedOptions); } public FailoverProvider(URI[] uris) { this(uris, null); } public FailoverProvider(URI[] uris, Map<String, String> nestedOptions) { this.uris = new FailoverUriPool(uris, nestedOptions); this.serializer = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() { @Override public Thread newThread(Runnable runner) { Thread serial = new Thread(runner); serial.setDaemon(true); serial.setName("FailoverProvider: serialization thread"); return serial; } }); // All Connection attempts happen in this schedulers thread. Once a connection // is established it will hand the open connection back to the serializer thread // for state recovery. this.connectionHub = Executors.newScheduledThreadPool(1, new ThreadFactory() { @Override public Thread newThread(Runnable runner) { Thread serial = new Thread(runner); serial.setDaemon(true); serial.setName("FailoverProvider: connect thread"); return serial; } }); } @Override public void connect() throws IOException { checkClosed(); LOG.debug("Initiating initial connection attempt task"); triggerReconnectionAttempt(); } @Override public void start() throws IOException, IllegalStateException { checkClosed(); if (listener == null) { throw new IllegalStateException("No ProviderListener registered."); } } @Override public void close() { if (closed.compareAndSet(false, true)) { final ProviderFuture request = new ProviderFuture(); serializer.execute(new Runnable() { @Override public void run() { try { IOException error = failureCause != null ? failureCause : new IOException("Connection closed"); List<FailoverRequest> pending = new ArrayList<FailoverRequest>(requests.values()); for (FailoverRequest request : pending) { request.onFailure(error); } if (provider != null) { provider.close(); } } catch (Exception e) { LOG.debug("Caught exception while closing connection"); } finally { ThreadPoolUtils.shutdownGraceful(connectionHub); if (serializer != null) { serializer.shutdown(); } request.onSuccess(); } } }); try { if (this.closeTimeout < 0) { request.sync(); } else { request.sync(closeTimeout, TimeUnit.MILLISECONDS); } } catch (IOException e) { LOG.warn("Error caught while closing Provider: ", e.getMessage()); } } } @Override public void create(final JmsResource resource, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); FailoverRequest pending = null; if (resource instanceof JmsConnectionInfo) { pending = new CreateConnectionRequest(request) { @Override public void doTask() throws Exception { if (resource instanceof JmsConnectionInfo) { JmsConnectionInfo connectionInfo = (JmsConnectionInfo) resource; connectTimeout = connectionInfo.getConnectTimeout(); closeTimeout = connectionInfo.getCloseTimeout(); sendTimeout = connectionInfo.getSendTimeout(); requestTimeout = connectionInfo.getRequestTimeout(); } provider.create(resource, this); } }; } else { pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.create(resource, this); } }; } serializer.execute(pending); } @Override public void start(final JmsResource resource, final AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.start(resource, this); } }; serializer.execute(pending); } @Override public void stop(final JmsResource resource, final AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.stop(resource, this); } }; serializer.execute(pending); } @Override public void destroy(final JmsResource resourceId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws IOException, JMSException, UnsupportedOperationException { provider.destroy(resourceId, this); } @Override public boolean succeedsWhenOffline() { // Allow this to succeed, resource won't get recreated on reconnect. return true; } }; serializer.execute(pending); } @Override public void send(final JmsOutboundMessageDispatch envelope, AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.send(envelope, this); } }; serializer.execute(pending); } @Override public void acknowledge(final JmsSessionId sessionId, AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.acknowledge(sessionId, this); } @Override public boolean succeedsWhenOffline() { // Allow this to succeed, acks would be stale. return true; } }; serializer.execute(pending); } @Override public void acknowledge(final JmsInboundMessageDispatch envelope, final ACK_TYPE ackType, AsyncResult request) throws IOException, JMSException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.acknowledge(envelope, ackType, this); } @Override public boolean succeedsWhenOffline() { // Allow this to succeed, acks would be stale. return true; } }; serializer.execute(pending); } @Override public void commit(final JmsSessionId sessionId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.commit(sessionId, this); } @Override public boolean failureWhenOffline() { return true; } }; serializer.execute(pending); } @Override public void rollback(final JmsSessionId sessionId, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.rollback(sessionId, this); } @Override public boolean failureWhenOffline() { return true; } }; serializer.execute(pending); } @Override public void recover(final JmsSessionId sessionId, final AsyncResult request) throws IOException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.recover(sessionId, this); } @Override public boolean succeedsWhenOffline() { return true; } }; serializer.execute(pending); } @Override public void unsubscribe(final String subscription, AsyncResult request) throws IOException, JMSException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.unsubscribe(subscription, this); } }; serializer.execute(pending); } @Override public void pull(final JmsConsumerId consumerId, final long timeout, final AsyncResult request) throws IOException, UnsupportedOperationException { checkClosed(); final FailoverRequest pending = new FailoverRequest(request) { @Override public void doTask() throws Exception { provider.pull(consumerId, timeout, this); } }; serializer.execute(pending); } @Override public JmsMessageFactory getMessageFactory() { return messageFactory.get(); } //--------------- Connection Error and Recovery methods ------------------// /** * This method is always called from within the FailoverProvider's serialization thread. * * When a failure is encountered either from an outgoing request or from an error fired * from the underlying Provider instance this method is called to determine if a reconnect * is allowed and if so a new reconnect cycle is triggered on the connection thread. * * @param cause * the error that triggered the failure of the provider. */ private void handleProviderFailure(final IOException cause) { LOG.debug("handling Provider failure: {}", cause.getMessage()); LOG.trace("stack", cause); this.provider.setProviderListener(closedListener); URI failedURI = this.provider.getRemoteURI(); try { this.provider.close(); } catch (Throwable error) { LOG.trace("Caught exception while closing failed provider: {}", error.getMessage()); } this.provider = null; if (reconnectAllowed()) { ProviderListener listener = this.listener; if (listener != null) { listener.onConnectionInterrupted(failedURI); } triggerReconnectionAttempt(); } else { ProviderListener listener = this.listener; if (listener != null) { listener.onConnectionFailure(cause); } } } /** * Called from the reconnection thread. This method enqueues a new task that * will attempt to recover connection state, once successful, normal operations * will resume. If an error occurs while attempting to recover the JMS framework * state then a reconnect cycle is again triggered on the connection thread. * * @param provider * The newly connect Provider instance that will become active. */ private void initializeNewConnection(final Provider provider) { this.serializer.execute(new Runnable() { @Override public void run() { try { if (firstConnection) { FailoverProvider.this.provider = provider; provider.setProviderListener(FailoverProvider.this); // The only pending request here should be a Connection create request. List<FailoverRequest> pending = new ArrayList<FailoverRequest>(requests.values()); for (FailoverRequest request : pending) { request.run(); } } else { LOG.debug("Signalling connection recovery: {}", provider); FailoverProvider.this.provider = provider; provider.setProviderListener(FailoverProvider.this); // Stage 1: Recovery all JMS Framework resources listener.onConnectionRecovery(provider); // Stage 2: Connection state recovered, get newly configured message factory. FailoverProvider.this.messageFactory.set(provider.getMessageFactory()); // Stage 3: Restart consumers, send pull commands, etc. listener.onConnectionRecovered(provider); // Stage 4: Let the client know that connection has restored. listener.onConnectionRestored(provider.getRemoteURI()); // Stage 5: Send pending actions. List<FailoverRequest> pending = new ArrayList<FailoverRequest>(requests.values()); for (FailoverRequest request : pending) { request.run(); } reconnectDelay = initialReconnectDelay; reconnectAttempts = 0; connectedURI = provider.getRemoteURI(); uris.connected(); } } catch (Throwable error) { handleProviderFailure(IOExceptionSupport.create(error)); } } }); } /** * Called when the Provider was either first created or when a connection failure has * been reported. A reconnection attempt is immediately executed on the connection * thread. If a new Provider is able to be created and connected then a recovery task * is scheduled on the main serializer thread. If the connect attempt fails another * attempt is scheduled based on the configured delay settings until a max attempts * limit is hit, if one is set. * * Since the initialize is put on the serializer thread this thread stops and does * not queue another connect task. This allows for the reconnect delay to be reset * and a failure to initialize a new connection restarts the connect process from the * point of view that connection was lost and an immediate attempt cycle should start. */ private void triggerReconnectionAttempt() { if (closed.get() || failed.get()) { return; } connectionHub.execute(new Runnable() { @Override public void run() { if (provider != null || closed.get() || failed.get()) { return; } int reconnectLimit = reconnectAttemptLimit(); if (reconnectLimit != UNLIMITED && reconnectAttempts >= reconnectLimit) { return; } reconnectAttempts++; Throwable failure = null; URI target = uris.getNext(); if (target != null) { try { LOG.debug("Connection attempt:[{}] to: {} in-progress", reconnectAttempts, target); Provider provider = ProviderFactory.create(target); provider.connect(); initializeNewConnection(provider); return; } catch (Throwable e) { LOG.info("Connection attempt:[{}] to: {} failed", reconnectAttempts, target); failure = e; } } if (reconnectLimit != UNLIMITED && reconnectAttempts >= reconnectLimit) { LOG.error("Failed to connect after: " + reconnectAttempts + " attempt(s)"); failed.set(true); failureCause = IOExceptionSupport.create(failure); if (listener != null) { listener.onConnectionFailure(failureCause); }; return; } int warnInterval = getWarnAfterReconnectAttempts(); if (warnInterval > 0 && (reconnectAttempts % warnInterval) == 0) { LOG.warn("Failed to connect after: {} attempt(s) continuing to retry.", reconnectAttempts); } long delay = nextReconnectDelay(); LOG.trace("Next reconnect attempt will be in {} milliseconds", delay); connectionHub.schedule(this, delay, TimeUnit.MILLISECONDS); } }); } private boolean reconnectAllowed() { return reconnectAttemptLimit() != 0; } private int reconnectAttemptLimit() { int maxReconnectValue = this.maxReconnectAttempts; if (firstConnection && this.startupMaxReconnectAttempts != UNLIMITED) { maxReconnectValue = this.startupMaxReconnectAttempts; } return maxReconnectValue; } private long nextReconnectDelay() { if (useExponentialBackOff) { // Exponential increment of reconnect delay. reconnectDelay *= backOffMultiplier; if (reconnectDelay > maxReconnectDelay) { reconnectDelay = maxReconnectDelay; } } return reconnectDelay; } protected void checkClosed() throws IOException { if (closed.get()) { throw new IOException("The Provider is already closed"); } } //--------------- DefaultProviderListener overrides ----------------------// @Override public void onInboundMessage(final JmsInboundMessageDispatch envelope) { if (closed.get() || failed.get()) { return; } serializer.execute(new Runnable() { @Override public void run() { if (!closed.get()) { listener.onInboundMessage(envelope); } } }); } @Override public void onConnectionFailure(final IOException ex) { if (closed.get() || failed.get()) { return; } serializer.execute(new Runnable() { @Override public void run() { if (!closed.get() && !failed.get()) { LOG.debug("Failover: the provider reports failure: {}", ex.getMessage()); handleProviderFailure(ex); } } }); } //--------------- URI update and rebalance methods -----------------------// public void add(final URI uri) { serializer.execute(new Runnable() { @Override public void run() { uris.add(uri); } }); } public void remove(final URI uri) { serializer.execute(new Runnable() { @Override public void run() { uris.remove(uri); } }); } //--------------- Property Getters and Setters ---------------------------// @Override public URI getRemoteURI() { Provider provider = this.provider; if (provider != null) { return provider.getRemoteURI(); } return null; } @Override public void setProviderListener(ProviderListener listener) { this.listener = listener; } @Override public ProviderListener getProviderListener() { return listener; } public boolean isRandomize() { return uris.isRandomize(); } public void setRandomize(boolean value) { this.uris.setRandomize(value); } public long getInitialReconnectDealy() { return initialReconnectDelay; } public void setInitialReconnectDealy(long initialReconnectDealy) { this.initialReconnectDelay = initialReconnectDealy; } public long getMaxReconnectDelay() { return maxReconnectDelay; } public void setMaxReconnectDelay(long maxReconnectDelay) { this.maxReconnectDelay = maxReconnectDelay; } public int getMaxReconnectAttempts() { return maxReconnectAttempts; } public void setMaxReconnectAttempts(int maxReconnectAttempts) { this.maxReconnectAttempts = maxReconnectAttempts; } public int getStartupMaxReconnectAttempts() { return startupMaxReconnectAttempts; } public void setStartupMaxReconnectAttempts(int startupMaxReconnectAttempts) { this.startupMaxReconnectAttempts = startupMaxReconnectAttempts; } /** * Gets the current setting controlling how many Connect / Reconnect attempts must occur * before a warn message is logged. A value of {@code <= 0} indicates that there will be * no warn message logged regardless of how many reconnect attempts occur. * * @return the current number of connection attempts before warn logging is triggered. */ public int getWarnAfterReconnectAttempts() { return warnAfterReconnectAttempts; } /** * Sets the number of Connect / Reconnect attempts that must occur before a warn message * is logged indicating that the transport is not connected. This can be useful when the * client is running inside some container or service as it gives an indication of some * problem with the client connection that might not otherwise be visible. To disable the * log messages this value should be set to a value @{code attempts <= 0} * * @param warnAfterReconnectAttempts * The number of failed connection attempts that must happen before a warning is logged. */ public void setWarnAfterReconnectAttempts(int warnAfterReconnectAttempts) { this.warnAfterReconnectAttempts = warnAfterReconnectAttempts; } public double getReconnectDelayExponent() { return backOffMultiplier; } public void setReconnectDelayExponent(double reconnectDelayExponent) { this.backOffMultiplier = reconnectDelayExponent; } public boolean isUseExponentialBackOff() { return useExponentialBackOff; } public void setUseExponentialBackOff(boolean useExponentialBackOff) { this.useExponentialBackOff = useExponentialBackOff; } public long getConnectTimeout() { return this.connectTimeout; } public long getCloseTimeout() { return this.closeTimeout; } public long getSendTimeout() { return this.sendTimeout; } public long getRequestTimeout() { return this.requestTimeout; } @Override public String toString() { return "FailoverProvider: " + (connectedURI == null ? "unconnected" : connectedURI.toString()); } //--------------- FailoverProvider Asynchronous Request --------------------// /** * For all requests that are dispatched from the FailoverProvider to a connected * Provider instance an instance of FailoverRequest is used to handle errors that * occur during processing of that request and trigger a reconnect. */ protected abstract class FailoverRequest extends ProviderFuture implements Runnable { private final long id = requestId.incrementAndGet(); public FailoverRequest(AsyncResult watcher) { super(watcher); } @Override public void run() { requests.put(id, this); if (provider == null) { if (failureWhenOffline()) { requests.remove(id); getWrappedRequest().onFailure(new IOException("Provider disconnected")); } else if (succeedsWhenOffline()) { onSuccess(); } } else { try { LOG.debug("Executing Failover Task: {}", this); doTask(); } catch (UnsupportedOperationException e) { requests.remove(id); getWrappedRequest().onFailure(e); } catch (JMSException jmsEx) { getWrappedRequest().onFailure(jmsEx); } catch (Throwable e) { LOG.debug("Caught exception while executing task: {}", e.getMessage()); triggerReconnectionAttempt(); } } } @Override public void onFailure(final Throwable result) { if (closed.get() || failed.get()) { requests.remove(id); super.onFailure(result); } else { LOG.debug("Request received error: {}", result.getMessage()); serializer.execute(new Runnable() { @Override public void run() { handleProviderFailure(IOExceptionSupport.create(result)); } }); } } @Override public void onSuccess() { requests.remove(id); super.onSuccess(); } /** * Called to execute the specific task that was requested. * * @throws Exception if an error occurs during task execution. */ public abstract void doTask() throws Exception; /** * Should the request just succeed when the Provider is not connected. * * @return true if the request is marked as successful when not connected. */ public boolean succeedsWhenOffline() { return false; } /** * When the transport is not connected should this request automatically fail. * * @return true if the task should fail when the Provider is not connected. */ public boolean failureWhenOffline() { return false; } } /** * Captures the initial request to create a JmsConnectionInfo based resources and ensures * that if the connection is successfully established that the connection established event * is triggered once before moving on to sending only connection interrupted and restored * events. */ protected abstract class CreateConnectionRequest extends FailoverRequest { /** * @param watcher */ public CreateConnectionRequest(AsyncResult watcher) { super(watcher); } @Override public void onSuccess() { serializer.execute(new Runnable() { @Override public void run() { if (firstConnection) { LOG.trace("First connection requst has completed:"); FailoverProvider.this.messageFactory.set(provider.getMessageFactory()); listener.onConnectionEstablished(provider.getRemoteURI()); firstConnection = false; } else { LOG.warn("A second call to a CreateConnectionRequest not expected."); } CreateConnectionRequest.this.signalConnected(); } }); } public void signalConnected() { super.onSuccess(); } } }
add note
qpid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProvider.java
add note
<ide><path>pid-jms-client/src/main/java/org/apache/qpid/jms/provider/failover/FailoverProvider.java <ide> requests.remove(id); <ide> getWrappedRequest().onFailure(e); <ide> } catch (JMSException jmsEx) { <add> //TODO: should we remove the request as above? <ide> getWrappedRequest().onFailure(jmsEx); <ide> } catch (Throwable e) { <ide> LOG.debug("Caught exception while executing task: {}", e.getMessage());
Java
apache-2.0
error: pathspec 'gui/src/verification/platu/partialOrders/LpnTransitionPair.java' did not match any file(s) known to git
8f6cecca7b359ec171abc3af6991b2103d46795d
1
MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim,MyersResearchGroup/iBioSim
package verification.platu.partialOrders; import java.util.HashSet; public class LpnTransitionPair { private Integer lpnIndex; private Integer tranIndex; private HashSet<LpnTransitionPair> transVisited; private int hashVal; private int firingCount; public LpnTransitionPair(Integer lpnIndex, Integer tranIndex) { this.lpnIndex = lpnIndex; this.tranIndex = tranIndex; transVisited = new HashSet<LpnTransitionPair>(); //firingCount = 0; } public Integer getLpnIndex() { return lpnIndex; } public Integer getTranIndex() { return tranIndex; } public void addVisitedTran(LpnTransitionPair lpnTranPair) { transVisited.add(lpnTranPair); } public HashSet<LpnTransitionPair> getVisitedTrans() { return transVisited; } @Override public int hashCode() { if(hashVal == 0){ final int prime = 31; int result = 1; result = prime * result + lpnIndex.hashCode(); result = prime * result + tranIndex.hashCode(); //result = prime * result + tranSetVisitedByNecessary.hashCode(); hashVal = result; } return hashVal; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LpnTransitionPair other = (LpnTransitionPair) obj; if (!lpnIndex.equals(other.lpnIndex)) return false; if (!tranIndex.equals(other.tranIndex)) return false; return true; } // public void resetFiringCount() { // firingCount = 0; // } // // public void increaseFiringCount() { // firingCount++ ; // // } // // public int getFiringCount() { // return firingCount; // } }
gui/src/verification/platu/partialOrders/LpnTransitionPair.java
New data structure for each transition.
gui/src/verification/platu/partialOrders/LpnTransitionPair.java
New data structure for each transition.
<ide><path>ui/src/verification/platu/partialOrders/LpnTransitionPair.java <add>package verification.platu.partialOrders; <add> <add>import java.util.HashSet; <add> <add>public class LpnTransitionPair { <add> private Integer lpnIndex; <add> private Integer tranIndex; <add> private HashSet<LpnTransitionPair> transVisited; <add> private int hashVal; <add> private int firingCount; <add> <add> public LpnTransitionPair(Integer lpnIndex, Integer tranIndex) { <add> this.lpnIndex = lpnIndex; <add> this.tranIndex = tranIndex; <add> transVisited = new HashSet<LpnTransitionPair>(); <add> //firingCount = 0; <add> } <add> <add> public Integer getLpnIndex() { <add> return lpnIndex; <add> } <add> <add> public Integer getTranIndex() { <add> return tranIndex; <add> } <add> <add> public void addVisitedTran(LpnTransitionPair lpnTranPair) { <add> transVisited.add(lpnTranPair); <add> } <add> <add> public HashSet<LpnTransitionPair> getVisitedTrans() { <add> return transVisited; <add> } <add> <add> @Override <add> public int hashCode() { <add> if(hashVal == 0){ <add> final int prime = 31; <add> int result = 1; <add> result = prime * result + lpnIndex.hashCode(); <add> result = prime * result + tranIndex.hashCode(); <add> //result = prime * result + tranSetVisitedByNecessary.hashCode(); <add> hashVal = result; <add> } <add> return hashVal; <add> } <add> <add> @Override <add> public boolean equals(Object obj) { <add> if (this == obj) <add> return true; <add> <add> if (obj == null) <add> return false; <add> <add> if (getClass() != obj.getClass()) <add> return false; <add> <add> LpnTransitionPair other = (LpnTransitionPair) obj; <add> if (!lpnIndex.equals(other.lpnIndex)) <add> return false; <add> if (!tranIndex.equals(other.tranIndex)) <add> return false; <add> return true; <add> } <add> <add>// public void resetFiringCount() { <add>// firingCount = 0; <add>// } <add>// <add>// public void increaseFiringCount() { <add>// firingCount++ ; <add>// <add>// } <add>// <add>// public int getFiringCount() { <add>// return firingCount; <add>// } <add>}
JavaScript
mit
6459233e6231266ed2338019161fc3c36225a4a8
0
itchyny/github-better-header,itchyny/github-better-header
;(function() { // Promise-like object of gathering variables function variablesPool(variables) { var pool = {}; var values = {}; var resolved = false; var callbacks = []; pool.set = function(name, value) { values[name] = value; if (Object.keys(values).length === variables.filter(function(v) { return !v.when || values.hasOwnProperty(v.when) && values[v.when]; }).length) { resolved = true; callbacks.forEach(function(callback) { callback(values); }); } }; pool.then = function(callback) { if (resolved) { callback(values); } else { callbacks.push(callback); } }; return pool; } // Mutation observer witness with the settings injected function witness(setting) { var varpool = variablesPool(setting.variables); var htmlpromise = setting.overwrites.map(function(overwrite) { return [ overwrite.fileName, fetch(chrome.extension.getURL(overwrite.fileName)).then(function(response) { return response.text(); }) ]; }).reduce(function (o, v) { o[v[0]] = v[1]; return o; }, {}); return function(mutations) { [].forEach.call(mutations, function(mutation) { [].forEach.call(mutation.addedNodes || [], function(node) { // we firstly check variables setting.variables.forEach(function(variable) { if (!variable.done && node.getAttribute && (node.getAttribute('name') === variable.name || node.className === variable.className)) { varpool.set(variable.title, node.getAttribute(variable.attribute)); variable.done = true; } }); // then check whether or not we overwrite the element setting.overwrites.forEach(function(overwrite) { if (!overwrite.done && node.className === overwrite.className) { node.style.display = 'none'; htmlpromise[overwrite.fileName].then(function(innerHTML) { varpool.then(function(variables) { if (!overwrite.when || variables[overwrite.when]) { node.innerHTML = Object.keys(variables).reduce(function(innerHTML, name) { return innerHTML.replace(new RegExp('{{ *' + name + ' *}}', 'g'), variables[name]); }, innerHTML); } node.style.display = ''; }); }); overwrite.done = true; } }); }); }); // if all things done, stop observation if (setting.variables.every(function(variable) { return variable.done; }) && setting.overwrites.every(function(overwrite) { return overwrite.done; })) { this.disconnect(); } }; } // overwrite the page with the settings injected function start(setting) { var observer = new MutationObserver(witness(setting)); observer.observe(setting.target, setting.config); } // we start the process start({ target: document, config: { childList: true, subtree: true }, overwrites: [ { className: 'header-nav float-left', fileName: 'header-nav-left.html', when: 'user' }, { className: 'header-nav user-nav float-right', fileName: 'header-nav-right.html', when: 'user' } ], variables: [ { title: 'user', name: 'user-login', attribute: 'content' }, { title: 'avatar', className: 'avatar', attribute: 'src', when: 'user' }, { title: 'authenticity_token', name: 'authenticity_token', attribute: 'value', when: 'user' }, { title: 'form_nonce', name: 'html-safe-nonce', attribute: 'content', when: 'user' } ] }); })();
github-better-header.js
;(function() { // Promise-like object of gathering variables function variablesPool(variables) { var pool = {}; var values = {}; var resolved = false; var callbacks = []; pool.set = function(name, value) { values[name] = value; if (Object.keys(values).length === variables.filter(function(v) { return !v.when || values.hasOwnProperty(v.when) && values[v.when]; }).length) { resolved = true; callbacks.forEach(function(callback) { callback(values); }); } }; pool.then = function(callback) { if (resolved) { callback(values); } else { callbacks.push(callback); } }; return pool; } // Mutation observer witness with the settings injected function witness(setting) { var varpool = variablesPool(setting.variables); var htmlpromise = setting.overwrites.map(function(overwrite) { return [ overwrite.fileName, fetch(chrome.extension.getURL(overwrite.fileName)).then(function(response) { return response.text(); }) ]; }).reduce(function (o, v) { o[v[0]] = v[1]; return o; }, {}); return function(mutations) { [].forEach.call(mutations, function(mutation) { [].forEach.call(mutation.addedNodes || [], function(node) { // we firstly check variables setting.variables.forEach(function(variable) { if (!variable.done && node.getAttribute && (node.getAttribute('name') === variable.name || node.className === variable.className)) { varpool.set(variable.title, node.getAttribute(variable.attribute)); variable.done = true; } }); // then check whether or not we overwrite the element setting.overwrites.forEach(function(overwrite) { if (!overwrite.done && node.className === overwrite.className) { node.style.display = 'none'; htmlpromise[overwrite.fileName].then(function(innerHTML) { varpool.then(function(variables) { if (!overwrite.when || variables[overwrite.when]) { node.innerHTML = Object.keys(variables).reduce(function(innerHTML, name) { return innerHTML.replace(new RegExp('{{ *' + name + ' *}}', 'g'), variables[name]); }, innerHTML); } node.style.display = ''; }); }); overwrite.done = true; } }); setting.rewriteClass.forEach(function(config) { if (!config.done && node.className && node.className.indexOf(config.className) >= 0) { if (config.removeClassName !== undefined) { node.classList.remove(config.removeClassName); config.done = true; } } }); }); }); // if all things done, stop observation if (setting.variables.every(function(variable) { return variable.done; }) && setting.overwrites.every(function(overwrite) { return overwrite.done; })) { this.disconnect(); } }; } // overwrite the page with the settings injected function start(setting) { var observer = new MutationObserver(witness(setting)); observer.observe(setting.target, setting.config); } // we start the process start({ target: document, config: { childList: true, subtree: true }, overwrites: [ { className: 'header-nav float-left', fileName: 'header-nav-left.html', when: 'user' }, { className: 'header-nav user-nav float-right', fileName: 'header-nav-right.html', when: 'user' } ], rewriteClass: [ { className: 'header-dark', removeClassName: 'header-dark' } ], variables: [ { title: 'user', name: 'user-login', attribute: 'content' }, { title: 'avatar', className: 'avatar', attribute: 'src', when: 'user' }, { title: 'authenticity_token', name: 'authenticity_token', attribute: 'value', when: 'user' }, { title: 'form_nonce', name: 'html-safe-nonce', attribute: 'content', when: 'user' } ] }); })();
stop .header-dark removing
github-better-header.js
stop .header-dark removing
<ide><path>ithub-better-header.js <ide> overwrite.done = true; <ide> } <ide> }); <del> setting.rewriteClass.forEach(function(config) { <del> if (!config.done && node.className && node.className.indexOf(config.className) >= 0) { <del> if (config.removeClassName !== undefined) { <del> node.classList.remove(config.removeClassName); <del> config.done = true; <del> } <del> } <del> }); <ide> }); <ide> }); <ide> // if all things done, stop observation <ide> when: 'user' <ide> } <ide> ], <del> rewriteClass: [ <del> { <del> className: 'header-dark', <del> removeClassName: 'header-dark' <del> } <del> ], <ide> variables: [ <ide> { <ide> title: 'user',
JavaScript
epl-1.0
35d6a817d12b4ba520703e6245d3507554889ca3
0
Indoqa/logspace,Indoqa/logspace
/* * Logspace * Copyright (c) 2015 Indoqa Software Design und Beratung GmbH. All rights reserved. * This program and the accompanying materials are made available under the terms of * the Eclipse Public License Version 1.0, which accompanies this distribution and * is available at http://www.eclipse.org/legal/epl-v10.html. */ import React from 'react'; import Component from '../components/component.react'; import TimeSeriesLabel from './time-series-label.react'; import shallowEqual from 'react/lib/shallowEqual'; import {COLORS, TYPES, SCALES} from './constants'; import {onTimeSeriesSaved, onTimeSeriesPropertyChanged, onTimeSeriesDeleted} from './actions'; require('./time-series-edit.styl') export default class EditTimeSeries extends Component { handleChange(event) { onTimeSeriesPropertyChanged(event.target.name, event.target.value) } getCustomScaleInput(agentDescription) { if (agentDescription.get("scaleType") != 'custom') { return <div/> } return (<span> <input name='scaleMin' value={agentDescription.get("scaleMin")} onChange={this.handleChange.bind(this)}/> <nbsp/>-<nbsp/> <input name='scaleMax' value={agentDescription.get("scaleMax")} onChange={this.handleChange.bind(this)}/> </span>) } getPropertyScaleInput(agentDescription) { const propertyScale = SCALES[agentDescription.get("propertyId")] if (propertyScale == null) { return <div/> } const savePropertyScale = () => { onTimeSeriesPropertyChanged('scaleType', 'property') onTimeSeriesPropertyChanged('scaleMin', propertyScale.min) onTimeSeriesPropertyChanged('scaleMax', propertyScale.max) } return (<div> <input type="radio" name="scaleMin" value={'auto'} checked={agentDescription.get("scaleType") === 'property'} onChange={savePropertyScale} > </input> {propertyScale.label} ({propertyScale.min} - {propertyScale.max}) </div>) } render() { const agentDescription = this.props.editedTimeSeries.get("newItem"); const me = this; const propertyScaleInput = this.getPropertyScaleInput(agentDescription) const customScaleInput = this.getCustomScaleInput(agentDescription) const usedColors = this.props.timeSeries.map(function(item) { if (item.get("id") === agentDescription.get("id")) { return "" } return item.get("color") }); return ( <div className='time-series-edit'> <div className='time-series-label-wrapper'> <TimeSeriesLabel timeSeries={agentDescription} /> </div> <div className='details'> <b>Select Property</b> <br/> {agentDescription.get("propertyDescriptions").map((property) => { const propertyId = property.get("id") return ( <div key={propertyId}> <input type="radio" name="propertyId" value={propertyId} checked={propertyId === agentDescription.get("propertyId")} onChange={me.handleChange.bind(me)}> </input> <nbsp/> <span> {property.get("name")} </span> <br/> </div> ) })} <br/> <b>Select Aggregation </b> <br/> <select name="aggregate" value={agentDescription.get("aggregate")} onChange={this.handleChange.bind(this)}> <option value="count">count</option> <option value="max">max</option> <option value="min">min</option> <option value="avg">average</option> <option value="sum">sum</option> </select> <br/> <br/> <b>Select Color </b> <br/> {COLORS.map(function(color) { const colorSyle = { backgroundColor: color } return ( <div key={color} className='color-option' style={colorSyle} > <input type="radio" name="color" value={color} checked={color == agentDescription.get("color")} onChange={me.handleChange.bind(me)} disabled={color != agentDescription.get("color") && usedColors.indexOf(color) > -1}> </input> </div> ) })} <div className='clearer'/> <br/> <b>Define Scale</b> <br/> <input type="radio" name="scaleType" value={'auto'} checked={agentDescription.get("scaleType") == 'auto'} onChange={me.handleChange.bind(me)}> </input> Data (use min/max of result) <br/> {propertyScaleInput} <input type="radio" name="scaleType" value={'custom'} checked={agentDescription.get("scaleType") == 'custom'} onChange={me.handleChange.bind(me)}> </input> Custom {customScaleInput} <div className='buttons'> <button className='waves-effect waves-light btn' onClick={() => onTimeSeriesSaved()}>Save time series</button> <button className={(agentDescription.get("id") != null) ? 'delete-visible waves-effect waves-light btn btn-highlight' : 'delete-hidden'} onClick={() => onTimeSeriesDeleted(agentDescription.get('id'))}>Delete time series </button> </div> </div> </div> ); } }
logspace-frontend/src/client/time-series/time-series-edit.react.js
/* * Logspace * Copyright (c) 2015 Indoqa Software Design und Beratung GmbH. All rights reserved. * This program and the accompanying materials are made available under the terms of * the Eclipse Public License Version 1.0, which accompanies this distribution and * is available at http://www.eclipse.org/legal/epl-v10.html. */ import React from 'react'; import Component from '../components/component.react'; import TimeSeriesLabel from './time-series-label.react'; import shallowEqual from 'react/lib/shallowEqual'; import {COLORS, TYPES, SCALES} from './constants'; import {onTimeSeriesSaved, onTimeSeriesPropertyChanged, onTimeSeriesDeleted} from './actions'; require('./time-series-edit.styl') export default class EditTimeSeries extends Component { handleChange(event) { onTimeSeriesPropertyChanged(event.target.name, event.target.value) } getCustomScaleInput(agentDescription) { if (agentDescription.get("scaleType") != 'custom') { return <div/> } return (<span> <input name='scaleMin' value={agentDescription.get("scaleMin")} onChange={this.handleChange.bind(this)}/> <nbsp/>-<nbsp/> <input name='scaleMax' value={agentDescription.get("scaleMax")} onChange={this.handleChange.bind(this)}/> </span>) } getPropertyScaleInput(agentDescription) { const propertyScale = SCALES[agentDescription.get("propertyId")] if (propertyScale == null) { return <div/> } const savePropertyScale = () => { onTimeSeriesPropertyChanged('scaleType', 'property') onTimeSeriesPropertyChanged('scaleMin', propertyScale.min) onTimeSeriesPropertyChanged('scaleMax', propertyScale.max) } return (<div> <input type="radio" name="scaleMin" value={'auto'} checked={agentDescription.get("scaleType") === 'property'} onChange={savePropertyScale} > </input> {propertyScale.label} ({propertyScale.min} - {propertyScale.max}) </div>) } render() { const agentDescription = this.props.editedTimeSeries.get("newItem"); const me = this; const propertyScaleInput = this.getPropertyScaleInput(agentDescription) const customScaleInput = this.getCustomScaleInput(agentDescription) const usedColors = this.props.timeSeries.map(function(item) { if (item.get("id") === agentDescription.get("id")) { return "" } return item.get("color") }); return ( <div className='time-series-edit'> <div className='time-series-label-wrapper'> <TimeSeriesLabel timeSeries={agentDescription} /> </div> <div className='details'> <b>Select Property</b> <br/> {agentDescription.get("propertyDescriptions").map((property) => { const propertyId = property.get("id") return ( <div key={propertyId}> <input type="radio" name="propertyId" value={propertyId} checked={propertyId === agentDescription.get("propertyId")} onChange={me.handleChange.bind(me)} disabled={property.get("propertyType") === "STRING"}> </input> <nbsp/> <span> {property.get("name")} </span> <br/> </div> ) })} <br/> <b>Select Aggregation </b> <br/> <select name="aggregate" value={agentDescription.get("aggregate")} onChange={this.handleChange.bind(this)}> <option value="count">count</option> <option value="max">max</option> <option value="min">min</option> <option value="avg">average</option> <option value="sum">sum</option> </select> <br/> <br/> <b>Select Color </b> <br/> {COLORS.map(function(color) { const colorSyle = { backgroundColor: color } return ( <div key={color} className='color-option' style={colorSyle} > <input type="radio" name="color" value={color} checked={color == agentDescription.get("color")} onChange={me.handleChange.bind(me)} disabled={color != agentDescription.get("color") && usedColors.indexOf(color) > -1}> </input> </div> ) })} <div className='clearer'/> <br/> <b>Define Scale</b> <br/> <input type="radio" name="scaleType" value={'auto'} checked={agentDescription.get("scaleType") == 'auto'} onChange={me.handleChange.bind(me)}> </input> Data (use min/max of result) <br/> {propertyScaleInput} <input type="radio" name="scaleType" value={'custom'} checked={agentDescription.get("scaleType") == 'custom'} onChange={me.handleChange.bind(me)}> </input> Custom {customScaleInput} <div className='buttons'> <button className='waves-effect waves-light btn' onClick={() => onTimeSeriesSaved()}>Save time series</button> <button className={(agentDescription.get("id") != null) ? 'delete-visible waves-effect waves-light btn btn-highlight' : 'delete-hidden'} onClick={() => onTimeSeriesDeleted(agentDescription.get('id'))}>Delete time series </button> </div> </div> </div> ); } }
re-enable string properties
logspace-frontend/src/client/time-series/time-series-edit.react.js
re-enable string properties
<ide><path>ogspace-frontend/src/client/time-series/time-series-edit.react.js <ide> name="propertyId" <ide> value={propertyId} <ide> checked={propertyId === agentDescription.get("propertyId")} <del> onChange={me.handleChange.bind(me)} <del> disabled={property.get("propertyType") === "STRING"}> <add> onChange={me.handleChange.bind(me)}> <ide> </input> <ide> <nbsp/> <ide> <span> {property.get("name")} </span>
Java
bsd-3-clause
be606ccda168df8dba463537f918c229d43686a9
0
ursjoss/scipamato,ursjoss/scipamato,ursjoss/scipamato,ursjoss/scipamato
package ch.difty.scipamato.core.sync.jobs.paper; import static ch.difty.scipamato.db.core.public_.tables.Paper.*; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.jooq.DeleteConditionStep; import org.jooq.TableField; import org.jooq.impl.DSL; import org.springframework.batch.core.Job; import org.springframework.batch.item.ItemWriter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ch.difty.scipamato.core.sync.jobs.SyncConfig; import ch.difty.scipamato.db.core.public_.tables.Code; import ch.difty.scipamato.db.core.public_.tables.Paper; import ch.difty.scipamato.db.core.public_.tables.PaperCode; import ch.difty.scipamato.db.core.public_.tables.records.PaperRecord; /** * Defines the paper synchronization job, applying two steps: * <ol> * <li> paperInsertingOrUpdating: inserts new records or updates if already present</li> * <li> paperPurging: removes records that have not been touched by the first step * (within a defined grace time in minutes)</li> * </ol> * @author u.joss */ @Configuration public class PaperSyncConfig extends SyncConfig<PublicPaper, ch.difty.scipamato.db.public_.public_.tables.records.PaperRecord> { private static final String TOPIC = "paper"; private static final int CHUNK_SIZE = 100; private static final String ALIAS_CODES = "codes"; // relevant fields of the core Paper record private static final TableField<PaperRecord, Long> C_ID = PAPER.ID; private static final TableField<PaperRecord, Long> C_NUMBER = PAPER.NUMBER; private static final TableField<PaperRecord, Integer> C_PM_ID = PAPER.PM_ID; private static final TableField<PaperRecord, String> C_AUTHORS = PAPER.AUTHORS; private static final TableField<PaperRecord, String> C_TITLE = PAPER.TITLE; private static final TableField<PaperRecord, String> C_LOCATION = PAPER.LOCATION; private static final TableField<PaperRecord, Integer> C_PUB_YEAR = PAPER.PUBLICATION_YEAR; private static final TableField<PaperRecord, String> C_GOALS = PAPER.GOALS; private static final TableField<PaperRecord, String> C_METHODS = PAPER.METHODS; private static final TableField<PaperRecord, String> C_POPULATION = PAPER.POPULATION; private static final TableField<PaperRecord, String> C_RESULT = PAPER.RESULT; private static final TableField<PaperRecord, String> C_COMMENT = PAPER.COMMENT; private static final TableField<PaperRecord, Integer> C_VERSION = PAPER.VERSION; private static final TableField<PaperRecord, Timestamp> C_CREATED = PAPER.CREATED; private static final TableField<PaperRecord, Timestamp> C_LAST_MODIFIED = PAPER.LAST_MODIFIED; protected PaperSyncConfig() { super(TOPIC, CHUNK_SIZE); } @Bean public Job syncPaperJob() { return createJob(); } @Override protected String getJobName() { return "syncPaperJob"; } @Override protected ItemWriter<PublicPaper> publicWriter() { return new PaperItemWriter(getJooqPublic()); } @Override protected String selectSql() { return getJooqCore() .select(C_ID, C_NUMBER, C_PM_ID, C_AUTHORS, C_TITLE, C_LOCATION, C_PUB_YEAR, C_GOALS, C_METHODS, C_POPULATION, C_RESULT, C_COMMENT, C_VERSION, C_CREATED, C_LAST_MODIFIED, DSL.arrayAgg(PaperCode.PAPER_CODE.CODE).as(ALIAS_CODES)) .from(Paper.PAPER) .innerJoin(PaperCode.PAPER_CODE) .on(Paper.PAPER.ID.eq(PaperCode.PAPER_CODE.PAPER_ID)) .innerJoin(Code.CODE) .on(PaperCode.PAPER_CODE.CODE.eq(Code.CODE.CODE_)) .groupBy(C_ID, C_NUMBER, C_PM_ID, C_AUTHORS, C_TITLE, C_LOCATION, C_PUB_YEAR, C_GOALS, C_METHODS, C_POPULATION, C_RESULT, C_COMMENT, C_VERSION, C_CREATED, C_LAST_MODIFIED) .getSQL(); } @Override protected PublicPaper makeEntity(final ResultSet rs) throws SQLException { final PublicPaper paper = PublicPaper .builder() .id(getLong(C_ID, rs)) .number(getLong(C_NUMBER, rs)) .pmId(getInt(C_PM_ID, rs)) .authors(getString(C_AUTHORS, rs)) .title(getString(C_TITLE, rs)) .location(getString(C_LOCATION, rs)) .publicationYear(getInt(C_PUB_YEAR, rs)) .goals(getString(C_GOALS, rs)) .methods(getString(C_METHODS, rs)) .population(getString(C_POPULATION, rs)) .result(getString(C_RESULT, rs)) .comment(getString(C_COMMENT, rs)) .codes(extractCodes(ALIAS_CODES, rs)) .version(getInt(C_VERSION, rs)) .created(getTimestamp(C_CREATED, rs)) .lastModified(getTimestamp(C_LAST_MODIFIED, rs)) .lastSynched(getNow()) .build(); paper.setCodesPopulation(getPopulationCodes(paper)); paper.setCodesStudyDesign(getStudyDesignCodes(paper)); return paper; } // Population (1: Children (Codes 3A+3B), 2: Adults (Codes 3C) private Short[] getPopulationCodes(final PublicPaper paper) { final List<Short> pcList = new ArrayList<>(); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("3A") || x.equals("3B"))) pcList.add((short) 1); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("3C"))) pcList.add((short) 2); return pcList.toArray(new Short[pcList.size()]); } // (1: Experimental Studies (5A+5B+5C), 2: Epidemiolog. Studies (5E+5F+5G+5H+5I)), 3. Overview/Methodology (5U+5M) private Short[] getStudyDesignCodes(final PublicPaper paper) { final List<Short> pcList = new ArrayList<>(); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("5A") || x.equals("5B") || x.equals("5C"))) pcList.add((short) 1); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("5E") || x.equals("5F") || x.equals("5G") || x.equals("5H") || x.equals("5I"))) pcList.add((short) 2); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("5U") || x.equals("5M"))) pcList.add((short) 3); return pcList.toArray(new Short[pcList.size()]); } private String[] extractCodes(final String alias, final ResultSet rs) throws SQLException { return (String[]) rs.getArray(alias).getArray(); } @Override protected DeleteConditionStep<ch.difty.scipamato.db.public_.public_.tables.records.PaperRecord> getPurgeDcs(final Timestamp cutOff) { // @formatter:off return getJooqPublic() .delete(ch.difty.scipamato.db.public_.public_.tables.Paper.PAPER) .where(ch.difty.scipamato.db.public_.public_.tables.Paper.PAPER.LAST_SYNCHED.lessThan(cutOff)); // @formatter:on } }
implementation/scipamato/scipamato-core-sync/src/main/java/ch/difty/scipamato/core/sync/jobs/paper/PaperSyncConfig.java
package ch.difty.scipamato.core.sync.jobs.paper; import static ch.difty.scipamato.db.core.public_.tables.Paper.*; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import org.jooq.DeleteConditionStep; import org.jooq.TableField; import org.jooq.impl.DSL; import org.springframework.batch.core.Job; import org.springframework.batch.item.ItemWriter; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import ch.difty.scipamato.core.sync.jobs.SyncConfig; import ch.difty.scipamato.db.core.public_.tables.Code; import ch.difty.scipamato.db.core.public_.tables.Paper; import ch.difty.scipamato.db.core.public_.tables.PaperCode; import ch.difty.scipamato.db.core.public_.tables.records.PaperRecord; /** * Defines the paper synchronization job, applying two steps: * <ol> * <li> paperInsertingOrUpdating: inserts new records or updates if already present</li> * <li> paperPurging: removes records that have not been touched by the first step * (within a defined grace time in minutes)</li> * </ol> * @author u.joss */ @Configuration public class PaperSyncConfig extends SyncConfig<PublicPaper, ch.difty.scipamato.db.public_.public_.tables.records.PaperRecord> { private static final String TOPIC = "paper"; private static final int CHUNK_SIZE = 100; private static final String ALIAS_CODES = "codes"; // relevant fields of the core Paper record private static final TableField<PaperRecord, Long> C_ID = PAPER.ID; private static final TableField<PaperRecord, Long> C_NUMBER = PAPER.NUMBER; private static final TableField<PaperRecord, Integer> C_PM_ID = PAPER.PM_ID; private static final TableField<PaperRecord, String> C_AUTHORS = PAPER.AUTHORS; private static final TableField<PaperRecord, String> C_TITLE = PAPER.TITLE; private static final TableField<PaperRecord, String> C_LOCATION = PAPER.LOCATION; private static final TableField<PaperRecord, Integer> C_PUB_YEAR = PAPER.PUBLICATION_YEAR; private static final TableField<PaperRecord, String> C_GOALS = PAPER.GOALS; private static final TableField<PaperRecord, String> C_METHODS = PAPER.METHODS; private static final TableField<PaperRecord, String> C_POPULATION = PAPER.POPULATION; private static final TableField<PaperRecord, String> C_RESULT = PAPER.RESULT; private static final TableField<PaperRecord, String> C_COMMENT = PAPER.COMMENT; // TODO code arrays private static final TableField<PaperRecord, Integer> C_VERSION = PAPER.VERSION; private static final TableField<PaperRecord, Timestamp> C_CREATED = PAPER.CREATED; private static final TableField<PaperRecord, Timestamp> C_LAST_MODIFIED = PAPER.LAST_MODIFIED; protected PaperSyncConfig() { super(TOPIC, CHUNK_SIZE); } @Bean public Job syncPaperJob() { return createJob(); } @Override protected String getJobName() { return "syncPaperJob"; } @Override protected ItemWriter<PublicPaper> publicWriter() { return new PaperItemWriter(getJooqPublic()); } @Override protected String selectSql() { return getJooqCore() // TODO derive remaining code stuff .select(C_ID, C_NUMBER, C_PM_ID, C_AUTHORS, C_TITLE, C_LOCATION, C_PUB_YEAR, C_GOALS, C_METHODS, C_POPULATION, C_RESULT, C_COMMENT, C_VERSION, C_CREATED, C_LAST_MODIFIED, DSL.arrayAgg(PaperCode.PAPER_CODE.CODE).as(ALIAS_CODES)) .from(Paper.PAPER) .innerJoin(PaperCode.PAPER_CODE) .on(Paper.PAPER.ID.eq(PaperCode.PAPER_CODE.PAPER_ID)) .innerJoin(Code.CODE) .on(PaperCode.PAPER_CODE.CODE.eq(Code.CODE.CODE_)) // .where(Code.CODE.INTERNAL.isFalse()) // TODO need to filter only some of those .groupBy(C_ID, C_NUMBER, C_PM_ID, C_AUTHORS, C_TITLE, C_LOCATION, C_PUB_YEAR, C_GOALS, C_METHODS, C_POPULATION, C_RESULT, C_COMMENT, C_VERSION, C_CREATED, C_LAST_MODIFIED) .getSQL(); } @Override protected PublicPaper makeEntity(final ResultSet rs) throws SQLException { final PublicPaper paper = PublicPaper .builder() .id(getLong(C_ID, rs)) .number(getLong(C_NUMBER, rs)) .pmId(getInt(C_PM_ID, rs)) .authors(getString(C_AUTHORS, rs)) .title(getString(C_TITLE, rs)) .location(getString(C_LOCATION, rs)) .publicationYear(getInt(C_PUB_YEAR, rs)) .goals(getString(C_GOALS, rs)) .methods(getString(C_METHODS, rs)) .population(getString(C_POPULATION, rs)) .result(getString(C_RESULT, rs)) .comment(getString(C_COMMENT, rs)) .codes(extractCodes(ALIAS_CODES, rs)) .version(getInt(C_VERSION, rs)) .created(getTimestamp(C_CREATED, rs)) .lastModified(getTimestamp(C_LAST_MODIFIED, rs)) .lastSynched(getNow()) .build(); paper.setCodesPopulation(getPopulationCodes(paper)); paper.setCodesStudyDesign(getStudyDesignCodes(paper)); return paper; } // Population (1: Children (Codes 3A+3B), 2: Adults (Codes 3C) private Short[] getPopulationCodes(final PublicPaper paper) { final List<Short> pcList = new ArrayList<>(); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("3A") || x.equals("3B"))) pcList.add((short) 1); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("3C"))) pcList.add((short) 2); return pcList.toArray(new Short[pcList.size()]); } // (1: Experimental Studies (5A+5B+5C), 2: Epidemiolog. Studies (5E+5F+5G+5H+5I)), 3. Overview/Methodology (5U+5M) private Short[] getStudyDesignCodes(final PublicPaper paper) { final List<Short> pcList = new ArrayList<>(); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("5A") || x.equals("5B") || x.equals("5C"))) pcList.add((short) 1); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("5E") || x.equals("5F") || x.equals("5G") || x.equals("5H") || x.equals("5I"))) pcList.add((short) 2); if (Stream.of(paper.getCodes()).anyMatch(x -> x.equals("5U") || x.equals("5M"))) pcList.add((short) 3); return pcList.toArray(new Short[pcList.size()]); } private String[] extractCodes(final String alias, final ResultSet rs) throws SQLException { return (String[]) rs.getArray(alias).getArray(); } @Override protected DeleteConditionStep<ch.difty.scipamato.db.public_.public_.tables.records.PaperRecord> getPurgeDcs(final Timestamp cutOff) { // @formatter:off return getJooqPublic() .delete(ch.difty.scipamato.db.public_.public_.tables.Paper.PAPER) .where(ch.difty.scipamato.db.public_.public_.tables.Paper.PAPER.LAST_SYNCHED.lessThan(cutOff)); // @formatter:on } }
07/13: Remove obsolete TODOs
implementation/scipamato/scipamato-core-sync/src/main/java/ch/difty/scipamato/core/sync/jobs/paper/PaperSyncConfig.java
07/13: Remove obsolete TODOs
<ide><path>mplementation/scipamato/scipamato-core-sync/src/main/java/ch/difty/scipamato/core/sync/jobs/paper/PaperSyncConfig.java <ide> private static final TableField<PaperRecord, String> C_POPULATION = PAPER.POPULATION; <ide> private static final TableField<PaperRecord, String> C_RESULT = PAPER.RESULT; <ide> private static final TableField<PaperRecord, String> C_COMMENT = PAPER.COMMENT; <del> <del> // TODO code arrays <del> <ide> private static final TableField<PaperRecord, Integer> C_VERSION = PAPER.VERSION; <ide> private static final TableField<PaperRecord, Timestamp> C_CREATED = PAPER.CREATED; <ide> private static final TableField<PaperRecord, Timestamp> C_LAST_MODIFIED = PAPER.LAST_MODIFIED; <ide> @Override <ide> protected String selectSql() { <ide> return getJooqCore() <del> // TODO derive remaining code stuff <ide> .select(C_ID, C_NUMBER, C_PM_ID, C_AUTHORS, C_TITLE, C_LOCATION, C_PUB_YEAR, C_GOALS, C_METHODS, C_POPULATION, C_RESULT, C_COMMENT, C_VERSION, C_CREATED, C_LAST_MODIFIED, <ide> DSL.arrayAgg(PaperCode.PAPER_CODE.CODE).as(ALIAS_CODES)) <ide> .from(Paper.PAPER) <ide> .on(Paper.PAPER.ID.eq(PaperCode.PAPER_CODE.PAPER_ID)) <ide> .innerJoin(Code.CODE) <ide> .on(PaperCode.PAPER_CODE.CODE.eq(Code.CODE.CODE_)) <del>// .where(Code.CODE.INTERNAL.isFalse()) // TODO need to filter only some of those <ide> .groupBy(C_ID, C_NUMBER, C_PM_ID, C_AUTHORS, C_TITLE, C_LOCATION, C_PUB_YEAR, C_GOALS, C_METHODS, C_POPULATION, C_RESULT, C_COMMENT, C_VERSION, C_CREATED, C_LAST_MODIFIED) <ide> .getSQL(); <ide> }
JavaScript
mit
f9d88c2423a54fb48ebdbbef6f1915c876df80af
0
gero3/three.js,fraguada/three.js,fraguada/three.js,fraguada/three.js,TristanVALCKE/three.js,fyoudine/three.js,TristanVALCKE/three.js,stanford-gfx/three.js,mrdoob/three.js,Samsy/three.js,WestLangley/three.js,stanford-gfx/three.js,TristanVALCKE/three.js,QingchaoHu/three.js,fraguada/three.js,Samsy/three.js,aardgoose/three.js,kaisalmen/three.js,Samsy/three.js,fyoudine/three.js,kaisalmen/three.js,aardgoose/three.js,Liuer/three.js,donmccurdy/three.js,Itee/three.js,SpinVR/three.js,greggman/three.js,looeee/three.js,makc/three.js.fork,TristanVALCKE/three.js,Itee/three.js,looeee/three.js,TristanVALCKE/three.js,fraguada/three.js,06wj/three.js,zhoushijie163/three.js,Liuer/three.js,gero3/three.js,fraguada/three.js,greggman/three.js,QingchaoHu/three.js,Samsy/three.js,WestLangley/three.js,jpweeks/three.js,Samsy/three.js,TristanVALCKE/three.js,zhoushijie163/three.js,donmccurdy/three.js,06wj/three.js,SpinVR/three.js,jpweeks/three.js,Samsy/three.js,mrdoob/three.js,makc/three.js.fork
/** * @author Rich Tibbett / https://github.com/richtr * @author mrdoob / http://mrdoob.com/ * @author Tony Parisi / http://www.tonyparisi.com/ * @author Takahiro / https://github.com/takahirox * @author Don McCurdy / https://www.donmccurdy.com */ THREE.GLTFLoader = ( function () { function GLTFLoader( manager ) { THREE.Loader.call( this, manager ); this.dracoLoader = null; this.ddsLoader = null; } GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { constructor: GLTFLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var resourcePath; if ( this.resourcePath !== '' ) { resourcePath = this.resourcePath; } else if ( this.path !== '' ) { resourcePath = this.path; } else { resourcePath = THREE.LoaderUtils.extractUrlBase( url ); } // Tells the LoadingManager to track an extra item, which resolves after // the model is fully loaded. This means the count of items loaded will // be incorrect, but ensures manager.onLoad() does not fire early. scope.manager.itemStart( url ); var _onError = function ( e ) { if ( onError ) { onError( e ); } else { console.error( e ); } scope.manager.itemError( url ); scope.manager.itemEnd( url ); }; var loader = new THREE.FileLoader( scope.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); if ( scope.crossOrigin === 'use-credentials' ) { loader.setWithCredentials( true ); } loader.load( url, function ( data ) { try { scope.parse( data, resourcePath, function ( gltf ) { onLoad( gltf ); scope.manager.itemEnd( url ); }, _onError ); } catch ( e ) { _onError( e ); } }, onProgress, _onError ); }, setDRACOLoader: function ( dracoLoader ) { this.dracoLoader = dracoLoader; return this; }, setDDSLoader: function ( ddsLoader ) { this.ddsLoader = ddsLoader; return this; }, parse: function ( data, path, onLoad, onError ) { var content; var extensions = {}; if ( typeof data === 'string' ) { content = data; } else { var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) ); if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { try { extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); } catch ( error ) { if ( onError ) onError( error ); return; } content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content; } else { content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) ); } } var json = JSON.parse( content ); if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) ); return; } if ( json.extensionsUsed ) { for ( var i = 0; i < json.extensionsUsed.length; ++ i ) { var extensionName = json.extensionsUsed[ i ]; var extensionsRequired = json.extensionsRequired || []; switch ( extensionName ) { case EXTENSIONS.KHR_LIGHTS_PUNCTUAL: extensions[ extensionName ] = new GLTFLightsExtension( json ); break; case EXTENSIONS.KHR_MATERIALS_UNLIT: extensions[ extensionName ] = new GLTFMaterialsUnlitExtension(); break; case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension(); break; case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader ); break; case EXTENSIONS.MSFT_TEXTURE_DDS: extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension( this.ddsLoader ); break; case EXTENSIONS.KHR_TEXTURE_TRANSFORM: extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension(); break; default: if ( extensionsRequired.indexOf( extensionName ) >= 0 ) { console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' ); } } } } var parser = new GLTFParser( json, extensions, { path: path || this.resourcePath || '', crossOrigin: this.crossOrigin, manager: this.manager } ); parser.parse( onLoad, onError ); } } ); /* GLTFREGISTRY */ function GLTFRegistry() { var objects = {}; return { get: function ( key ) { return objects[ key ]; }, add: function ( key, object ) { objects[ key ] = object; }, remove: function ( key ) { delete objects[ key ]; }, removeAll: function () { objects = {}; } }; } /*********************************/ /********** EXTENSIONS ***********/ /*********************************/ var EXTENSIONS = { KHR_BINARY_GLTF: 'KHR_binary_glTF', KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', MSFT_TEXTURE_DDS: 'MSFT_texture_dds' }; /** * DDS Texture Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds * */ function GLTFTextureDDSExtension( ddsLoader ) { if ( ! ddsLoader ) { throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' ); } this.name = EXTENSIONS.MSFT_TEXTURE_DDS; this.ddsLoader = ddsLoader; } /** * Punctual Lights Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual */ function GLTFLightsExtension( json ) { this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {}; this.lightDefs = extension.lights || []; } GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) { var lightDef = this.lightDefs[ lightIndex ]; var lightNode; var color = new THREE.Color( 0xffffff ); if ( lightDef.color !== undefined ) color.fromArray( lightDef.color ); var range = lightDef.range !== undefined ? lightDef.range : 0; switch ( lightDef.type ) { case 'directional': lightNode = new THREE.DirectionalLight( color ); lightNode.target.position.set( 0, 0, - 1 ); lightNode.add( lightNode.target ); break; case 'point': lightNode = new THREE.PointLight( color ); lightNode.distance = range; break; case 'spot': lightNode = new THREE.SpotLight( color ); lightNode.distance = range; // Handle spotlight properties. lightDef.spot = lightDef.spot || {}; lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0; lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0; lightNode.angle = lightDef.spot.outerConeAngle; lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; lightNode.target.position.set( 0, 0, - 1 ); lightNode.add( lightNode.target ); break; default: throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' ); } // Some lights (e.g. spot) default to a position other than the origin. Reset the position // here, because node-level parsing will only override position if explicitly specified. lightNode.position.set( 0, 0, 0 ); lightNode.decay = 2; if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity; lightNode.name = lightDef.name || ( 'light_' + lightIndex ); return Promise.resolve( lightNode ); }; /** * Unlit Materials Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit */ function GLTFMaterialsUnlitExtension() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () { return THREE.MeshBasicMaterial; }; GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) { var pending = []; materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; var metallicRoughness = materialDef.pbrMetallicRoughness; if ( metallicRoughness ) { if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { var array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; } if ( metallicRoughness.baseColorTexture !== undefined ) { pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) ); } } return Promise.all( pending ); }; /* BINARY EXTENSION */ var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; var BINARY_EXTENSION_HEADER_LENGTH = 12; var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; function GLTFBinaryExtension( data ) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); this.header = { magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ), version: headerView.getUint32( 4, true ), length: headerView.getUint32( 8, true ) }; if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) { throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' ); } else if ( this.header.version < 2.0 ) { throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' ); } var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH ); var chunkIndex = 0; while ( chunkIndex < chunkView.byteLength ) { var chunkLength = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; var chunkType = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) { var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); this.content = THREE.LoaderUtils.decodeText( contentArray ); } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) { var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice( byteOffset, byteOffset + chunkLength ); } // Clients must ignore chunks with unknown types. chunkIndex += chunkLength; } if ( this.content === null ) { throw new Error( 'THREE.GLTFLoader: JSON content not found.' ); } } /** * DRACO Mesh Compression Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression */ function GLTFDracoMeshCompressionExtension( json, dracoLoader ) { if ( ! dracoLoader ) { throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' ); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; } GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) { var json = this.json; var dracoLoader = this.dracoLoader; var bufferViewIndex = primitive.extensions[ this.name ].bufferView; var gltfAttributeMap = primitive.extensions[ this.name ].attributes; var threeAttributeMap = {}; var attributeNormalizedMap = {}; var attributeTypeMap = {}; for ( var attributeName in gltfAttributeMap ) { var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ]; } for ( attributeName in primitive.attributes ) { var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); if ( gltfAttributeMap[ attributeName ] !== undefined ) { var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ]; var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; attributeTypeMap[ threeAttributeName ] = componentType; attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true; } } return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) { return new Promise( function ( resolve ) { dracoLoader.decodeDracoFile( bufferView, function ( geometry ) { for ( var attributeName in geometry.attributes ) { var attribute = geometry.attributes[ attributeName ]; var normalized = attributeNormalizedMap[ attributeName ]; if ( normalized !== undefined ) attribute.normalized = normalized; } resolve( geometry ); }, threeAttributeMap, attributeTypeMap ); } ); } ); }; /** * Texture Transform Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform */ function GLTFTextureTransformExtension() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) { texture = texture.clone(); if ( transform.offset !== undefined ) { texture.offset.fromArray( transform.offset ); } if ( transform.rotation !== undefined ) { texture.rotation = transform.rotation; } if ( transform.scale !== undefined ) { texture.repeat.fromArray( transform.scale ); } if ( transform.texCoord !== undefined ) { console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' ); } texture.needsUpdate = true; return texture; }; /** * Specular-Glossiness Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness */ function GLTFMaterialsPbrSpecularGlossinessExtension() { return { name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS, specularGlossinessParams: [ 'color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio', ], getMaterialType: function () { return THREE.ShaderMaterial; }, extendParams: function ( materialParams, materialDef, parser ) { var pbrSpecularGlossiness = materialDef.extensions[ this.name ]; var shader = THREE.ShaderLib[ 'standard' ]; var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); var specularMapParsFragmentChunk = [ '#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif' ].join( '\n' ); var glossinessMapParsFragmentChunk = [ '#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif' ].join( '\n' ); var specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' ); var glossinessMapFragmentChunk = [ 'float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif' ].join( '\n' ); var lightPhysicalFragmentChunk = [ 'PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;', ].join( '\n' ); var fragmentShader = shader.fragmentShader .replace( 'uniform float roughness;', 'uniform vec3 specular;' ) .replace( 'uniform float metalness;', 'uniform float glossiness;' ) .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk ) .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk ) .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk ) .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk ) .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk ); delete uniforms.roughness; delete uniforms.metalness; delete uniforms.roughnessMap; delete uniforms.metalnessMap; uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) }; uniforms.glossiness = { value: 0.5 }; uniforms.specularMap = { value: null }; uniforms.glossinessMap = { value: null }; materialParams.vertexShader = shader.vertexShader; materialParams.fragmentShader = fragmentShader; materialParams.uniforms = uniforms; materialParams.defines = { 'STANDARD': '' }; materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; var pending = []; if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) { var array = pbrSpecularGlossiness.diffuseFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; } if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) { pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) ); } materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 ); materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 ); if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) { materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor ); } if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) { var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) ); pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) ); } return Promise.all( pending ); }, createMaterial: function ( params ) { // setup material properties based on MeshStandardMaterial for Specular-Glossiness var material = new THREE.ShaderMaterial( { defines: params.defines, vertexShader: params.vertexShader, fragmentShader: params.fragmentShader, uniforms: params.uniforms, fog: true, lights: true, opacity: params.opacity, transparent: params.transparent } ); material.isGLTFSpecularGlossinessMaterial = true; material.color = params.color; material.map = params.map === undefined ? null : params.map; material.lightMap = null; material.lightMapIntensity = 1.0; material.aoMap = params.aoMap === undefined ? null : params.aoMap; material.aoMapIntensity = 1.0; material.emissive = params.emissive; material.emissiveIntensity = 1.0; material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap; material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap; material.bumpScale = 1; material.normalMap = params.normalMap === undefined ? null : params.normalMap; if ( params.normalScale ) material.normalScale = params.normalScale; material.displacementMap = null; material.displacementScale = 1; material.displacementBias = 0; material.specularMap = params.specularMap === undefined ? null : params.specularMap; material.specular = params.specular; material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap; material.glossiness = params.glossiness; material.alphaMap = null; material.envMap = params.envMap === undefined ? null : params.envMap; material.envMapIntensity = 1.0; material.refractionRatio = 0.98; material.extensions.derivatives = true; return material; }, /** * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can * copy only properties it knows about or inherits, and misses many properties that would * normally be defined by MeshStandardMaterial. * * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of * loading a glTF model, but cloning later (e.g. by the user) would require these changes * AND also updating `.onBeforeRender` on the parent mesh. * * @param {THREE.ShaderMaterial} source * @return {THREE.ShaderMaterial} */ cloneMaterial: function ( source ) { var target = source.clone(); target.isGLTFSpecularGlossinessMaterial = true; var params = this.specularGlossinessParams; for ( var i = 0, il = params.length; i < il; i ++ ) { var value = source[ params[ i ] ]; target[ params[ i ] ] = ( value && value.isColor ) ? value.clone() : value; } return target; }, // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer. refreshUniforms: function ( renderer, scene, camera, geometry, material ) { if ( material.isGLTFSpecularGlossinessMaterial !== true ) { return; } var uniforms = material.uniforms; var defines = material.defines; uniforms.opacity.value = material.opacity; uniforms.diffuse.value.copy( material.color ); uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); uniforms.map.value = material.map; uniforms.specularMap.value = material.specularMap; uniforms.alphaMap.value = material.alphaMap; uniforms.lightMap.value = material.lightMap; uniforms.lightMapIntensity.value = material.lightMapIntensity; uniforms.aoMap.value = material.aoMap; uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities // 1. color map // 2. specular map // 3. normal map // 4. bump map // 5. alpha map // 6. emissive map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.specularMap ) { uvScaleMap = material.specularMap; } else if ( material.displacementMap ) { uvScaleMap = material.displacementMap; } else if ( material.normalMap ) { uvScaleMap = material.normalMap; } else if ( material.bumpMap ) { uvScaleMap = material.bumpMap; } else if ( material.glossinessMap ) { uvScaleMap = material.glossinessMap; } else if ( material.alphaMap ) { uvScaleMap = material.alphaMap; } else if ( material.emissiveMap ) { uvScaleMap = material.emissiveMap; } if ( uvScaleMap !== undefined ) { // backwards compatibility if ( uvScaleMap.isWebGLRenderTarget ) { uvScaleMap = uvScaleMap.texture; } if ( uvScaleMap.matrixAutoUpdate === true ) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy( uvScaleMap.matrix ); } if ( material.envMap ) { uniforms.envMap.value = material.envMap; uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else: // WebGLRenderTargetCube will be flipped for backwards compatibility // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1; uniforms.reflectivity.value = material.reflectivity; uniforms.refractionRatio.value = material.refractionRatio; uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel; } uniforms.specular.value.copy( material.specular ); uniforms.glossiness.value = material.glossiness; uniforms.glossinessMap.value = material.glossinessMap; uniforms.emissiveMap.value = material.emissiveMap; uniforms.bumpMap.value = material.bumpMap; uniforms.normalMap.value = material.normalMap; uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) { defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv defines.USE_ROUGHNESSMAP = ''; } if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) { delete defines.USE_GLOSSINESSMAP; delete defines.USE_ROUGHNESSMAP; } } }; } /*********************************/ /********** INTERPOLATION ********/ /*********************************/ // Spline Interpolation // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); } GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype ); GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant; GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) { // Copies a sample value to the result buffer. See description of glTF // CUBICSPLINE values layout in interpolate_() function below. var result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize; for ( var i = 0; i !== valueSize; i ++ ) { result[ i ] = values[ offset + i ]; } return result; }; GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) { var result = this.resultBuffer; var values = this.sampleValues; var stride = this.valueSize; var stride2 = stride * 2; var stride3 = stride * 3; var td = t1 - t0; var p = ( t - t0 ) / td; var pp = p * p; var ppp = pp * p; var offset1 = i1 * stride3; var offset0 = offset1 - stride3; var s2 = - 2 * ppp + 3 * pp; var s3 = ppp - pp; var s0 = 1 - s2; var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations: // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] for ( var i = 0; i !== stride; i ++ ) { var p0 = values[ offset0 + i + stride ]; // splineVertex_k var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k) var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1 var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k) result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; } return result; }; /*********************************/ /********** INTERNALS ************/ /*********************************/ /* CONSTANTS */ var WEBGL_CONSTANTS = { FLOAT: 5126, //FLOAT_MAT2: 35674, FLOAT_MAT3: 35675, FLOAT_MAT4: 35676, FLOAT_VEC2: 35664, FLOAT_VEC3: 35665, FLOAT_VEC4: 35666, LINEAR: 9729, REPEAT: 10497, SAMPLER_2D: 35678, POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6, UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123 }; var WEBGL_COMPONENT_TYPES = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }; var WEBGL_FILTERS = { 9728: THREE.NearestFilter, 9729: THREE.LinearFilter, 9984: THREE.NearestMipmapNearestFilter, 9985: THREE.LinearMipmapNearestFilter, 9986: THREE.NearestMipmapLinearFilter, 9987: THREE.LinearMipmapLinearFilter }; var WEBGL_WRAPPINGS = { 33071: THREE.ClampToEdgeWrapping, 33648: THREE.MirroredRepeatWrapping, 10497: THREE.RepeatWrapping }; var WEBGL_TYPE_SIZES = { 'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, 'MAT2': 4, 'MAT3': 9, 'MAT4': 16 }; var ATTRIBUTES = { POSITION: 'position', NORMAL: 'normal', TANGENT: 'tangent', TEXCOORD_0: 'uv', TEXCOORD_1: 'uv2', COLOR_0: 'color', WEIGHTS_0: 'skinWeight', JOINTS_0: 'skinIndex', }; var PATH_PROPERTIES = { scale: 'scale', translation: 'position', rotation: 'quaternion', weights: 'morphTargetInfluences' }; var INTERPOLATION = { CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. LINEAR: THREE.InterpolateLinear, STEP: THREE.InterpolateDiscrete }; var ALPHA_MODES = { OPAQUE: 'OPAQUE', MASK: 'MASK', BLEND: 'BLEND' }; var MIME_TYPE_FORMATS = { 'image/png': THREE.RGBAFormat, 'image/jpeg': THREE.RGBFormat }; /* UTILITY FUNCTIONS */ function resolveURL( url, path ) { // Invalid URL if ( typeof url !== 'string' || url === '' ) return ''; // Host Relative URL if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); } // Absolute URL http://,https://,// if ( /^(https?:)?\/\//i.test( url ) ) return url; // Data URI if ( /^data:.*,.*$/i.test( url ) ) return url; // Blob URL if ( /^blob:.*$/i.test( url ) ) return url; // Relative URL return path + url; } var defaultMaterial; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material */ function createDefaultMaterial() { defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( { color: 0xFFFFFF, emissive: 0x000000, metalness: 1, roughness: 1, transparent: false, depthTest: true, side: THREE.FrontSide } ); return defaultMaterial; } function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) { // Add unknown glTF extensions to an object's userData. for ( var name in objectDef.extensions ) { if ( knownExtensions[ name ] === undefined ) { object.userData.gltfExtensions = object.userData.gltfExtensions || {}; object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ]; } } } /** * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object * @param {GLTF.definition} gltfDef */ function assignExtrasToUserData( object, gltfDef ) { if ( gltfDef.extras !== undefined ) { if ( typeof gltfDef.extras === 'object' ) { Object.assign( object.userData, gltfDef.extras ); } else { console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras ); } } } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets * * @param {THREE.BufferGeometry} geometry * @param {Array<GLTF.Target>} targets * @param {GLTFParser} parser * @return {Promise<THREE.BufferGeometry>} */ function addMorphTargets( geometry, targets, parser ) { var hasMorphPosition = false; var hasMorphNormal = false; for ( var i = 0, il = targets.length; i < il; i ++ ) { var target = targets[ i ]; if ( target.POSITION !== undefined ) hasMorphPosition = true; if ( target.NORMAL !== undefined ) hasMorphNormal = true; if ( hasMorphPosition && hasMorphNormal ) break; } if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry ); var pendingPositionAccessors = []; var pendingNormalAccessors = []; for ( var i = 0, il = targets.length; i < il; i ++ ) { var target = targets[ i ]; if ( hasMorphPosition ) { var pendingAccessor = target.POSITION !== undefined ? parser.getDependency( 'accessor', target.POSITION ) : geometry.attributes.position; pendingPositionAccessors.push( pendingAccessor ); } if ( hasMorphNormal ) { var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency( 'accessor', target.NORMAL ) : geometry.attributes.normal; pendingNormalAccessors.push( pendingAccessor ); } } return Promise.all( [ Promise.all( pendingPositionAccessors ), Promise.all( pendingNormalAccessors ) ] ).then( function ( accessors ) { var morphPositions = accessors[ 0 ]; var morphNormals = accessors[ 1 ]; // Clone morph target accessors before modifying them. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) { if ( geometry.attributes.position === morphPositions[ i ] ) continue; morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] ); } for ( var i = 0, il = morphNormals.length; i < il; i ++ ) { if ( geometry.attributes.normal === morphNormals[ i ] ) continue; morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] ); } for ( var i = 0, il = targets.length; i < il; i ++ ) { var target = targets[ i ]; var attributeName = 'morphTarget' + i; if ( hasMorphPosition ) { // Three.js morph position is absolute value. The formula is // basePosition // + weight0 * ( morphPosition0 - basePosition ) // + weight1 * ( morphPosition1 - basePosition ) // ... // while the glTF one is relative // basePosition // + weight0 * glTFmorphPosition0 // + weight1 * glTFmorphPosition1 // ... // then we need to convert from relative to absolute here. if ( target.POSITION !== undefined ) { var positionAttribute = morphPositions[ i ]; positionAttribute.name = attributeName; var position = geometry.attributes.position; for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) { positionAttribute.setXYZ( j, positionAttribute.getX( j ) + position.getX( j ), positionAttribute.getY( j ) + position.getY( j ), positionAttribute.getZ( j ) + position.getZ( j ) ); } } } if ( hasMorphNormal ) { // see target.POSITION's comment if ( target.NORMAL !== undefined ) { var normalAttribute = morphNormals[ i ]; normalAttribute.name = attributeName; var normal = geometry.attributes.normal; for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) { normalAttribute.setXYZ( j, normalAttribute.getX( j ) + normal.getX( j ), normalAttribute.getY( j ) + normal.getY( j ), normalAttribute.getZ( j ) + normal.getZ( j ) ); } } } } if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions; if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals; return geometry; } ); } /** * @param {THREE.Mesh} mesh * @param {GLTF.Mesh} meshDef */ function updateMorphTargets( mesh, meshDef ) { mesh.updateMorphTargets(); if ( meshDef.weights !== undefined ) { for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) { mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ]; } } // .extras has user-defined data, so check that .extras.targetNames is an array. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) { var targetNames = meshDef.extras.targetNames; if ( mesh.morphTargetInfluences.length === targetNames.length ) { mesh.morphTargetDictionary = {}; for ( var i = 0, il = targetNames.length; i < il; i ++ ) { mesh.morphTargetDictionary[ targetNames[ i ] ] = i; } } else { console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' ); } } } function createPrimitiveKey( primitiveDef ) { var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]; var geometryKey; if ( dracoExtension ) { geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey( dracoExtension.attributes ); } else { geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode; } return geometryKey; } function createAttributesKey( attributes ) { var attributesKey = ''; var keys = Object.keys( attributes ).sort(); for ( var i = 0, il = keys.length; i < il; i ++ ) { attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';'; } return attributesKey; } function cloneBufferAttribute( attribute ) { if ( attribute.isInterleavedBufferAttribute ) { var count = attribute.count; var itemSize = attribute.itemSize; var array = attribute.array.slice( 0, count * itemSize ); for ( var i = 0, j = 0; i < count; ++ i ) { array[ j ++ ] = attribute.getX( i ); if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i ); if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i ); if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i ); } return new THREE.BufferAttribute( array, itemSize, attribute.normalized ); } return attribute.clone(); } /* GLTF PARSER */ function GLTFParser( json, extensions, options ) { this.json = json || {}; this.extensions = extensions || {}; this.options = options || {}; // loader object cache this.cache = new GLTFRegistry(); // BufferGeometry caching this.primitiveCache = {}; this.textureLoader = new THREE.TextureLoader( this.options.manager ); this.textureLoader.setCrossOrigin( this.options.crossOrigin ); this.fileLoader = new THREE.FileLoader( this.options.manager ); this.fileLoader.setResponseType( 'arraybuffer' ); if ( this.options.crossOrigin === 'use-credentials' ) { this.fileLoader.setWithCredentials( true ); } } GLTFParser.prototype.parse = function ( onLoad, onError ) { var parser = this; var json = this.json; var extensions = this.extensions; // Clear the loader cache this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse this.markDefs(); Promise.all( [ this.getDependencies( 'scene' ), this.getDependencies( 'animation' ), this.getDependencies( 'camera' ), ] ).then( function ( dependencies ) { var result = { scene: dependencies[ 0 ][ json.scene || 0 ], scenes: dependencies[ 0 ], animations: dependencies[ 1 ], cameras: dependencies[ 2 ], asset: json.asset, parser: parser, userData: {} }; addUnknownExtensionsToUserData( extensions, result, json ); assignExtrasToUserData( result, json ); onLoad( result ); } ).catch( onError ); }; /** * Marks the special nodes/meshes in json for efficient parse. */ GLTFParser.prototype.markDefs = function () { var nodeDefs = this.json.nodes || []; var skinDefs = this.json.skins || []; var meshDefs = this.json.meshes || []; var meshReferences = {}; var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an // Object3D. Use the skins' joint references to mark bones. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { var joints = skinDefs[ skinIndex ].joints; for ( var i = 0, il = joints.length; i < il; i ++ ) { nodeDefs[ joints[ i ] ].isBone = true; } } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To // avoid having more than one THREE.Mesh with the same name, count // references and rename instances below. // // Example: CesiumMilkTruck sample model reuses "Wheel" meshes. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { var nodeDef = nodeDefs[ nodeIndex ]; if ( nodeDef.mesh !== undefined ) { if ( meshReferences[ nodeDef.mesh ] === undefined ) { meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0; } meshReferences[ nodeDef.mesh ] ++; // Nothing in the mesh definition indicates whether it is // a SkinnedMesh or Mesh. Use the node's mesh reference // to mark SkinnedMesh if node has skin. if ( nodeDef.skin !== undefined ) { meshDefs[ nodeDef.mesh ].isSkinnedMesh = true; } } } this.json.meshReferences = meshReferences; this.json.meshUses = meshUses; }; /** * Requests the specified dependency asynchronously, with caching. * @param {string} type * @param {number} index * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>} */ GLTFParser.prototype.getDependency = function ( type, index ) { var cacheKey = type + ':' + index; var dependency = this.cache.get( cacheKey ); if ( ! dependency ) { switch ( type ) { case 'scene': dependency = this.loadScene( index ); break; case 'node': dependency = this.loadNode( index ); break; case 'mesh': dependency = this.loadMesh( index ); break; case 'accessor': dependency = this.loadAccessor( index ); break; case 'bufferView': dependency = this.loadBufferView( index ); break; case 'buffer': dependency = this.loadBuffer( index ); break; case 'material': dependency = this.loadMaterial( index ); break; case 'texture': dependency = this.loadTexture( index ); break; case 'skin': dependency = this.loadSkin( index ); break; case 'animation': dependency = this.loadAnimation( index ); break; case 'camera': dependency = this.loadCamera( index ); break; case 'light': dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index ); break; default: throw new Error( 'Unknown type: ' + type ); } this.cache.add( cacheKey, dependency ); } return dependency; }; /** * Requests all dependencies of the specified type asynchronously, with caching. * @param {string} type * @return {Promise<Array<Object>>} */ GLTFParser.prototype.getDependencies = function ( type ) { var dependencies = this.cache.get( type ); if ( ! dependencies ) { var parser = this; var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || []; dependencies = Promise.all( defs.map( function ( def, index ) { return parser.getDependency( type, index ); } ) ); this.cache.add( type, dependencies ); } return dependencies; }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferIndex * @return {Promise<ArrayBuffer>} */ GLTFParser.prototype.loadBuffer = function ( bufferIndex ) { var bufferDef = this.json.buffers[ bufferIndex ]; var loader = this.fileLoader; if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) { throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' ); } // If present, GLB container is required to be the first buffer. if ( bufferDef.uri === undefined && bufferIndex === 0 ) { return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body ); } var options = this.options; return new Promise( function ( resolve, reject ) { loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () { reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) ); } ); } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferViewIndex * @return {Promise<ArrayBuffer>} */ GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) { var bufferViewDef = this.json.bufferViews[ bufferViewIndex ]; return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) { var byteLength = bufferViewDef.byteLength || 0; var byteOffset = bufferViewDef.byteOffset || 0; return buffer.slice( byteOffset, byteOffset + byteLength ); } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>} */ GLTFParser.prototype.loadAccessor = function ( accessorIndex ) { var parser = this; var json = this.json; var accessorDef = this.json.accessors[ accessorIndex ]; if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) { // Ignore empty accessors, which may be used to declare runtime // information about attributes coming from another source (e.g. Draco // compression extension). return Promise.resolve( null ); } var pendingBufferViews = []; if ( accessorDef.bufferView !== undefined ) { pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) ); } else { pendingBufferViews.push( null ); } if ( accessorDef.sparse !== undefined ) { pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) ); pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) ); } return Promise.all( pendingBufferViews ).then( function ( bufferViews ) { var bufferView = bufferViews[ 0 ]; var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ]; var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. var elementBytes = TypedArray.BYTES_PER_ELEMENT; var itemBytes = elementBytes * itemSize; var byteOffset = accessorDef.byteOffset || 0; var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined; var normalized = accessorDef.normalized === true; var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes. if ( byteStride && byteStride !== itemBytes ) { // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer // This makes sure that IBA.count reflects accessor.count properly var ibSlice = Math.floor( byteOffset / byteStride ); var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; var ib = parser.cache.get( ibCacheKey ); if ( ! ib ) { array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes ); // Integer parameters to IB/IBA are in array elements, not bytes. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes ); parser.cache.add( ibCacheKey, ib ); } bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized ); } else { if ( bufferView === null ) { array = new TypedArray( accessorDef.count * itemSize ); } else { array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize ); } bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized ); } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors if ( accessorDef.sparse !== undefined ) { var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ]; var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices ); var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize ); if ( bufferView !== null ) { // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized ); } for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) { var index = sparseIndices[ i ]; bufferAttribute.setX( index, sparseValues[ i * itemSize ] ); if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] ); if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] ); if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] ); if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' ); } } return bufferAttribute; } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise<THREE.Texture>} */ GLTFParser.prototype.loadTexture = function ( textureIndex ) { var parser = this; var json = this.json; var options = this.options; var textureLoader = this.textureLoader; var URL = window.URL || window.webkitURL; var textureDef = json.textures[ textureIndex ]; var textureExtensions = textureDef.extensions || {}; var source; if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) { source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ]; } else { source = json.images[ textureDef.source ]; } var sourceURI = source.uri; var isObjectURL = false; if ( source.bufferView !== undefined ) { // Load binary image data from bufferView, if provided. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) { isObjectURL = true; var blob = new Blob( [ bufferView ], { type: source.mimeType } ); sourceURI = URL.createObjectURL( blob ); return sourceURI; } ); } return Promise.resolve( sourceURI ).then( function ( sourceURI ) { // Load Texture resource. var loader = options.manager.getHandler( sourceURI ); if ( ! loader ) { loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader : textureLoader; } return new Promise( function ( resolve, reject ) { loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject ); } ); } ).then( function ( texture ) { // Clean up resources and configure Texture. if ( isObjectURL === true ) { URL.revokeObjectURL( sourceURI ); } texture.flipY = false; if ( textureDef.name !== undefined ) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files. if ( source.mimeType in MIME_TYPE_FORMATS ) { texture.format = MIME_TYPE_FORMATS[ source.mimeType ]; } var samplers = json.samplers || {}; var sampler = samplers[ textureDef.sampler ] || {}; texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter; texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter; texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping; texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping; return texture; } ); }; /** * Asynchronously assigns a texture to the given material parameters. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef * @return {Promise} */ GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) { var parser = this; return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) { if ( ! texture.isCompressedTexture ) { switch ( mapName ) { case 'aoMap': case 'emissiveMap': case 'metalnessMap': case 'normalMap': case 'roughnessMap': texture.format = THREE.RGBFormat; break; } } if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) { var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined; if ( transform ) { texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform ); } } materialParams[ mapName ] = texture; } ); }; /** * Assigns final material to a Mesh, Line, or Points instance. The instance * already has a material (generated from the glTF material options alone) * but reuse of the same glTF material may require multiple threejs materials * to accomodate different primitive types, defines, etc. New materials will * be created if necessary, and reused from a cache. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance. */ GLTFParser.prototype.assignFinalMaterial = function ( mesh ) { var geometry = mesh.geometry; var material = mesh.material; var extensions = this.extensions; var useVertexTangents = geometry.attributes.tangent !== undefined; var useVertexColors = geometry.attributes.color !== undefined; var useFlatShading = geometry.attributes.normal === undefined; var useSkinning = mesh.isSkinnedMesh === true; var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0; var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined; if ( mesh.isPoints ) { var cacheKey = 'PointsMaterial:' + material.uuid; var pointsMaterial = this.cache.get( cacheKey ); if ( ! pointsMaterial ) { pointsMaterial = new THREE.PointsMaterial(); THREE.Material.prototype.copy.call( pointsMaterial, material ); pointsMaterial.color.copy( material.color ); pointsMaterial.map = material.map; pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px this.cache.add( cacheKey, pointsMaterial ); } material = pointsMaterial; } else if ( mesh.isLine ) { var cacheKey = 'LineBasicMaterial:' + material.uuid; var lineMaterial = this.cache.get( cacheKey ); if ( ! lineMaterial ) { lineMaterial = new THREE.LineBasicMaterial(); THREE.Material.prototype.copy.call( lineMaterial, material ); lineMaterial.color.copy( material.color ); lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet this.cache.add( cacheKey, lineMaterial ); } material = lineMaterial; } // Clone the material if it will be modified if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) { var cacheKey = 'ClonedMaterial:' + material.uuid + ':'; if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:'; if ( useSkinning ) cacheKey += 'skinning:'; if ( useVertexTangents ) cacheKey += 'vertex-tangents:'; if ( useVertexColors ) cacheKey += 'vertex-colors:'; if ( useFlatShading ) cacheKey += 'flat-shading:'; if ( useMorphTargets ) cacheKey += 'morph-targets:'; if ( useMorphNormals ) cacheKey += 'morph-normals:'; var cachedMaterial = this.cache.get( cacheKey ); if ( ! cachedMaterial ) { cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material ) : material.clone(); if ( useSkinning ) cachedMaterial.skinning = true; if ( useVertexTangents ) cachedMaterial.vertexTangents = true; if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors; if ( useFlatShading ) cachedMaterial.flatShading = true; if ( useMorphTargets ) cachedMaterial.morphTargets = true; if ( useMorphNormals ) cachedMaterial.morphNormals = true; this.cache.add( cacheKey, cachedMaterial ); } material = cachedMaterial; } // workarounds for mesh and geometry if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) { console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' ); geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) ); } if ( material.isGLTFSpecularGlossinessMaterial ) { // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms; } mesh.material = material; }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise<THREE.Material>} */ GLTFParser.prototype.loadMaterial = function ( materialIndex ) { var parser = this; var json = this.json; var extensions = this.extensions; var materialDef = json.materials[ materialIndex ]; var materialType; var materialParams = {}; var materialExtensions = materialDef.extensions || {}; var pending = []; if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) { var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ]; materialType = sgExtension.getMaterialType(); pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) ); } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) { var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ]; materialType = kmuExtension.getMaterialType(); pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) ); } else { // Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material materialType = THREE.MeshStandardMaterial; var metallicRoughness = materialDef.pbrMetallicRoughness || {}; materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { var array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; } if ( metallicRoughness.baseColorTexture !== undefined ) { pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) ); } materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0; materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0; if ( metallicRoughness.metallicRoughnessTexture !== undefined ) { pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) ); pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) ); } } if ( materialDef.doubleSided === true ) { materialParams.side = THREE.DoubleSide; } var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; if ( alphaMode === ALPHA_MODES.BLEND ) { materialParams.transparent = true; } else { materialParams.transparent = false; if ( alphaMode === ALPHA_MODES.MASK ) { materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5; } } if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) ); materialParams.normalScale = new THREE.Vector2( 1, 1 ); if ( materialDef.normalTexture.scale !== undefined ) { materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale ); } } if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) ); if ( materialDef.occlusionTexture.strength !== undefined ) { materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; } } if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) { materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor ); } if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) ); } return Promise.all( pending ).then( function () { var material; if ( materialType === THREE.ShaderMaterial ) { material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams ); } else { material = new materialType( materialParams ); } if ( materialDef.name !== undefined ) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding. if ( material.map ) material.map.encoding = THREE.sRGBEncoding; if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding; if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding; assignExtrasToUserData( material, materialDef ); if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef ); return material; } ); }; /** * @param {THREE.BufferGeometry} geometry * @param {GLTF.Primitive} primitiveDef * @param {GLTFParser} parser * @return {Promise<THREE.BufferGeometry>} */ function addPrimitiveAttributes( geometry, primitiveDef, parser ) { var attributes = primitiveDef.attributes; var pending = []; function assignAttributeAccessor( accessorIndex, attributeName ) { return parser.getDependency( 'accessor', accessorIndex ) .then( function ( accessor ) { geometry.addAttribute( attributeName, accessor ); } ); } for ( var gltfAttributeName in attributes ) { var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension. if ( threeAttributeName in geometry.attributes ) continue; pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) ); } if ( primitiveDef.indices !== undefined && ! geometry.index ) { var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) { geometry.setIndex( accessor ); } ); pending.push( accessor ); } assignExtrasToUserData( geometry, primitiveDef ); return Promise.all( pending ).then( function () { return primitiveDef.targets !== undefined ? addMorphTargets( geometry, primitiveDef.targets, parser ) : geometry; } ); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry * * Creates BufferGeometries from primitives. * * @param {Array<GLTF.Primitive>} primitives * @return {Promise<Array<THREE.BufferGeometry>>} */ GLTFParser.prototype.loadGeometries = function ( primitives ) { var parser = this; var extensions = this.extensions; var cache = this.primitiveCache; function createDracoPrimitive( primitive ) { return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] .decodePrimitive( primitive, parser ) .then( function ( geometry ) { return addPrimitiveAttributes( geometry, primitive, parser ); } ); } var pending = []; for ( var i = 0, il = primitives.length; i < il; i ++ ) { var primitive = primitives[ i ]; var cacheKey = createPrimitiveKey( primitive ); // See if we've already created this geometry var cached = cache[ cacheKey ]; if ( cached ) { // Use the cached geometry if it exists pending.push( cached.promise ); } else { var geometryPromise; if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) { // Use DRACO geometry if available geometryPromise = createDracoPrimitive( primitive ); } else { // Otherwise create a new geometry geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser ); } // Cache this geometry cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise }; pending.push( geometryPromise ); } } return Promise.all( pending ); }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * @param {number} meshIndex * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>} */ GLTFParser.prototype.loadMesh = function ( meshIndex ) { var parser = this; var json = this.json; var meshDef = json.meshes[ meshIndex ]; var primitives = meshDef.primitives; var pending = []; for ( var i = 0, il = primitives.length; i < il; i ++ ) { var material = primitives[ i ].material === undefined ? createDefaultMaterial() : this.getDependency( 'material', primitives[ i ].material ); pending.push( material ); } return Promise.all( pending ).then( function ( originalMaterials ) { return parser.loadGeometries( primitives ).then( function ( geometries ) { var meshes = []; for ( var i = 0, il = geometries.length; i < il; i ++ ) { var geometry = geometries[ i ]; var primitive = primitives[ i ]; // 1. create Mesh var mesh; var material = originalMaterials[ i ]; if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined ) { // .isSkinnedMesh isn't in glTF spec. See .markDefs() mesh = meshDef.isSkinnedMesh === true ? new THREE.SkinnedMesh( geometry, material ) : new THREE.Mesh( geometry, material ); if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) { // we normalize floating point skin weight array to fix malformed assets (see #15319) // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs mesh.normalizeSkinWeights(); } if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) { mesh.drawMode = THREE.TriangleStripDrawMode; } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) { mesh.drawMode = THREE.TriangleFanDrawMode; } } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) { mesh = new THREE.LineSegments( geometry, material ); } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) { mesh = new THREE.Line( geometry, material ); } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) { mesh = new THREE.LineLoop( geometry, material ); } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) { mesh = new THREE.Points( geometry, material ); } else { throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode ); } if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) { updateMorphTargets( mesh, meshDef ); } mesh.name = meshDef.name || ( 'mesh_' + meshIndex ); if ( geometries.length > 1 ) mesh.name += '_' + i; assignExtrasToUserData( mesh, meshDef ); parser.assignFinalMaterial( mesh ); meshes.push( mesh ); } if ( meshes.length === 1 ) { return meshes[ 0 ]; } var group = new THREE.Group(); for ( var i = 0, il = meshes.length; i < il; i ++ ) { group.add( meshes[ i ] ); } return group; } ); } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * @param {number} cameraIndex * @return {Promise<THREE.Camera>} */ GLTFParser.prototype.loadCamera = function ( cameraIndex ) { var camera; var cameraDef = this.json.cameras[ cameraIndex ]; var params = cameraDef[ cameraDef.type ]; if ( ! params ) { console.warn( 'THREE.GLTFLoader: Missing camera parameters.' ); return; } if ( cameraDef.type === 'perspective' ) { camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 ); } else if ( cameraDef.type === 'orthographic' ) { camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar ); } if ( cameraDef.name !== undefined ) camera.name = cameraDef.name; assignExtrasToUserData( camera, cameraDef ); return Promise.resolve( camera ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * @param {number} skinIndex * @return {Promise<Object>} */ GLTFParser.prototype.loadSkin = function ( skinIndex ) { var skinDef = this.json.skins[ skinIndex ]; var skinEntry = { joints: skinDef.joints }; if ( skinDef.inverseBindMatrices === undefined ) { return Promise.resolve( skinEntry ); } return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) { skinEntry.inverseBindMatrices = accessor; return skinEntry; } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise<THREE.AnimationClip>} */ GLTFParser.prototype.loadAnimation = function ( animationIndex ) { var json = this.json; var animationDef = json.animations[ animationIndex ]; var pendingNodes = []; var pendingInputAccessors = []; var pendingOutputAccessors = []; var pendingSamplers = []; var pendingTargets = []; for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) { var channel = animationDef.channels[ i ]; var sampler = animationDef.samplers[ channel.sampler ]; var target = channel.target; var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input; var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output; pendingNodes.push( this.getDependency( 'node', name ) ); pendingInputAccessors.push( this.getDependency( 'accessor', input ) ); pendingOutputAccessors.push( this.getDependency( 'accessor', output ) ); pendingSamplers.push( sampler ); pendingTargets.push( target ); } return Promise.all( [ Promise.all( pendingNodes ), Promise.all( pendingInputAccessors ), Promise.all( pendingOutputAccessors ), Promise.all( pendingSamplers ), Promise.all( pendingTargets ) ] ).then( function ( dependencies ) { var nodes = dependencies[ 0 ]; var inputAccessors = dependencies[ 1 ]; var outputAccessors = dependencies[ 2 ]; var samplers = dependencies[ 3 ]; var targets = dependencies[ 4 ]; var tracks = []; for ( var i = 0, il = nodes.length; i < il; i ++ ) { var node = nodes[ i ]; var inputAccessor = inputAccessors[ i ]; var outputAccessor = outputAccessors[ i ]; var sampler = samplers[ i ]; var target = targets[ i ]; if ( node === undefined ) continue; node.updateMatrix(); node.matrixAutoUpdate = true; var TypedKeyframeTrack; switch ( PATH_PROPERTIES[ target.path ] ) { case PATH_PROPERTIES.weights: TypedKeyframeTrack = THREE.NumberKeyframeTrack; break; case PATH_PROPERTIES.rotation: TypedKeyframeTrack = THREE.QuaternionKeyframeTrack; break; case PATH_PROPERTIES.position: case PATH_PROPERTIES.scale: default: TypedKeyframeTrack = THREE.VectorKeyframeTrack; break; } var targetName = node.name ? node.name : node.uuid; var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear; var targetNames = []; if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) { // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh. node.traverse( function ( object ) { if ( object.isMesh === true && object.morphTargetInfluences ) { targetNames.push( object.name ? object.name : object.uuid ); } } ); } else { targetNames.push( targetName ); } var outputArray = outputAccessor.array; if ( outputAccessor.normalized ) { var scale; if ( outputArray.constructor === Int8Array ) { scale = 1 / 127; } else if ( outputArray.constructor === Uint8Array ) { scale = 1 / 255; } else if ( outputArray.constructor == Int16Array ) { scale = 1 / 32767; } else if ( outputArray.constructor === Uint16Array ) { scale = 1 / 65535; } else { throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' ); } var scaled = new Float32Array( outputArray.length ); for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) { scaled[ j ] = outputArray[ j ] * scale; } outputArray = scaled; } for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) { var track = new TypedKeyframeTrack( targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ], inputAccessor.array, outputArray, interpolation ); // Override interpolation with custom factory method. if ( sampler.interpolation === 'CUBICSPLINE' ) { track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) { // A CUBICSPLINE keyframe in glTF has three output values for each input value, // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize() // must be divided by three to get the interpolant's sampleSize argument. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result ); }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; } tracks.push( track ); } } var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex; return new THREE.AnimationClip( name, undefined, tracks ); } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy * @param {number} nodeIndex * @return {Promise<THREE.Object3D>} */ GLTFParser.prototype.loadNode = function ( nodeIndex ) { var json = this.json; var extensions = this.extensions; var parser = this; var meshReferences = json.meshReferences; var meshUses = json.meshUses; var nodeDef = json.nodes[ nodeIndex ]; return ( function () { var pending = []; if ( nodeDef.mesh !== undefined ) { pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) { var node; if ( meshReferences[ nodeDef.mesh ] > 1 ) { var instanceNum = meshUses[ nodeDef.mesh ] ++; node = mesh.clone(); node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness node.onBeforeRender = mesh.onBeforeRender; for ( var i = 0, il = node.children.length; i < il; i ++ ) { node.children[ i ].name += '_instance_' + instanceNum; node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender; } } else { node = mesh; } // if weights are provided on the node, override weights on the mesh. if ( nodeDef.weights !== undefined ) { node.traverse( function ( o ) { if ( ! o.isMesh ) return; for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) { o.morphTargetInfluences[ i ] = nodeDef.weights[ i ]; } } ); } return node; } ) ); } if ( nodeDef.camera !== undefined ) { pending.push( parser.getDependency( 'camera', nodeDef.camera ) ); } if ( nodeDef.extensions && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) { pending.push( parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ) ); } return Promise.all( pending ); }() ).then( function ( objects ) { var node; // .isBone isn't in glTF spec. See .markDefs if ( nodeDef.isBone === true ) { node = new THREE.Bone(); } else if ( objects.length > 1 ) { node = new THREE.Group(); } else if ( objects.length === 1 ) { node = objects[ 0 ]; } else { node = new THREE.Object3D(); } if ( node !== objects[ 0 ] ) { for ( var i = 0, il = objects.length; i < il; i ++ ) { node.add( objects[ i ] ); } } if ( nodeDef.name !== undefined ) { node.userData.name = nodeDef.name; node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name ); } assignExtrasToUserData( node, nodeDef ); if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef ); if ( nodeDef.matrix !== undefined ) { var matrix = new THREE.Matrix4(); matrix.fromArray( nodeDef.matrix ); node.applyMatrix( matrix ); } else { if ( nodeDef.translation !== undefined ) { node.position.fromArray( nodeDef.translation ); } if ( nodeDef.rotation !== undefined ) { node.quaternion.fromArray( nodeDef.rotation ); } if ( nodeDef.scale !== undefined ) { node.scale.fromArray( nodeDef.scale ); } } return node; } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * @param {number} sceneIndex * @return {Promise<THREE.Scene>} */ GLTFParser.prototype.loadScene = function () { // scene node hierachy builder function buildNodeHierachy( nodeId, parentObject, json, parser ) { var nodeDef = json.nodes[ nodeId ]; return parser.getDependency( 'node', nodeId ).then( function ( node ) { if ( nodeDef.skin === undefined ) return node; // build skeleton here as well var skinEntry; return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) { skinEntry = skin; var pendingJoints = []; for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) { pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) ); } return Promise.all( pendingJoints ); } ).then( function ( jointNodes ) { node.traverse( function ( mesh ) { if ( ! mesh.isMesh ) return; var bones = []; var boneInverses = []; for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) { var jointNode = jointNodes[ j ]; if ( jointNode ) { bones.push( jointNode ); var mat = new THREE.Matrix4(); if ( skinEntry.inverseBindMatrices !== undefined ) { mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 ); } boneInverses.push( mat ); } else { console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] ); } } mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld ); } ); return node; } ); } ).then( function ( node ) { // build node hierachy parentObject.add( node ); var pending = []; if ( nodeDef.children ) { var children = nodeDef.children; for ( var i = 0, il = children.length; i < il; i ++ ) { var child = children[ i ]; pending.push( buildNodeHierachy( child, node, json, parser ) ); } } return Promise.all( pending ); } ); } return function loadScene( sceneIndex ) { var json = this.json; var extensions = this.extensions; var sceneDef = this.json.scenes[ sceneIndex ]; var parser = this; var scene = new THREE.Scene(); if ( sceneDef.name !== undefined ) scene.name = sceneDef.name; assignExtrasToUserData( scene, sceneDef ); if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef ); var nodeIds = sceneDef.nodes || []; var pending = []; for ( var i = 0, il = nodeIds.length; i < il; i ++ ) { pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) ); } return Promise.all( pending ).then( function () { return scene; } ); }; }(); return GLTFLoader; } )();
examples/js/loaders/GLTFLoader.js
/** * @author Rich Tibbett / https://github.com/richtr * @author mrdoob / http://mrdoob.com/ * @author Tony Parisi / http://www.tonyparisi.com/ * @author Takahiro / https://github.com/takahirox * @author Don McCurdy / https://www.donmccurdy.com */ THREE.GLTFLoader = ( function () { function GLTFLoader( manager ) { THREE.Loader.call( this, manager ); this.dracoLoader = null; this.ddsLoader = null; } GLTFLoader.prototype = Object.assign( Object.create( THREE.Loader.prototype ), { constructor: GLTFLoader, load: function ( url, onLoad, onProgress, onError ) { var scope = this; var resourcePath; if ( this.resourcePath !== '' ) { resourcePath = this.resourcePath; } else if ( this.path !== '' ) { resourcePath = this.path; } else { resourcePath = THREE.LoaderUtils.extractUrlBase( url ); } // Tells the LoadingManager to track an extra item, which resolves after // the model is fully loaded. This means the count of items loaded will // be incorrect, but ensures manager.onLoad() does not fire early. scope.manager.itemStart( url ); var _onError = function ( e ) { if ( onError ) { onError( e ); } else { console.error( e ); } scope.manager.itemError( url ); scope.manager.itemEnd( url ); }; var loader = new THREE.FileLoader( scope.manager ); loader.setPath( this.path ); loader.setResponseType( 'arraybuffer' ); if ( scope.crossOrigin === 'use-credentials' ) { loader.setWithCredentials( true ); } loader.load( url, function ( data ) { try { scope.parse( data, resourcePath, function ( gltf ) { onLoad( gltf ); scope.manager.itemEnd( url ); }, _onError ); } catch ( e ) { _onError( e ); } }, onProgress, _onError ); }, setDRACOLoader: function ( dracoLoader ) { this.dracoLoader = dracoLoader; return this; }, setDDSLoader: function ( ddsLoader ) { this.ddsLoader = ddsLoader; return this; }, parse: function ( data, path, onLoad, onError ) { var content; var extensions = {}; if ( typeof data === 'string' ) { content = data; } else { var magic = THREE.LoaderUtils.decodeText( new Uint8Array( data, 0, 4 ) ); if ( magic === BINARY_EXTENSION_HEADER_MAGIC ) { try { extensions[ EXTENSIONS.KHR_BINARY_GLTF ] = new GLTFBinaryExtension( data ); } catch ( error ) { if ( onError ) onError( error ); return; } content = extensions[ EXTENSIONS.KHR_BINARY_GLTF ].content; } else { content = THREE.LoaderUtils.decodeText( new Uint8Array( data ) ); } } var json = JSON.parse( content ); if ( json.asset === undefined || json.asset.version[ 0 ] < 2 ) { if ( onError ) onError( new Error( 'THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported. Use LegacyGLTFLoader instead.' ) ); return; } if ( json.extensionsUsed ) { for ( var i = 0; i < json.extensionsUsed.length; ++ i ) { var extensionName = json.extensionsUsed[ i ]; var extensionsRequired = json.extensionsRequired || []; switch ( extensionName ) { case EXTENSIONS.KHR_LIGHTS_PUNCTUAL: extensions[ extensionName ] = new GLTFLightsExtension( json ); break; case EXTENSIONS.KHR_MATERIALS_UNLIT: extensions[ extensionName ] = new GLTFMaterialsUnlitExtension(); break; case EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: extensions[ extensionName ] = new GLTFMaterialsPbrSpecularGlossinessExtension(); break; case EXTENSIONS.KHR_DRACO_MESH_COMPRESSION: extensions[ extensionName ] = new GLTFDracoMeshCompressionExtension( json, this.dracoLoader ); break; case EXTENSIONS.MSFT_TEXTURE_DDS: extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] = new GLTFTextureDDSExtension( this.ddsLoader ); break; case EXTENSIONS.KHR_TEXTURE_TRANSFORM: extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] = new GLTFTextureTransformExtension(); break; default: if ( extensionsRequired.indexOf( extensionName ) >= 0 ) { console.warn( 'THREE.GLTFLoader: Unknown extension "' + extensionName + '".' ); } } } } var parser = new GLTFParser( json, extensions, { path: path || this.resourcePath || '', crossOrigin: this.crossOrigin, manager: this.manager } ); parser.parse( onLoad, onError ); } } ); /* GLTFREGISTRY */ function GLTFRegistry() { var objects = {}; return { get: function ( key ) { return objects[ key ]; }, add: function ( key, object ) { objects[ key ] = object; }, remove: function ( key ) { delete objects[ key ]; }, removeAll: function () { objects = {}; } }; } /*********************************/ /********** EXTENSIONS ***********/ /*********************************/ var EXTENSIONS = { KHR_BINARY_GLTF: 'KHR_binary_glTF', KHR_DRACO_MESH_COMPRESSION: 'KHR_draco_mesh_compression', KHR_LIGHTS_PUNCTUAL: 'KHR_lights_punctual', KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS: 'KHR_materials_pbrSpecularGlossiness', KHR_MATERIALS_UNLIT: 'KHR_materials_unlit', KHR_TEXTURE_TRANSFORM: 'KHR_texture_transform', MSFT_TEXTURE_DDS: 'MSFT_texture_dds' }; /** * DDS Texture Extension * * Specification: * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds * */ function GLTFTextureDDSExtension( ddsLoader ) { if ( ! ddsLoader ) { throw new Error( 'THREE.GLTFLoader: Attempting to load .dds texture without importing THREE.DDSLoader' ); } this.name = EXTENSIONS.MSFT_TEXTURE_DDS; this.ddsLoader = ddsLoader; } /** * Lights Extension * * Specification: PENDING */ function GLTFLightsExtension( json ) { this.name = EXTENSIONS.KHR_LIGHTS_PUNCTUAL; var extension = ( json.extensions && json.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] ) || {}; this.lightDefs = extension.lights || []; } GLTFLightsExtension.prototype.loadLight = function ( lightIndex ) { var lightDef = this.lightDefs[ lightIndex ]; var lightNode; var color = new THREE.Color( 0xffffff ); if ( lightDef.color !== undefined ) color.fromArray( lightDef.color ); var range = lightDef.range !== undefined ? lightDef.range : 0; switch ( lightDef.type ) { case 'directional': lightNode = new THREE.DirectionalLight( color ); lightNode.target.position.set( 0, 0, - 1 ); lightNode.add( lightNode.target ); break; case 'point': lightNode = new THREE.PointLight( color ); lightNode.distance = range; break; case 'spot': lightNode = new THREE.SpotLight( color ); lightNode.distance = range; // Handle spotlight properties. lightDef.spot = lightDef.spot || {}; lightDef.spot.innerConeAngle = lightDef.spot.innerConeAngle !== undefined ? lightDef.spot.innerConeAngle : 0; lightDef.spot.outerConeAngle = lightDef.spot.outerConeAngle !== undefined ? lightDef.spot.outerConeAngle : Math.PI / 4.0; lightNode.angle = lightDef.spot.outerConeAngle; lightNode.penumbra = 1.0 - lightDef.spot.innerConeAngle / lightDef.spot.outerConeAngle; lightNode.target.position.set( 0, 0, - 1 ); lightNode.add( lightNode.target ); break; default: throw new Error( 'THREE.GLTFLoader: Unexpected light type, "' + lightDef.type + '".' ); } // Some lights (e.g. spot) default to a position other than the origin. Reset the position // here, because node-level parsing will only override position if explicitly specified. lightNode.position.set( 0, 0, 0 ); lightNode.decay = 2; if ( lightDef.intensity !== undefined ) lightNode.intensity = lightDef.intensity; lightNode.name = lightDef.name || ( 'light_' + lightIndex ); return Promise.resolve( lightNode ); }; /** * Unlit Materials Extension (pending) * * PR: https://github.com/KhronosGroup/glTF/pull/1163 */ function GLTFMaterialsUnlitExtension() { this.name = EXTENSIONS.KHR_MATERIALS_UNLIT; } GLTFMaterialsUnlitExtension.prototype.getMaterialType = function () { return THREE.MeshBasicMaterial; }; GLTFMaterialsUnlitExtension.prototype.extendParams = function ( materialParams, materialDef, parser ) { var pending = []; materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; var metallicRoughness = materialDef.pbrMetallicRoughness; if ( metallicRoughness ) { if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { var array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; } if ( metallicRoughness.baseColorTexture !== undefined ) { pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) ); } } return Promise.all( pending ); }; /* BINARY EXTENSION */ var BINARY_EXTENSION_HEADER_MAGIC = 'glTF'; var BINARY_EXTENSION_HEADER_LENGTH = 12; var BINARY_EXTENSION_CHUNK_TYPES = { JSON: 0x4E4F534A, BIN: 0x004E4942 }; function GLTFBinaryExtension( data ) { this.name = EXTENSIONS.KHR_BINARY_GLTF; this.content = null; this.body = null; var headerView = new DataView( data, 0, BINARY_EXTENSION_HEADER_LENGTH ); this.header = { magic: THREE.LoaderUtils.decodeText( new Uint8Array( data.slice( 0, 4 ) ) ), version: headerView.getUint32( 4, true ), length: headerView.getUint32( 8, true ) }; if ( this.header.magic !== BINARY_EXTENSION_HEADER_MAGIC ) { throw new Error( 'THREE.GLTFLoader: Unsupported glTF-Binary header.' ); } else if ( this.header.version < 2.0 ) { throw new Error( 'THREE.GLTFLoader: Legacy binary file detected. Use LegacyGLTFLoader instead.' ); } var chunkView = new DataView( data, BINARY_EXTENSION_HEADER_LENGTH ); var chunkIndex = 0; while ( chunkIndex < chunkView.byteLength ) { var chunkLength = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; var chunkType = chunkView.getUint32( chunkIndex, true ); chunkIndex += 4; if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.JSON ) { var contentArray = new Uint8Array( data, BINARY_EXTENSION_HEADER_LENGTH + chunkIndex, chunkLength ); this.content = THREE.LoaderUtils.decodeText( contentArray ); } else if ( chunkType === BINARY_EXTENSION_CHUNK_TYPES.BIN ) { var byteOffset = BINARY_EXTENSION_HEADER_LENGTH + chunkIndex; this.body = data.slice( byteOffset, byteOffset + chunkLength ); } // Clients must ignore chunks with unknown types. chunkIndex += chunkLength; } if ( this.content === null ) { throw new Error( 'THREE.GLTFLoader: JSON content not found.' ); } } /** * DRACO Mesh Compression Extension * * Specification: https://github.com/KhronosGroup/glTF/pull/874 */ function GLTFDracoMeshCompressionExtension( json, dracoLoader ) { if ( ! dracoLoader ) { throw new Error( 'THREE.GLTFLoader: No DRACOLoader instance provided.' ); } this.name = EXTENSIONS.KHR_DRACO_MESH_COMPRESSION; this.json = json; this.dracoLoader = dracoLoader; } GLTFDracoMeshCompressionExtension.prototype.decodePrimitive = function ( primitive, parser ) { var json = this.json; var dracoLoader = this.dracoLoader; var bufferViewIndex = primitive.extensions[ this.name ].bufferView; var gltfAttributeMap = primitive.extensions[ this.name ].attributes; var threeAttributeMap = {}; var attributeNormalizedMap = {}; var attributeTypeMap = {}; for ( var attributeName in gltfAttributeMap ) { var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); threeAttributeMap[ threeAttributeName ] = gltfAttributeMap[ attributeName ]; } for ( attributeName in primitive.attributes ) { var threeAttributeName = ATTRIBUTES[ attributeName ] || attributeName.toLowerCase(); if ( gltfAttributeMap[ attributeName ] !== undefined ) { var accessorDef = json.accessors[ primitive.attributes[ attributeName ] ]; var componentType = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; attributeTypeMap[ threeAttributeName ] = componentType; attributeNormalizedMap[ threeAttributeName ] = accessorDef.normalized === true; } } return parser.getDependency( 'bufferView', bufferViewIndex ).then( function ( bufferView ) { return new Promise( function ( resolve ) { dracoLoader.decodeDracoFile( bufferView, function ( geometry ) { for ( var attributeName in geometry.attributes ) { var attribute = geometry.attributes[ attributeName ]; var normalized = attributeNormalizedMap[ attributeName ]; if ( normalized !== undefined ) attribute.normalized = normalized; } resolve( geometry ); }, threeAttributeMap, attributeTypeMap ); } ); } ); }; /** * Texture Transform Extension * * Specification: */ function GLTFTextureTransformExtension() { this.name = EXTENSIONS.KHR_TEXTURE_TRANSFORM; } GLTFTextureTransformExtension.prototype.extendTexture = function ( texture, transform ) { texture = texture.clone(); if ( transform.offset !== undefined ) { texture.offset.fromArray( transform.offset ); } if ( transform.rotation !== undefined ) { texture.rotation = transform.rotation; } if ( transform.scale !== undefined ) { texture.repeat.fromArray( transform.scale ); } if ( transform.texCoord !== undefined ) { console.warn( 'THREE.GLTFLoader: Custom UV sets in "' + this.name + '" extension not yet supported.' ); } texture.needsUpdate = true; return texture; }; /** * Specular-Glossiness Extension * * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness */ function GLTFMaterialsPbrSpecularGlossinessExtension() { return { name: EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS, specularGlossinessParams: [ 'color', 'map', 'lightMap', 'lightMapIntensity', 'aoMap', 'aoMapIntensity', 'emissive', 'emissiveIntensity', 'emissiveMap', 'bumpMap', 'bumpScale', 'normalMap', 'displacementMap', 'displacementScale', 'displacementBias', 'specularMap', 'specular', 'glossinessMap', 'glossiness', 'alphaMap', 'envMap', 'envMapIntensity', 'refractionRatio', ], getMaterialType: function () { return THREE.ShaderMaterial; }, extendParams: function ( materialParams, materialDef, parser ) { var pbrSpecularGlossiness = materialDef.extensions[ this.name ]; var shader = THREE.ShaderLib[ 'standard' ]; var uniforms = THREE.UniformsUtils.clone( shader.uniforms ); var specularMapParsFragmentChunk = [ '#ifdef USE_SPECULARMAP', ' uniform sampler2D specularMap;', '#endif' ].join( '\n' ); var glossinessMapParsFragmentChunk = [ '#ifdef USE_GLOSSINESSMAP', ' uniform sampler2D glossinessMap;', '#endif' ].join( '\n' ); var specularMapFragmentChunk = [ 'vec3 specularFactor = specular;', '#ifdef USE_SPECULARMAP', ' vec4 texelSpecular = texture2D( specularMap, vUv );', ' texelSpecular = sRGBToLinear( texelSpecular );', ' // reads channel RGB, compatible with a glTF Specular-Glossiness (RGBA) texture', ' specularFactor *= texelSpecular.rgb;', '#endif' ].join( '\n' ); var glossinessMapFragmentChunk = [ 'float glossinessFactor = glossiness;', '#ifdef USE_GLOSSINESSMAP', ' vec4 texelGlossiness = texture2D( glossinessMap, vUv );', ' // reads channel A, compatible with a glTF Specular-Glossiness (RGBA) texture', ' glossinessFactor *= texelGlossiness.a;', '#endif' ].join( '\n' ); var lightPhysicalFragmentChunk = [ 'PhysicalMaterial material;', 'material.diffuseColor = diffuseColor.rgb;', 'material.specularRoughness = clamp( 1.0 - glossinessFactor, 0.04, 1.0 );', 'material.specularColor = specularFactor.rgb;', ].join( '\n' ); var fragmentShader = shader.fragmentShader .replace( 'uniform float roughness;', 'uniform vec3 specular;' ) .replace( 'uniform float metalness;', 'uniform float glossiness;' ) .replace( '#include <roughnessmap_pars_fragment>', specularMapParsFragmentChunk ) .replace( '#include <metalnessmap_pars_fragment>', glossinessMapParsFragmentChunk ) .replace( '#include <roughnessmap_fragment>', specularMapFragmentChunk ) .replace( '#include <metalnessmap_fragment>', glossinessMapFragmentChunk ) .replace( '#include <lights_physical_fragment>', lightPhysicalFragmentChunk ); delete uniforms.roughness; delete uniforms.metalness; delete uniforms.roughnessMap; delete uniforms.metalnessMap; uniforms.specular = { value: new THREE.Color().setHex( 0x111111 ) }; uniforms.glossiness = { value: 0.5 }; uniforms.specularMap = { value: null }; uniforms.glossinessMap = { value: null }; materialParams.vertexShader = shader.vertexShader; materialParams.fragmentShader = fragmentShader; materialParams.uniforms = uniforms; materialParams.defines = { 'STANDARD': '' }; materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; var pending = []; if ( Array.isArray( pbrSpecularGlossiness.diffuseFactor ) ) { var array = pbrSpecularGlossiness.diffuseFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; } if ( pbrSpecularGlossiness.diffuseTexture !== undefined ) { pending.push( parser.assignTexture( materialParams, 'map', pbrSpecularGlossiness.diffuseTexture ) ); } materialParams.emissive = new THREE.Color( 0.0, 0.0, 0.0 ); materialParams.glossiness = pbrSpecularGlossiness.glossinessFactor !== undefined ? pbrSpecularGlossiness.glossinessFactor : 1.0; materialParams.specular = new THREE.Color( 1.0, 1.0, 1.0 ); if ( Array.isArray( pbrSpecularGlossiness.specularFactor ) ) { materialParams.specular.fromArray( pbrSpecularGlossiness.specularFactor ); } if ( pbrSpecularGlossiness.specularGlossinessTexture !== undefined ) { var specGlossMapDef = pbrSpecularGlossiness.specularGlossinessTexture; pending.push( parser.assignTexture( materialParams, 'glossinessMap', specGlossMapDef ) ); pending.push( parser.assignTexture( materialParams, 'specularMap', specGlossMapDef ) ); } return Promise.all( pending ); }, createMaterial: function ( params ) { // setup material properties based on MeshStandardMaterial for Specular-Glossiness var material = new THREE.ShaderMaterial( { defines: params.defines, vertexShader: params.vertexShader, fragmentShader: params.fragmentShader, uniforms: params.uniforms, fog: true, lights: true, opacity: params.opacity, transparent: params.transparent } ); material.isGLTFSpecularGlossinessMaterial = true; material.color = params.color; material.map = params.map === undefined ? null : params.map; material.lightMap = null; material.lightMapIntensity = 1.0; material.aoMap = params.aoMap === undefined ? null : params.aoMap; material.aoMapIntensity = 1.0; material.emissive = params.emissive; material.emissiveIntensity = 1.0; material.emissiveMap = params.emissiveMap === undefined ? null : params.emissiveMap; material.bumpMap = params.bumpMap === undefined ? null : params.bumpMap; material.bumpScale = 1; material.normalMap = params.normalMap === undefined ? null : params.normalMap; if ( params.normalScale ) material.normalScale = params.normalScale; material.displacementMap = null; material.displacementScale = 1; material.displacementBias = 0; material.specularMap = params.specularMap === undefined ? null : params.specularMap; material.specular = params.specular; material.glossinessMap = params.glossinessMap === undefined ? null : params.glossinessMap; material.glossiness = params.glossiness; material.alphaMap = null; material.envMap = params.envMap === undefined ? null : params.envMap; material.envMapIntensity = 1.0; material.refractionRatio = 0.98; material.extensions.derivatives = true; return material; }, /** * Clones a GLTFSpecularGlossinessMaterial instance. The ShaderMaterial.copy() method can * copy only properties it knows about or inherits, and misses many properties that would * normally be defined by MeshStandardMaterial. * * This method allows GLTFSpecularGlossinessMaterials to be cloned in the process of * loading a glTF model, but cloning later (e.g. by the user) would require these changes * AND also updating `.onBeforeRender` on the parent mesh. * * @param {THREE.ShaderMaterial} source * @return {THREE.ShaderMaterial} */ cloneMaterial: function ( source ) { var target = source.clone(); target.isGLTFSpecularGlossinessMaterial = true; var params = this.specularGlossinessParams; for ( var i = 0, il = params.length; i < il; i ++ ) { var value = source[ params[ i ] ]; target[ params[ i ] ] = ( value && value.isColor ) ? value.clone() : value; } return target; }, // Here's based on refreshUniformsCommon() and refreshUniformsStandard() in WebGLRenderer. refreshUniforms: function ( renderer, scene, camera, geometry, material ) { if ( material.isGLTFSpecularGlossinessMaterial !== true ) { return; } var uniforms = material.uniforms; var defines = material.defines; uniforms.opacity.value = material.opacity; uniforms.diffuse.value.copy( material.color ); uniforms.emissive.value.copy( material.emissive ).multiplyScalar( material.emissiveIntensity ); uniforms.map.value = material.map; uniforms.specularMap.value = material.specularMap; uniforms.alphaMap.value = material.alphaMap; uniforms.lightMap.value = material.lightMap; uniforms.lightMapIntensity.value = material.lightMapIntensity; uniforms.aoMap.value = material.aoMap; uniforms.aoMapIntensity.value = material.aoMapIntensity; // uv repeat and offset setting priorities // 1. color map // 2. specular map // 3. normal map // 4. bump map // 5. alpha map // 6. emissive map var uvScaleMap; if ( material.map ) { uvScaleMap = material.map; } else if ( material.specularMap ) { uvScaleMap = material.specularMap; } else if ( material.displacementMap ) { uvScaleMap = material.displacementMap; } else if ( material.normalMap ) { uvScaleMap = material.normalMap; } else if ( material.bumpMap ) { uvScaleMap = material.bumpMap; } else if ( material.glossinessMap ) { uvScaleMap = material.glossinessMap; } else if ( material.alphaMap ) { uvScaleMap = material.alphaMap; } else if ( material.emissiveMap ) { uvScaleMap = material.emissiveMap; } if ( uvScaleMap !== undefined ) { // backwards compatibility if ( uvScaleMap.isWebGLRenderTarget ) { uvScaleMap = uvScaleMap.texture; } if ( uvScaleMap.matrixAutoUpdate === true ) { uvScaleMap.updateMatrix(); } uniforms.uvTransform.value.copy( uvScaleMap.matrix ); } if ( material.envMap ) { uniforms.envMap.value = material.envMap; uniforms.envMapIntensity.value = material.envMapIntensity; // don't flip CubeTexture envMaps, flip everything else: // WebGLRenderTargetCube will be flipped for backwards compatibility // WebGLRenderTargetCube.texture will be flipped because it's a Texture and NOT a CubeTexture // this check must be handled differently, or removed entirely, if WebGLRenderTargetCube uses a CubeTexture in the future uniforms.flipEnvMap.value = material.envMap.isCubeTexture ? - 1 : 1; uniforms.reflectivity.value = material.reflectivity; uniforms.refractionRatio.value = material.refractionRatio; uniforms.maxMipLevel.value = renderer.properties.get( material.envMap ).__maxMipLevel; } uniforms.specular.value.copy( material.specular ); uniforms.glossiness.value = material.glossiness; uniforms.glossinessMap.value = material.glossinessMap; uniforms.emissiveMap.value = material.emissiveMap; uniforms.bumpMap.value = material.bumpMap; uniforms.normalMap.value = material.normalMap; uniforms.displacementMap.value = material.displacementMap; uniforms.displacementScale.value = material.displacementScale; uniforms.displacementBias.value = material.displacementBias; if ( uniforms.glossinessMap.value !== null && defines.USE_GLOSSINESSMAP === undefined ) { defines.USE_GLOSSINESSMAP = ''; // set USE_ROUGHNESSMAP to enable vUv defines.USE_ROUGHNESSMAP = ''; } if ( uniforms.glossinessMap.value === null && defines.USE_GLOSSINESSMAP !== undefined ) { delete defines.USE_GLOSSINESSMAP; delete defines.USE_ROUGHNESSMAP; } } }; } /*********************************/ /********** INTERPOLATION ********/ /*********************************/ // Spline Interpolation // Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#appendix-c-spline-interpolation function GLTFCubicSplineInterpolant( parameterPositions, sampleValues, sampleSize, resultBuffer ) { THREE.Interpolant.call( this, parameterPositions, sampleValues, sampleSize, resultBuffer ); } GLTFCubicSplineInterpolant.prototype = Object.create( THREE.Interpolant.prototype ); GLTFCubicSplineInterpolant.prototype.constructor = GLTFCubicSplineInterpolant; GLTFCubicSplineInterpolant.prototype.copySampleValue_ = function ( index ) { // Copies a sample value to the result buffer. See description of glTF // CUBICSPLINE values layout in interpolate_() function below. var result = this.resultBuffer, values = this.sampleValues, valueSize = this.valueSize, offset = index * valueSize * 3 + valueSize; for ( var i = 0; i !== valueSize; i ++ ) { result[ i ] = values[ offset + i ]; } return result; }; GLTFCubicSplineInterpolant.prototype.beforeStart_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; GLTFCubicSplineInterpolant.prototype.afterEnd_ = GLTFCubicSplineInterpolant.prototype.copySampleValue_; GLTFCubicSplineInterpolant.prototype.interpolate_ = function ( i1, t0, t, t1 ) { var result = this.resultBuffer; var values = this.sampleValues; var stride = this.valueSize; var stride2 = stride * 2; var stride3 = stride * 3; var td = t1 - t0; var p = ( t - t0 ) / td; var pp = p * p; var ppp = pp * p; var offset1 = i1 * stride3; var offset0 = offset1 - stride3; var s2 = - 2 * ppp + 3 * pp; var s3 = ppp - pp; var s0 = 1 - s2; var s1 = s3 - pp + p; // Layout of keyframe output values for CUBICSPLINE animations: // [ inTangent_1, splineVertex_1, outTangent_1, inTangent_2, splineVertex_2, ... ] for ( var i = 0; i !== stride; i ++ ) { var p0 = values[ offset0 + i + stride ]; // splineVertex_k var m0 = values[ offset0 + i + stride2 ] * td; // outTangent_k * (t_k+1 - t_k) var p1 = values[ offset1 + i + stride ]; // splineVertex_k+1 var m1 = values[ offset1 + i ] * td; // inTangent_k+1 * (t_k+1 - t_k) result[ i ] = s0 * p0 + s1 * m0 + s2 * p1 + s3 * m1; } return result; }; /*********************************/ /********** INTERNALS ************/ /*********************************/ /* CONSTANTS */ var WEBGL_CONSTANTS = { FLOAT: 5126, //FLOAT_MAT2: 35674, FLOAT_MAT3: 35675, FLOAT_MAT4: 35676, FLOAT_VEC2: 35664, FLOAT_VEC3: 35665, FLOAT_VEC4: 35666, LINEAR: 9729, REPEAT: 10497, SAMPLER_2D: 35678, POINTS: 0, LINES: 1, LINE_LOOP: 2, LINE_STRIP: 3, TRIANGLES: 4, TRIANGLE_STRIP: 5, TRIANGLE_FAN: 6, UNSIGNED_BYTE: 5121, UNSIGNED_SHORT: 5123 }; var WEBGL_COMPONENT_TYPES = { 5120: Int8Array, 5121: Uint8Array, 5122: Int16Array, 5123: Uint16Array, 5125: Uint32Array, 5126: Float32Array }; var WEBGL_FILTERS = { 9728: THREE.NearestFilter, 9729: THREE.LinearFilter, 9984: THREE.NearestMipmapNearestFilter, 9985: THREE.LinearMipmapNearestFilter, 9986: THREE.NearestMipmapLinearFilter, 9987: THREE.LinearMipmapLinearFilter }; var WEBGL_WRAPPINGS = { 33071: THREE.ClampToEdgeWrapping, 33648: THREE.MirroredRepeatWrapping, 10497: THREE.RepeatWrapping }; var WEBGL_TYPE_SIZES = { 'SCALAR': 1, 'VEC2': 2, 'VEC3': 3, 'VEC4': 4, 'MAT2': 4, 'MAT3': 9, 'MAT4': 16 }; var ATTRIBUTES = { POSITION: 'position', NORMAL: 'normal', TANGENT: 'tangent', TEXCOORD_0: 'uv', TEXCOORD_1: 'uv2', COLOR_0: 'color', WEIGHTS_0: 'skinWeight', JOINTS_0: 'skinIndex', }; var PATH_PROPERTIES = { scale: 'scale', translation: 'position', rotation: 'quaternion', weights: 'morphTargetInfluences' }; var INTERPOLATION = { CUBICSPLINE: undefined, // We use a custom interpolant (GLTFCubicSplineInterpolation) for CUBICSPLINE tracks. Each // keyframe track will be initialized with a default interpolation type, then modified. LINEAR: THREE.InterpolateLinear, STEP: THREE.InterpolateDiscrete }; var ALPHA_MODES = { OPAQUE: 'OPAQUE', MASK: 'MASK', BLEND: 'BLEND' }; var MIME_TYPE_FORMATS = { 'image/png': THREE.RGBAFormat, 'image/jpeg': THREE.RGBFormat }; /* UTILITY FUNCTIONS */ function resolveURL( url, path ) { // Invalid URL if ( typeof url !== 'string' || url === '' ) return ''; // Host Relative URL if ( /^https?:\/\//i.test( path ) && /^\//.test( url ) ) { path = path.replace( /(^https?:\/\/[^\/]+).*/i, '$1' ); } // Absolute URL http://,https://,// if ( /^(https?:)?\/\//i.test( url ) ) return url; // Data URI if ( /^data:.*,.*$/i.test( url ) ) return url; // Blob URL if ( /^blob:.*$/i.test( url ) ) return url; // Relative URL return path + url; } var defaultMaterial; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#default-material */ function createDefaultMaterial() { defaultMaterial = defaultMaterial || new THREE.MeshStandardMaterial( { color: 0xFFFFFF, emissive: 0x000000, metalness: 1, roughness: 1, transparent: false, depthTest: true, side: THREE.FrontSide } ); return defaultMaterial; } function addUnknownExtensionsToUserData( knownExtensions, object, objectDef ) { // Add unknown glTF extensions to an object's userData. for ( var name in objectDef.extensions ) { if ( knownExtensions[ name ] === undefined ) { object.userData.gltfExtensions = object.userData.gltfExtensions || {}; object.userData.gltfExtensions[ name ] = objectDef.extensions[ name ]; } } } /** * @param {THREE.Object3D|THREE.Material|THREE.BufferGeometry} object * @param {GLTF.definition} gltfDef */ function assignExtrasToUserData( object, gltfDef ) { if ( gltfDef.extras !== undefined ) { if ( typeof gltfDef.extras === 'object' ) { Object.assign( object.userData, gltfDef.extras ); } else { console.warn( 'THREE.GLTFLoader: Ignoring primitive type .extras, ' + gltfDef.extras ); } } } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#morph-targets * * @param {THREE.BufferGeometry} geometry * @param {Array<GLTF.Target>} targets * @param {GLTFParser} parser * @return {Promise<THREE.BufferGeometry>} */ function addMorphTargets( geometry, targets, parser ) { var hasMorphPosition = false; var hasMorphNormal = false; for ( var i = 0, il = targets.length; i < il; i ++ ) { var target = targets[ i ]; if ( target.POSITION !== undefined ) hasMorphPosition = true; if ( target.NORMAL !== undefined ) hasMorphNormal = true; if ( hasMorphPosition && hasMorphNormal ) break; } if ( ! hasMorphPosition && ! hasMorphNormal ) return Promise.resolve( geometry ); var pendingPositionAccessors = []; var pendingNormalAccessors = []; for ( var i = 0, il = targets.length; i < il; i ++ ) { var target = targets[ i ]; if ( hasMorphPosition ) { var pendingAccessor = target.POSITION !== undefined ? parser.getDependency( 'accessor', target.POSITION ) : geometry.attributes.position; pendingPositionAccessors.push( pendingAccessor ); } if ( hasMorphNormal ) { var pendingAccessor = target.NORMAL !== undefined ? parser.getDependency( 'accessor', target.NORMAL ) : geometry.attributes.normal; pendingNormalAccessors.push( pendingAccessor ); } } return Promise.all( [ Promise.all( pendingPositionAccessors ), Promise.all( pendingNormalAccessors ) ] ).then( function ( accessors ) { var morphPositions = accessors[ 0 ]; var morphNormals = accessors[ 1 ]; // Clone morph target accessors before modifying them. for ( var i = 0, il = morphPositions.length; i < il; i ++ ) { if ( geometry.attributes.position === morphPositions[ i ] ) continue; morphPositions[ i ] = cloneBufferAttribute( morphPositions[ i ] ); } for ( var i = 0, il = morphNormals.length; i < il; i ++ ) { if ( geometry.attributes.normal === morphNormals[ i ] ) continue; morphNormals[ i ] = cloneBufferAttribute( morphNormals[ i ] ); } for ( var i = 0, il = targets.length; i < il; i ++ ) { var target = targets[ i ]; var attributeName = 'morphTarget' + i; if ( hasMorphPosition ) { // Three.js morph position is absolute value. The formula is // basePosition // + weight0 * ( morphPosition0 - basePosition ) // + weight1 * ( morphPosition1 - basePosition ) // ... // while the glTF one is relative // basePosition // + weight0 * glTFmorphPosition0 // + weight1 * glTFmorphPosition1 // ... // then we need to convert from relative to absolute here. if ( target.POSITION !== undefined ) { var positionAttribute = morphPositions[ i ]; positionAttribute.name = attributeName; var position = geometry.attributes.position; for ( var j = 0, jl = positionAttribute.count; j < jl; j ++ ) { positionAttribute.setXYZ( j, positionAttribute.getX( j ) + position.getX( j ), positionAttribute.getY( j ) + position.getY( j ), positionAttribute.getZ( j ) + position.getZ( j ) ); } } } if ( hasMorphNormal ) { // see target.POSITION's comment if ( target.NORMAL !== undefined ) { var normalAttribute = morphNormals[ i ]; normalAttribute.name = attributeName; var normal = geometry.attributes.normal; for ( var j = 0, jl = normalAttribute.count; j < jl; j ++ ) { normalAttribute.setXYZ( j, normalAttribute.getX( j ) + normal.getX( j ), normalAttribute.getY( j ) + normal.getY( j ), normalAttribute.getZ( j ) + normal.getZ( j ) ); } } } } if ( hasMorphPosition ) geometry.morphAttributes.position = morphPositions; if ( hasMorphNormal ) geometry.morphAttributes.normal = morphNormals; return geometry; } ); } /** * @param {THREE.Mesh} mesh * @param {GLTF.Mesh} meshDef */ function updateMorphTargets( mesh, meshDef ) { mesh.updateMorphTargets(); if ( meshDef.weights !== undefined ) { for ( var i = 0, il = meshDef.weights.length; i < il; i ++ ) { mesh.morphTargetInfluences[ i ] = meshDef.weights[ i ]; } } // .extras has user-defined data, so check that .extras.targetNames is an array. if ( meshDef.extras && Array.isArray( meshDef.extras.targetNames ) ) { var targetNames = meshDef.extras.targetNames; if ( mesh.morphTargetInfluences.length === targetNames.length ) { mesh.morphTargetDictionary = {}; for ( var i = 0, il = targetNames.length; i < il; i ++ ) { mesh.morphTargetDictionary[ targetNames[ i ] ] = i; } } else { console.warn( 'THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.' ); } } } function createPrimitiveKey( primitiveDef ) { var dracoExtension = primitiveDef.extensions && primitiveDef.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ]; var geometryKey; if ( dracoExtension ) { geometryKey = 'draco:' + dracoExtension.bufferView + ':' + dracoExtension.indices + ':' + createAttributesKey( dracoExtension.attributes ); } else { geometryKey = primitiveDef.indices + ':' + createAttributesKey( primitiveDef.attributes ) + ':' + primitiveDef.mode; } return geometryKey; } function createAttributesKey( attributes ) { var attributesKey = ''; var keys = Object.keys( attributes ).sort(); for ( var i = 0, il = keys.length; i < il; i ++ ) { attributesKey += keys[ i ] + ':' + attributes[ keys[ i ] ] + ';'; } return attributesKey; } function cloneBufferAttribute( attribute ) { if ( attribute.isInterleavedBufferAttribute ) { var count = attribute.count; var itemSize = attribute.itemSize; var array = attribute.array.slice( 0, count * itemSize ); for ( var i = 0, j = 0; i < count; ++ i ) { array[ j ++ ] = attribute.getX( i ); if ( itemSize >= 2 ) array[ j ++ ] = attribute.getY( i ); if ( itemSize >= 3 ) array[ j ++ ] = attribute.getZ( i ); if ( itemSize >= 4 ) array[ j ++ ] = attribute.getW( i ); } return new THREE.BufferAttribute( array, itemSize, attribute.normalized ); } return attribute.clone(); } /* GLTF PARSER */ function GLTFParser( json, extensions, options ) { this.json = json || {}; this.extensions = extensions || {}; this.options = options || {}; // loader object cache this.cache = new GLTFRegistry(); // BufferGeometry caching this.primitiveCache = {}; this.textureLoader = new THREE.TextureLoader( this.options.manager ); this.textureLoader.setCrossOrigin( this.options.crossOrigin ); this.fileLoader = new THREE.FileLoader( this.options.manager ); this.fileLoader.setResponseType( 'arraybuffer' ); if ( this.options.crossOrigin === 'use-credentials' ) { this.fileLoader.setWithCredentials( true ); } } GLTFParser.prototype.parse = function ( onLoad, onError ) { var parser = this; var json = this.json; var extensions = this.extensions; // Clear the loader cache this.cache.removeAll(); // Mark the special nodes/meshes in json for efficient parse this.markDefs(); Promise.all( [ this.getDependencies( 'scene' ), this.getDependencies( 'animation' ), this.getDependencies( 'camera' ), ] ).then( function ( dependencies ) { var result = { scene: dependencies[ 0 ][ json.scene || 0 ], scenes: dependencies[ 0 ], animations: dependencies[ 1 ], cameras: dependencies[ 2 ], asset: json.asset, parser: parser, userData: {} }; addUnknownExtensionsToUserData( extensions, result, json ); assignExtrasToUserData( result, json ); onLoad( result ); } ).catch( onError ); }; /** * Marks the special nodes/meshes in json for efficient parse. */ GLTFParser.prototype.markDefs = function () { var nodeDefs = this.json.nodes || []; var skinDefs = this.json.skins || []; var meshDefs = this.json.meshes || []; var meshReferences = {}; var meshUses = {}; // Nothing in the node definition indicates whether it is a Bone or an // Object3D. Use the skins' joint references to mark bones. for ( var skinIndex = 0, skinLength = skinDefs.length; skinIndex < skinLength; skinIndex ++ ) { var joints = skinDefs[ skinIndex ].joints; for ( var i = 0, il = joints.length; i < il; i ++ ) { nodeDefs[ joints[ i ] ].isBone = true; } } // Meshes can (and should) be reused by multiple nodes in a glTF asset. To // avoid having more than one THREE.Mesh with the same name, count // references and rename instances below. // // Example: CesiumMilkTruck sample model reuses "Wheel" meshes. for ( var nodeIndex = 0, nodeLength = nodeDefs.length; nodeIndex < nodeLength; nodeIndex ++ ) { var nodeDef = nodeDefs[ nodeIndex ]; if ( nodeDef.mesh !== undefined ) { if ( meshReferences[ nodeDef.mesh ] === undefined ) { meshReferences[ nodeDef.mesh ] = meshUses[ nodeDef.mesh ] = 0; } meshReferences[ nodeDef.mesh ] ++; // Nothing in the mesh definition indicates whether it is // a SkinnedMesh or Mesh. Use the node's mesh reference // to mark SkinnedMesh if node has skin. if ( nodeDef.skin !== undefined ) { meshDefs[ nodeDef.mesh ].isSkinnedMesh = true; } } } this.json.meshReferences = meshReferences; this.json.meshUses = meshUses; }; /** * Requests the specified dependency asynchronously, with caching. * @param {string} type * @param {number} index * @return {Promise<THREE.Object3D|THREE.Material|THREE.Texture|THREE.AnimationClip|ArrayBuffer|Object>} */ GLTFParser.prototype.getDependency = function ( type, index ) { var cacheKey = type + ':' + index; var dependency = this.cache.get( cacheKey ); if ( ! dependency ) { switch ( type ) { case 'scene': dependency = this.loadScene( index ); break; case 'node': dependency = this.loadNode( index ); break; case 'mesh': dependency = this.loadMesh( index ); break; case 'accessor': dependency = this.loadAccessor( index ); break; case 'bufferView': dependency = this.loadBufferView( index ); break; case 'buffer': dependency = this.loadBuffer( index ); break; case 'material': dependency = this.loadMaterial( index ); break; case 'texture': dependency = this.loadTexture( index ); break; case 'skin': dependency = this.loadSkin( index ); break; case 'animation': dependency = this.loadAnimation( index ); break; case 'camera': dependency = this.loadCamera( index ); break; case 'light': dependency = this.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].loadLight( index ); break; default: throw new Error( 'Unknown type: ' + type ); } this.cache.add( cacheKey, dependency ); } return dependency; }; /** * Requests all dependencies of the specified type asynchronously, with caching. * @param {string} type * @return {Promise<Array<Object>>} */ GLTFParser.prototype.getDependencies = function ( type ) { var dependencies = this.cache.get( type ); if ( ! dependencies ) { var parser = this; var defs = this.json[ type + ( type === 'mesh' ? 'es' : 's' ) ] || []; dependencies = Promise.all( defs.map( function ( def, index ) { return parser.getDependency( type, index ); } ) ); this.cache.add( type, dependencies ); } return dependencies; }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferIndex * @return {Promise<ArrayBuffer>} */ GLTFParser.prototype.loadBuffer = function ( bufferIndex ) { var bufferDef = this.json.buffers[ bufferIndex ]; var loader = this.fileLoader; if ( bufferDef.type && bufferDef.type !== 'arraybuffer' ) { throw new Error( 'THREE.GLTFLoader: ' + bufferDef.type + ' buffer type is not supported.' ); } // If present, GLB container is required to be the first buffer. if ( bufferDef.uri === undefined && bufferIndex === 0 ) { return Promise.resolve( this.extensions[ EXTENSIONS.KHR_BINARY_GLTF ].body ); } var options = this.options; return new Promise( function ( resolve, reject ) { loader.load( resolveURL( bufferDef.uri, options.path ), resolve, undefined, function () { reject( new Error( 'THREE.GLTFLoader: Failed to load buffer "' + bufferDef.uri + '".' ) ); } ); } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#buffers-and-buffer-views * @param {number} bufferViewIndex * @return {Promise<ArrayBuffer>} */ GLTFParser.prototype.loadBufferView = function ( bufferViewIndex ) { var bufferViewDef = this.json.bufferViews[ bufferViewIndex ]; return this.getDependency( 'buffer', bufferViewDef.buffer ).then( function ( buffer ) { var byteLength = bufferViewDef.byteLength || 0; var byteOffset = bufferViewDef.byteOffset || 0; return buffer.slice( byteOffset, byteOffset + byteLength ); } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#accessors * @param {number} accessorIndex * @return {Promise<THREE.BufferAttribute|THREE.InterleavedBufferAttribute>} */ GLTFParser.prototype.loadAccessor = function ( accessorIndex ) { var parser = this; var json = this.json; var accessorDef = this.json.accessors[ accessorIndex ]; if ( accessorDef.bufferView === undefined && accessorDef.sparse === undefined ) { // Ignore empty accessors, which may be used to declare runtime // information about attributes coming from another source (e.g. Draco // compression extension). return Promise.resolve( null ); } var pendingBufferViews = []; if ( accessorDef.bufferView !== undefined ) { pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.bufferView ) ); } else { pendingBufferViews.push( null ); } if ( accessorDef.sparse !== undefined ) { pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.indices.bufferView ) ); pendingBufferViews.push( this.getDependency( 'bufferView', accessorDef.sparse.values.bufferView ) ); } return Promise.all( pendingBufferViews ).then( function ( bufferViews ) { var bufferView = bufferViews[ 0 ]; var itemSize = WEBGL_TYPE_SIZES[ accessorDef.type ]; var TypedArray = WEBGL_COMPONENT_TYPES[ accessorDef.componentType ]; // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12. var elementBytes = TypedArray.BYTES_PER_ELEMENT; var itemBytes = elementBytes * itemSize; var byteOffset = accessorDef.byteOffset || 0; var byteStride = accessorDef.bufferView !== undefined ? json.bufferViews[ accessorDef.bufferView ].byteStride : undefined; var normalized = accessorDef.normalized === true; var array, bufferAttribute; // The buffer is not interleaved if the stride is the item size in bytes. if ( byteStride && byteStride !== itemBytes ) { // Each "slice" of the buffer, as defined by 'count' elements of 'byteStride' bytes, gets its own InterleavedBuffer // This makes sure that IBA.count reflects accessor.count properly var ibSlice = Math.floor( byteOffset / byteStride ); var ibCacheKey = 'InterleavedBuffer:' + accessorDef.bufferView + ':' + accessorDef.componentType + ':' + ibSlice + ':' + accessorDef.count; var ib = parser.cache.get( ibCacheKey ); if ( ! ib ) { array = new TypedArray( bufferView, ibSlice * byteStride, accessorDef.count * byteStride / elementBytes ); // Integer parameters to IB/IBA are in array elements, not bytes. ib = new THREE.InterleavedBuffer( array, byteStride / elementBytes ); parser.cache.add( ibCacheKey, ib ); } bufferAttribute = new THREE.InterleavedBufferAttribute( ib, itemSize, ( byteOffset % byteStride ) / elementBytes, normalized ); } else { if ( bufferView === null ) { array = new TypedArray( accessorDef.count * itemSize ); } else { array = new TypedArray( bufferView, byteOffset, accessorDef.count * itemSize ); } bufferAttribute = new THREE.BufferAttribute( array, itemSize, normalized ); } // https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#sparse-accessors if ( accessorDef.sparse !== undefined ) { var itemSizeIndices = WEBGL_TYPE_SIZES.SCALAR; var TypedArrayIndices = WEBGL_COMPONENT_TYPES[ accessorDef.sparse.indices.componentType ]; var byteOffsetIndices = accessorDef.sparse.indices.byteOffset || 0; var byteOffsetValues = accessorDef.sparse.values.byteOffset || 0; var sparseIndices = new TypedArrayIndices( bufferViews[ 1 ], byteOffsetIndices, accessorDef.sparse.count * itemSizeIndices ); var sparseValues = new TypedArray( bufferViews[ 2 ], byteOffsetValues, accessorDef.sparse.count * itemSize ); if ( bufferView !== null ) { // Avoid modifying the original ArrayBuffer, if the bufferView wasn't initialized with zeroes. bufferAttribute = new THREE.BufferAttribute( bufferAttribute.array.slice(), bufferAttribute.itemSize, bufferAttribute.normalized ); } for ( var i = 0, il = sparseIndices.length; i < il; i ++ ) { var index = sparseIndices[ i ]; bufferAttribute.setX( index, sparseValues[ i * itemSize ] ); if ( itemSize >= 2 ) bufferAttribute.setY( index, sparseValues[ i * itemSize + 1 ] ); if ( itemSize >= 3 ) bufferAttribute.setZ( index, sparseValues[ i * itemSize + 2 ] ); if ( itemSize >= 4 ) bufferAttribute.setW( index, sparseValues[ i * itemSize + 3 ] ); if ( itemSize >= 5 ) throw new Error( 'THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.' ); } } return bufferAttribute; } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#textures * @param {number} textureIndex * @return {Promise<THREE.Texture>} */ GLTFParser.prototype.loadTexture = function ( textureIndex ) { var parser = this; var json = this.json; var options = this.options; var textureLoader = this.textureLoader; var URL = window.URL || window.webkitURL; var textureDef = json.textures[ textureIndex ]; var textureExtensions = textureDef.extensions || {}; var source; if ( textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ) { source = json.images[ textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].source ]; } else { source = json.images[ textureDef.source ]; } var sourceURI = source.uri; var isObjectURL = false; if ( source.bufferView !== undefined ) { // Load binary image data from bufferView, if provided. sourceURI = parser.getDependency( 'bufferView', source.bufferView ).then( function ( bufferView ) { isObjectURL = true; var blob = new Blob( [ bufferView ], { type: source.mimeType } ); sourceURI = URL.createObjectURL( blob ); return sourceURI; } ); } return Promise.resolve( sourceURI ).then( function ( sourceURI ) { // Load Texture resource. var loader = options.manager.getHandler( sourceURI ); if ( ! loader ) { loader = textureExtensions[ EXTENSIONS.MSFT_TEXTURE_DDS ] ? parser.extensions[ EXTENSIONS.MSFT_TEXTURE_DDS ].ddsLoader : textureLoader; } return new Promise( function ( resolve, reject ) { loader.load( resolveURL( sourceURI, options.path ), resolve, undefined, reject ); } ); } ).then( function ( texture ) { // Clean up resources and configure Texture. if ( isObjectURL === true ) { URL.revokeObjectURL( sourceURI ); } texture.flipY = false; if ( textureDef.name !== undefined ) texture.name = textureDef.name; // Ignore unknown mime types, like DDS files. if ( source.mimeType in MIME_TYPE_FORMATS ) { texture.format = MIME_TYPE_FORMATS[ source.mimeType ]; } var samplers = json.samplers || {}; var sampler = samplers[ textureDef.sampler ] || {}; texture.magFilter = WEBGL_FILTERS[ sampler.magFilter ] || THREE.LinearFilter; texture.minFilter = WEBGL_FILTERS[ sampler.minFilter ] || THREE.LinearMipmapLinearFilter; texture.wrapS = WEBGL_WRAPPINGS[ sampler.wrapS ] || THREE.RepeatWrapping; texture.wrapT = WEBGL_WRAPPINGS[ sampler.wrapT ] || THREE.RepeatWrapping; return texture; } ); }; /** * Asynchronously assigns a texture to the given material parameters. * @param {Object} materialParams * @param {string} mapName * @param {Object} mapDef * @return {Promise} */ GLTFParser.prototype.assignTexture = function ( materialParams, mapName, mapDef ) { var parser = this; return this.getDependency( 'texture', mapDef.index ).then( function ( texture ) { if ( ! texture.isCompressedTexture ) { switch ( mapName ) { case 'aoMap': case 'emissiveMap': case 'metalnessMap': case 'normalMap': case 'roughnessMap': texture.format = THREE.RGBFormat; break; } } if ( parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] ) { var transform = mapDef.extensions !== undefined ? mapDef.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ] : undefined; if ( transform ) { texture = parser.extensions[ EXTENSIONS.KHR_TEXTURE_TRANSFORM ].extendTexture( texture, transform ); } } materialParams[ mapName ] = texture; } ); }; /** * Assigns final material to a Mesh, Line, or Points instance. The instance * already has a material (generated from the glTF material options alone) * but reuse of the same glTF material may require multiple threejs materials * to accomodate different primitive types, defines, etc. New materials will * be created if necessary, and reused from a cache. * @param {THREE.Object3D} mesh Mesh, Line, or Points instance. */ GLTFParser.prototype.assignFinalMaterial = function ( mesh ) { var geometry = mesh.geometry; var material = mesh.material; var extensions = this.extensions; var useVertexTangents = geometry.attributes.tangent !== undefined; var useVertexColors = geometry.attributes.color !== undefined; var useFlatShading = geometry.attributes.normal === undefined; var useSkinning = mesh.isSkinnedMesh === true; var useMorphTargets = Object.keys( geometry.morphAttributes ).length > 0; var useMorphNormals = useMorphTargets && geometry.morphAttributes.normal !== undefined; if ( mesh.isPoints ) { var cacheKey = 'PointsMaterial:' + material.uuid; var pointsMaterial = this.cache.get( cacheKey ); if ( ! pointsMaterial ) { pointsMaterial = new THREE.PointsMaterial(); THREE.Material.prototype.copy.call( pointsMaterial, material ); pointsMaterial.color.copy( material.color ); pointsMaterial.map = material.map; pointsMaterial.lights = false; // PointsMaterial doesn't support lights yet pointsMaterial.sizeAttenuation = false; // glTF spec says points should be 1px this.cache.add( cacheKey, pointsMaterial ); } material = pointsMaterial; } else if ( mesh.isLine ) { var cacheKey = 'LineBasicMaterial:' + material.uuid; var lineMaterial = this.cache.get( cacheKey ); if ( ! lineMaterial ) { lineMaterial = new THREE.LineBasicMaterial(); THREE.Material.prototype.copy.call( lineMaterial, material ); lineMaterial.color.copy( material.color ); lineMaterial.lights = false; // LineBasicMaterial doesn't support lights yet this.cache.add( cacheKey, lineMaterial ); } material = lineMaterial; } // Clone the material if it will be modified if ( useVertexTangents || useVertexColors || useFlatShading || useSkinning || useMorphTargets ) { var cacheKey = 'ClonedMaterial:' + material.uuid + ':'; if ( material.isGLTFSpecularGlossinessMaterial ) cacheKey += 'specular-glossiness:'; if ( useSkinning ) cacheKey += 'skinning:'; if ( useVertexTangents ) cacheKey += 'vertex-tangents:'; if ( useVertexColors ) cacheKey += 'vertex-colors:'; if ( useFlatShading ) cacheKey += 'flat-shading:'; if ( useMorphTargets ) cacheKey += 'morph-targets:'; if ( useMorphNormals ) cacheKey += 'morph-normals:'; var cachedMaterial = this.cache.get( cacheKey ); if ( ! cachedMaterial ) { cachedMaterial = material.isGLTFSpecularGlossinessMaterial ? extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].cloneMaterial( material ) : material.clone(); if ( useSkinning ) cachedMaterial.skinning = true; if ( useVertexTangents ) cachedMaterial.vertexTangents = true; if ( useVertexColors ) cachedMaterial.vertexColors = THREE.VertexColors; if ( useFlatShading ) cachedMaterial.flatShading = true; if ( useMorphTargets ) cachedMaterial.morphTargets = true; if ( useMorphNormals ) cachedMaterial.morphNormals = true; this.cache.add( cacheKey, cachedMaterial ); } material = cachedMaterial; } // workarounds for mesh and geometry if ( material.aoMap && geometry.attributes.uv2 === undefined && geometry.attributes.uv !== undefined ) { console.log( 'THREE.GLTFLoader: Duplicating UVs to support aoMap.' ); geometry.addAttribute( 'uv2', new THREE.BufferAttribute( geometry.attributes.uv.array, 2 ) ); } if ( material.isGLTFSpecularGlossinessMaterial ) { // for GLTFSpecularGlossinessMaterial(ShaderMaterial) uniforms runtime update mesh.onBeforeRender = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].refreshUniforms; } mesh.material = material; }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#materials * @param {number} materialIndex * @return {Promise<THREE.Material>} */ GLTFParser.prototype.loadMaterial = function ( materialIndex ) { var parser = this; var json = this.json; var extensions = this.extensions; var materialDef = json.materials[ materialIndex ]; var materialType; var materialParams = {}; var materialExtensions = materialDef.extensions || {}; var pending = []; if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ] ) { var sgExtension = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ]; materialType = sgExtension.getMaterialType(); pending.push( sgExtension.extendParams( materialParams, materialDef, parser ) ); } else if ( materialExtensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ] ) { var kmuExtension = extensions[ EXTENSIONS.KHR_MATERIALS_UNLIT ]; materialType = kmuExtension.getMaterialType(); pending.push( kmuExtension.extendParams( materialParams, materialDef, parser ) ); } else { // Specification: // https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#metallic-roughness-material materialType = THREE.MeshStandardMaterial; var metallicRoughness = materialDef.pbrMetallicRoughness || {}; materialParams.color = new THREE.Color( 1.0, 1.0, 1.0 ); materialParams.opacity = 1.0; if ( Array.isArray( metallicRoughness.baseColorFactor ) ) { var array = metallicRoughness.baseColorFactor; materialParams.color.fromArray( array ); materialParams.opacity = array[ 3 ]; } if ( metallicRoughness.baseColorTexture !== undefined ) { pending.push( parser.assignTexture( materialParams, 'map', metallicRoughness.baseColorTexture ) ); } materialParams.metalness = metallicRoughness.metallicFactor !== undefined ? metallicRoughness.metallicFactor : 1.0; materialParams.roughness = metallicRoughness.roughnessFactor !== undefined ? metallicRoughness.roughnessFactor : 1.0; if ( metallicRoughness.metallicRoughnessTexture !== undefined ) { pending.push( parser.assignTexture( materialParams, 'metalnessMap', metallicRoughness.metallicRoughnessTexture ) ); pending.push( parser.assignTexture( materialParams, 'roughnessMap', metallicRoughness.metallicRoughnessTexture ) ); } } if ( materialDef.doubleSided === true ) { materialParams.side = THREE.DoubleSide; } var alphaMode = materialDef.alphaMode || ALPHA_MODES.OPAQUE; if ( alphaMode === ALPHA_MODES.BLEND ) { materialParams.transparent = true; } else { materialParams.transparent = false; if ( alphaMode === ALPHA_MODES.MASK ) { materialParams.alphaTest = materialDef.alphaCutoff !== undefined ? materialDef.alphaCutoff : 0.5; } } if ( materialDef.normalTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'normalMap', materialDef.normalTexture ) ); materialParams.normalScale = new THREE.Vector2( 1, 1 ); if ( materialDef.normalTexture.scale !== undefined ) { materialParams.normalScale.set( materialDef.normalTexture.scale, materialDef.normalTexture.scale ); } } if ( materialDef.occlusionTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'aoMap', materialDef.occlusionTexture ) ); if ( materialDef.occlusionTexture.strength !== undefined ) { materialParams.aoMapIntensity = materialDef.occlusionTexture.strength; } } if ( materialDef.emissiveFactor !== undefined && materialType !== THREE.MeshBasicMaterial ) { materialParams.emissive = new THREE.Color().fromArray( materialDef.emissiveFactor ); } if ( materialDef.emissiveTexture !== undefined && materialType !== THREE.MeshBasicMaterial ) { pending.push( parser.assignTexture( materialParams, 'emissiveMap', materialDef.emissiveTexture ) ); } return Promise.all( pending ).then( function () { var material; if ( materialType === THREE.ShaderMaterial ) { material = extensions[ EXTENSIONS.KHR_MATERIALS_PBR_SPECULAR_GLOSSINESS ].createMaterial( materialParams ); } else { material = new materialType( materialParams ); } if ( materialDef.name !== undefined ) material.name = materialDef.name; // baseColorTexture, emissiveTexture, and specularGlossinessTexture use sRGB encoding. if ( material.map ) material.map.encoding = THREE.sRGBEncoding; if ( material.emissiveMap ) material.emissiveMap.encoding = THREE.sRGBEncoding; if ( material.specularMap ) material.specularMap.encoding = THREE.sRGBEncoding; assignExtrasToUserData( material, materialDef ); if ( materialDef.extensions ) addUnknownExtensionsToUserData( extensions, material, materialDef ); return material; } ); }; /** * @param {THREE.BufferGeometry} geometry * @param {GLTF.Primitive} primitiveDef * @param {GLTFParser} parser * @return {Promise<THREE.BufferGeometry>} */ function addPrimitiveAttributes( geometry, primitiveDef, parser ) { var attributes = primitiveDef.attributes; var pending = []; function assignAttributeAccessor( accessorIndex, attributeName ) { return parser.getDependency( 'accessor', accessorIndex ) .then( function ( accessor ) { geometry.addAttribute( attributeName, accessor ); } ); } for ( var gltfAttributeName in attributes ) { var threeAttributeName = ATTRIBUTES[ gltfAttributeName ] || gltfAttributeName.toLowerCase(); // Skip attributes already provided by e.g. Draco extension. if ( threeAttributeName in geometry.attributes ) continue; pending.push( assignAttributeAccessor( attributes[ gltfAttributeName ], threeAttributeName ) ); } if ( primitiveDef.indices !== undefined && ! geometry.index ) { var accessor = parser.getDependency( 'accessor', primitiveDef.indices ).then( function ( accessor ) { geometry.setIndex( accessor ); } ); pending.push( accessor ); } assignExtrasToUserData( geometry, primitiveDef ); return Promise.all( pending ).then( function () { return primitiveDef.targets !== undefined ? addMorphTargets( geometry, primitiveDef.targets, parser ) : geometry; } ); } /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#geometry * * Creates BufferGeometries from primitives. * * @param {Array<GLTF.Primitive>} primitives * @return {Promise<Array<THREE.BufferGeometry>>} */ GLTFParser.prototype.loadGeometries = function ( primitives ) { var parser = this; var extensions = this.extensions; var cache = this.primitiveCache; function createDracoPrimitive( primitive ) { return extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] .decodePrimitive( primitive, parser ) .then( function ( geometry ) { return addPrimitiveAttributes( geometry, primitive, parser ); } ); } var pending = []; for ( var i = 0, il = primitives.length; i < il; i ++ ) { var primitive = primitives[ i ]; var cacheKey = createPrimitiveKey( primitive ); // See if we've already created this geometry var cached = cache[ cacheKey ]; if ( cached ) { // Use the cached geometry if it exists pending.push( cached.promise ); } else { var geometryPromise; if ( primitive.extensions && primitive.extensions[ EXTENSIONS.KHR_DRACO_MESH_COMPRESSION ] ) { // Use DRACO geometry if available geometryPromise = createDracoPrimitive( primitive ); } else { // Otherwise create a new geometry geometryPromise = addPrimitiveAttributes( new THREE.BufferGeometry(), primitive, parser ); } // Cache this geometry cache[ cacheKey ] = { primitive: primitive, promise: geometryPromise }; pending.push( geometryPromise ); } } return Promise.all( pending ); }; /** * Specification: https://github.com/KhronosGroup/glTF/blob/master/specification/2.0/README.md#meshes * @param {number} meshIndex * @return {Promise<THREE.Group|THREE.Mesh|THREE.SkinnedMesh>} */ GLTFParser.prototype.loadMesh = function ( meshIndex ) { var parser = this; var json = this.json; var meshDef = json.meshes[ meshIndex ]; var primitives = meshDef.primitives; var pending = []; for ( var i = 0, il = primitives.length; i < il; i ++ ) { var material = primitives[ i ].material === undefined ? createDefaultMaterial() : this.getDependency( 'material', primitives[ i ].material ); pending.push( material ); } return Promise.all( pending ).then( function ( originalMaterials ) { return parser.loadGeometries( primitives ).then( function ( geometries ) { var meshes = []; for ( var i = 0, il = geometries.length; i < il; i ++ ) { var geometry = geometries[ i ]; var primitive = primitives[ i ]; // 1. create Mesh var mesh; var material = originalMaterials[ i ]; if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLES || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP || primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN || primitive.mode === undefined ) { // .isSkinnedMesh isn't in glTF spec. See .markDefs() mesh = meshDef.isSkinnedMesh === true ? new THREE.SkinnedMesh( geometry, material ) : new THREE.Mesh( geometry, material ); if ( mesh.isSkinnedMesh === true && ! mesh.geometry.attributes.skinWeight.normalized ) { // we normalize floating point skin weight array to fix malformed assets (see #15319) // it's important to skip this for non-float32 data since normalizeSkinWeights assumes non-normalized inputs mesh.normalizeSkinWeights(); } if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_STRIP ) { mesh.drawMode = THREE.TriangleStripDrawMode; } else if ( primitive.mode === WEBGL_CONSTANTS.TRIANGLE_FAN ) { mesh.drawMode = THREE.TriangleFanDrawMode; } } else if ( primitive.mode === WEBGL_CONSTANTS.LINES ) { mesh = new THREE.LineSegments( geometry, material ); } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_STRIP ) { mesh = new THREE.Line( geometry, material ); } else if ( primitive.mode === WEBGL_CONSTANTS.LINE_LOOP ) { mesh = new THREE.LineLoop( geometry, material ); } else if ( primitive.mode === WEBGL_CONSTANTS.POINTS ) { mesh = new THREE.Points( geometry, material ); } else { throw new Error( 'THREE.GLTFLoader: Primitive mode unsupported: ' + primitive.mode ); } if ( Object.keys( mesh.geometry.morphAttributes ).length > 0 ) { updateMorphTargets( mesh, meshDef ); } mesh.name = meshDef.name || ( 'mesh_' + meshIndex ); if ( geometries.length > 1 ) mesh.name += '_' + i; assignExtrasToUserData( mesh, meshDef ); parser.assignFinalMaterial( mesh ); meshes.push( mesh ); } if ( meshes.length === 1 ) { return meshes[ 0 ]; } var group = new THREE.Group(); for ( var i = 0, il = meshes.length; i < il; i ++ ) { group.add( meshes[ i ] ); } return group; } ); } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#cameras * @param {number} cameraIndex * @return {Promise<THREE.Camera>} */ GLTFParser.prototype.loadCamera = function ( cameraIndex ) { var camera; var cameraDef = this.json.cameras[ cameraIndex ]; var params = cameraDef[ cameraDef.type ]; if ( ! params ) { console.warn( 'THREE.GLTFLoader: Missing camera parameters.' ); return; } if ( cameraDef.type === 'perspective' ) { camera = new THREE.PerspectiveCamera( THREE.Math.radToDeg( params.yfov ), params.aspectRatio || 1, params.znear || 1, params.zfar || 2e6 ); } else if ( cameraDef.type === 'orthographic' ) { camera = new THREE.OrthographicCamera( params.xmag / - 2, params.xmag / 2, params.ymag / 2, params.ymag / - 2, params.znear, params.zfar ); } if ( cameraDef.name !== undefined ) camera.name = cameraDef.name; assignExtrasToUserData( camera, cameraDef ); return Promise.resolve( camera ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins * @param {number} skinIndex * @return {Promise<Object>} */ GLTFParser.prototype.loadSkin = function ( skinIndex ) { var skinDef = this.json.skins[ skinIndex ]; var skinEntry = { joints: skinDef.joints }; if ( skinDef.inverseBindMatrices === undefined ) { return Promise.resolve( skinEntry ); } return this.getDependency( 'accessor', skinDef.inverseBindMatrices ).then( function ( accessor ) { skinEntry.inverseBindMatrices = accessor; return skinEntry; } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#animations * @param {number} animationIndex * @return {Promise<THREE.AnimationClip>} */ GLTFParser.prototype.loadAnimation = function ( animationIndex ) { var json = this.json; var animationDef = json.animations[ animationIndex ]; var pendingNodes = []; var pendingInputAccessors = []; var pendingOutputAccessors = []; var pendingSamplers = []; var pendingTargets = []; for ( var i = 0, il = animationDef.channels.length; i < il; i ++ ) { var channel = animationDef.channels[ i ]; var sampler = animationDef.samplers[ channel.sampler ]; var target = channel.target; var name = target.node !== undefined ? target.node : target.id; // NOTE: target.id is deprecated. var input = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.input ] : sampler.input; var output = animationDef.parameters !== undefined ? animationDef.parameters[ sampler.output ] : sampler.output; pendingNodes.push( this.getDependency( 'node', name ) ); pendingInputAccessors.push( this.getDependency( 'accessor', input ) ); pendingOutputAccessors.push( this.getDependency( 'accessor', output ) ); pendingSamplers.push( sampler ); pendingTargets.push( target ); } return Promise.all( [ Promise.all( pendingNodes ), Promise.all( pendingInputAccessors ), Promise.all( pendingOutputAccessors ), Promise.all( pendingSamplers ), Promise.all( pendingTargets ) ] ).then( function ( dependencies ) { var nodes = dependencies[ 0 ]; var inputAccessors = dependencies[ 1 ]; var outputAccessors = dependencies[ 2 ]; var samplers = dependencies[ 3 ]; var targets = dependencies[ 4 ]; var tracks = []; for ( var i = 0, il = nodes.length; i < il; i ++ ) { var node = nodes[ i ]; var inputAccessor = inputAccessors[ i ]; var outputAccessor = outputAccessors[ i ]; var sampler = samplers[ i ]; var target = targets[ i ]; if ( node === undefined ) continue; node.updateMatrix(); node.matrixAutoUpdate = true; var TypedKeyframeTrack; switch ( PATH_PROPERTIES[ target.path ] ) { case PATH_PROPERTIES.weights: TypedKeyframeTrack = THREE.NumberKeyframeTrack; break; case PATH_PROPERTIES.rotation: TypedKeyframeTrack = THREE.QuaternionKeyframeTrack; break; case PATH_PROPERTIES.position: case PATH_PROPERTIES.scale: default: TypedKeyframeTrack = THREE.VectorKeyframeTrack; break; } var targetName = node.name ? node.name : node.uuid; var interpolation = sampler.interpolation !== undefined ? INTERPOLATION[ sampler.interpolation ] : THREE.InterpolateLinear; var targetNames = []; if ( PATH_PROPERTIES[ target.path ] === PATH_PROPERTIES.weights ) { // Node may be a THREE.Group (glTF mesh with several primitives) or a THREE.Mesh. node.traverse( function ( object ) { if ( object.isMesh === true && object.morphTargetInfluences ) { targetNames.push( object.name ? object.name : object.uuid ); } } ); } else { targetNames.push( targetName ); } var outputArray = outputAccessor.array; if ( outputAccessor.normalized ) { var scale; if ( outputArray.constructor === Int8Array ) { scale = 1 / 127; } else if ( outputArray.constructor === Uint8Array ) { scale = 1 / 255; } else if ( outputArray.constructor == Int16Array ) { scale = 1 / 32767; } else if ( outputArray.constructor === Uint16Array ) { scale = 1 / 65535; } else { throw new Error( 'THREE.GLTFLoader: Unsupported output accessor component type.' ); } var scaled = new Float32Array( outputArray.length ); for ( var j = 0, jl = outputArray.length; j < jl; j ++ ) { scaled[ j ] = outputArray[ j ] * scale; } outputArray = scaled; } for ( var j = 0, jl = targetNames.length; j < jl; j ++ ) { var track = new TypedKeyframeTrack( targetNames[ j ] + '.' + PATH_PROPERTIES[ target.path ], inputAccessor.array, outputArray, interpolation ); // Override interpolation with custom factory method. if ( sampler.interpolation === 'CUBICSPLINE' ) { track.createInterpolant = function InterpolantFactoryMethodGLTFCubicSpline( result ) { // A CUBICSPLINE keyframe in glTF has three output values for each input value, // representing inTangent, splineVertex, and outTangent. As a result, track.getValueSize() // must be divided by three to get the interpolant's sampleSize argument. return new GLTFCubicSplineInterpolant( this.times, this.values, this.getValueSize() / 3, result ); }; // Mark as CUBICSPLINE. `track.getInterpolation()` doesn't support custom interpolants. track.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline = true; } tracks.push( track ); } } var name = animationDef.name !== undefined ? animationDef.name : 'animation_' + animationIndex; return new THREE.AnimationClip( name, undefined, tracks ); } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#nodes-and-hierarchy * @param {number} nodeIndex * @return {Promise<THREE.Object3D>} */ GLTFParser.prototype.loadNode = function ( nodeIndex ) { var json = this.json; var extensions = this.extensions; var parser = this; var meshReferences = json.meshReferences; var meshUses = json.meshUses; var nodeDef = json.nodes[ nodeIndex ]; return ( function () { var pending = []; if ( nodeDef.mesh !== undefined ) { pending.push( parser.getDependency( 'mesh', nodeDef.mesh ).then( function ( mesh ) { var node; if ( meshReferences[ nodeDef.mesh ] > 1 ) { var instanceNum = meshUses[ nodeDef.mesh ] ++; node = mesh.clone(); node.name += '_instance_' + instanceNum; // onBeforeRender copy for Specular-Glossiness node.onBeforeRender = mesh.onBeforeRender; for ( var i = 0, il = node.children.length; i < il; i ++ ) { node.children[ i ].name += '_instance_' + instanceNum; node.children[ i ].onBeforeRender = mesh.children[ i ].onBeforeRender; } } else { node = mesh; } // if weights are provided on the node, override weights on the mesh. if ( nodeDef.weights !== undefined ) { node.traverse( function ( o ) { if ( ! o.isMesh ) return; for ( var i = 0, il = nodeDef.weights.length; i < il; i ++ ) { o.morphTargetInfluences[ i ] = nodeDef.weights[ i ]; } } ); } return node; } ) ); } if ( nodeDef.camera !== undefined ) { pending.push( parser.getDependency( 'camera', nodeDef.camera ) ); } if ( nodeDef.extensions && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ] && nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light !== undefined ) { pending.push( parser.getDependency( 'light', nodeDef.extensions[ EXTENSIONS.KHR_LIGHTS_PUNCTUAL ].light ) ); } return Promise.all( pending ); }() ).then( function ( objects ) { var node; // .isBone isn't in glTF spec. See .markDefs if ( nodeDef.isBone === true ) { node = new THREE.Bone(); } else if ( objects.length > 1 ) { node = new THREE.Group(); } else if ( objects.length === 1 ) { node = objects[ 0 ]; } else { node = new THREE.Object3D(); } if ( node !== objects[ 0 ] ) { for ( var i = 0, il = objects.length; i < il; i ++ ) { node.add( objects[ i ] ); } } if ( nodeDef.name !== undefined ) { node.userData.name = nodeDef.name; node.name = THREE.PropertyBinding.sanitizeNodeName( nodeDef.name ); } assignExtrasToUserData( node, nodeDef ); if ( nodeDef.extensions ) addUnknownExtensionsToUserData( extensions, node, nodeDef ); if ( nodeDef.matrix !== undefined ) { var matrix = new THREE.Matrix4(); matrix.fromArray( nodeDef.matrix ); node.applyMatrix( matrix ); } else { if ( nodeDef.translation !== undefined ) { node.position.fromArray( nodeDef.translation ); } if ( nodeDef.rotation !== undefined ) { node.quaternion.fromArray( nodeDef.rotation ); } if ( nodeDef.scale !== undefined ) { node.scale.fromArray( nodeDef.scale ); } } return node; } ); }; /** * Specification: https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#scenes * @param {number} sceneIndex * @return {Promise<THREE.Scene>} */ GLTFParser.prototype.loadScene = function () { // scene node hierachy builder function buildNodeHierachy( nodeId, parentObject, json, parser ) { var nodeDef = json.nodes[ nodeId ]; return parser.getDependency( 'node', nodeId ).then( function ( node ) { if ( nodeDef.skin === undefined ) return node; // build skeleton here as well var skinEntry; return parser.getDependency( 'skin', nodeDef.skin ).then( function ( skin ) { skinEntry = skin; var pendingJoints = []; for ( var i = 0, il = skinEntry.joints.length; i < il; i ++ ) { pendingJoints.push( parser.getDependency( 'node', skinEntry.joints[ i ] ) ); } return Promise.all( pendingJoints ); } ).then( function ( jointNodes ) { node.traverse( function ( mesh ) { if ( ! mesh.isMesh ) return; var bones = []; var boneInverses = []; for ( var j = 0, jl = jointNodes.length; j < jl; j ++ ) { var jointNode = jointNodes[ j ]; if ( jointNode ) { bones.push( jointNode ); var mat = new THREE.Matrix4(); if ( skinEntry.inverseBindMatrices !== undefined ) { mat.fromArray( skinEntry.inverseBindMatrices.array, j * 16 ); } boneInverses.push( mat ); } else { console.warn( 'THREE.GLTFLoader: Joint "%s" could not be found.', skinEntry.joints[ j ] ); } } mesh.bind( new THREE.Skeleton( bones, boneInverses ), mesh.matrixWorld ); } ); return node; } ); } ).then( function ( node ) { // build node hierachy parentObject.add( node ); var pending = []; if ( nodeDef.children ) { var children = nodeDef.children; for ( var i = 0, il = children.length; i < il; i ++ ) { var child = children[ i ]; pending.push( buildNodeHierachy( child, node, json, parser ) ); } } return Promise.all( pending ); } ); } return function loadScene( sceneIndex ) { var json = this.json; var extensions = this.extensions; var sceneDef = this.json.scenes[ sceneIndex ]; var parser = this; var scene = new THREE.Scene(); if ( sceneDef.name !== undefined ) scene.name = sceneDef.name; assignExtrasToUserData( scene, sceneDef ); if ( sceneDef.extensions ) addUnknownExtensionsToUserData( extensions, scene, sceneDef ); var nodeIds = sceneDef.nodes || []; var pending = []; for ( var i = 0, il = nodeIds.length; i < il; i ++ ) { pending.push( buildNodeHierachy( nodeIds[ i ], scene, json, parser ) ); } return Promise.all( pending ).then( function () { return scene; } ); }; }(); return GLTFLoader; } )();
GLTFLoader: Update references to extension specs.
examples/js/loaders/GLTFLoader.js
GLTFLoader: Update references to extension specs.
<ide><path>xamples/js/loaders/GLTFLoader.js <ide> /** <ide> * DDS Texture Extension <ide> * <del> * Specification: <del> * https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds <add> * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_texture_dds <ide> * <ide> */ <ide> function GLTFTextureDDSExtension( ddsLoader ) { <ide> } <ide> <ide> /** <del> * Lights Extension <add> * Punctual Lights Extension <ide> * <del> * Specification: PENDING <add> * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_lights_punctual <ide> */ <ide> function GLTFLightsExtension( json ) { <ide> <ide> }; <ide> <ide> /** <del> * Unlit Materials Extension (pending) <add> * Unlit Materials Extension <ide> * <del> * PR: https://github.com/KhronosGroup/glTF/pull/1163 <add> * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit <ide> */ <ide> function GLTFMaterialsUnlitExtension() { <ide> <ide> /** <ide> * DRACO Mesh Compression Extension <ide> * <del> * Specification: https://github.com/KhronosGroup/glTF/pull/874 <add> * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression <ide> */ <ide> function GLTFDracoMeshCompressionExtension( json, dracoLoader ) { <ide> <ide> /** <ide> * Texture Transform Extension <ide> * <del> * Specification: <add> * Specification: https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_texture_transform <ide> */ <ide> function GLTFTextureTransformExtension() { <ide>
JavaScript
mit
b8b46e5e78083c63dc4bb5b7db479bdda6dc2469
0
tentone/nunuStudio,tentone/nunuStudio,tentone/nunuStudio
"use strict"; function MainMenu(parent) { Element.call(this, parent, "div"); this.element.style.overflow = "visible"; this.element.style.backgroundColor = Editor.theme.barColor; this.element.style.top = "0px"; this.element.style.left = "0px"; this.element.style.width = "100%"; this.element.style.height = "25px"; this.size.set(0, 25); this.preventDragEvents(); //Editor Logo var logo = document.createElement("img"); logo.style.display = "block"; logo.style.position = "absolute"; logo.style.pointerEvents = "none"; logo.style.width = "108px"; logo.style.height = "18px"; logo.style.top = "3px"; logo.style.right = "3px"; logo.src = Global.FILE_PATH + "logo.png"; this.element.appendChild(logo); //File var fileMenu = new DropdownMenu(this); fileMenu.setText("File"); fileMenu.size.set(120, this.size.y); fileMenu.position.set(0, 0); //New project fileMenu.addOption(Locale.new, function() { Editor.gui.newProgram(); }, Global.FILE_PATH + "icons/misc/new.png"); //Save project fileMenu.addOption(Locale.save, function() { if(Editor.openFile !== null) { Editor.saveProgram(undefined, true); } else { Editor.gui.saveProgram(); } }, Global.FILE_PATH + "icons/misc/save.png"); //Save project fileMenu.addOption(Locale.saveAs, function() { Editor.gui.saveProgram(); }, Global.FILE_PATH + "icons/misc/save.png").setAltText("CTRL+S"); //Save readable legacy format if(Nunu.developmentMode() && Nunu.runningOnDesktop()) { fileMenu.addOption("Save ISP", function() { FileSystem.chooseFile(function(files) { Editor.saveProgram(files[0].path, false, true); }, ".isp", true); }, Global.FILE_PATH + "icons/misc/save.png"); } //Load Project fileMenu.addOption(Locale.load, function() { Editor.gui.loadProgram(); }, Global.FILE_PATH + "icons/misc/load.png").setAltText("CTRL+L"); //Settings fileMenu.addOption(Locale.settings, function() { var tab = Editor.gui.tab.getTab(SettingsTab); if(tab === null) { tab = Editor.gui.tab.addTab(SettingsTab, true); } tab.select(); }, Global.FILE_PATH + "icons/misc/settings.png"); //Publish var publish = fileMenu.addMenu(Locale.publish, Global.FILE_PATH + "icons/misc/publish.png"); if(Nunu.runningOnDesktop()) { //Publish web publish.addOption("Web", function() { FileSystem.chooseFile(function(files) { try { Editor.exportWebProject(files[0].path); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, "", Editor.program.name); }, Global.FILE_PATH + "icons/platform/web.png"); //Android if(Nunu.developmentMode()) { var android = publish.addMenu("Android", Global.FILE_PATH + "icons/platform/android.png"); android.addOption(Locale.run, function() { try { Editor.exportAndroid(Editor.ANDROID_RUN); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }); android.addOption("Unsigned APK", function() { FileSystem.chooseFile(function(files) { try { Editor.exportAndroid(Editor.ANDROID_EXPORT_UNSIGNED, files[0].path); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, ".apk", Editor.program.name); }); } //Publish windows if(Editor.canExportWindows()) { publish.addOption("Windows", function() { FileSystem.chooseFile(function(files) { try { Editor.exportWindows(files[0].path); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, "", Editor.program.name); }, Global.FILE_PATH + "icons/platform/windows.png"); } //Publish linux if(Editor.canExportLinux()) { publish.addOption("Linux", function() { FileSystem.chooseFile(function(files) { try { Editor.exportLinux(files[0].path); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, "", Editor.program.name); }, Global.FILE_PATH + "icons/platform/linux.png"); } //Publish macos if(Editor.canExportMacOS()) { publish.addOption("macOS", function() { FileSystem.chooseFile(function(files) { try { Editor.exportMacOS(files[0].path); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, "", Editor.program.name); }, Global.FILE_PATH + "icons/platform/osx.png"); } } //Running on web browser else { publish.addOption("Web", function() { FileSystem.chooseFileName(function(fname) { try { Editor.exportWebProjectZip(fname); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, ".zip"); }, Global.FILE_PATH + "icons/platform/web.png"); } //Import fileMenu.addOption(Locale.import, function() { FileSystem.chooseFile(function(files) { if(files.length > 0) { var file = files[0]; var binary = file.name.endsWith(".nsp"); var loader = new ObjectLoader(); var reader = new FileReader(); reader.onload = function() { if(binary) { var pson = new dcodeIO.PSON.StaticPair(); var data = pson.decode(reader.result); var program = loader.parse(data); } else { var program = loader.parse(JSON.parse(reader.result)); } var actions = []; for(var i = 0; i < program.children.length; i++) { actions.push(new AddAction(program.children[i], Editor.program)); } Editor.addAction(new ActionBundle(actions)); }; if(binary) { reader.readAsArrayBuffer(file); } else { reader.readAsText(file); } } }, ".isp, .nsp"); }, Global.FILE_PATH + "icons/misc/import.png"); //Export menu var exportMenu = fileMenu.addMenu(Locale.export, Global.FILE_PATH + "icons/misc/export.png"); //Export OBJ exportMenu.addOption("OBJ", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.OBJExporter(); var data = exporter.parse(Editor.getScene()); FileSystem.writeFile(files[0].path, data); } }, ".obj", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.OBJExporter(); var data = exporter.parse(Editor.getScene()); FileSystem.writeFile(fname, data); }, ".obj"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export GLTF exportMenu.addOption("GLTF", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.GLTFExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFile(files[0].path, JSON.stringify(result, null, "\t")); }); } }, ".gltf", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.GLTFExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFile(fname, JSON.stringify(result, null, "\t")); }) }, ".gltf"); } }, Global.FILE_PATH + "icons/gltf.png"); //Export GLB exportMenu.addOption("GLB", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.GLTFExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFileArrayBuffer(files[0].path, result); }, {binary: true, forceIndices: true, forcePowerOfTwoTextures: true}); } }, ".glb", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.GLTFExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFileArrayBuffer(fname, result); }, {binary: true, forceIndices: true, forcePowerOfTwoTextures: true}); }, ".glb"); } }, Global.FILE_PATH + "icons/gltf.png"); //Export Google Draco exportMenu.addOption("Draco", function() { if(Editor.selection.length > 0 && Editor.selection[0].geometry !== undefined) { var geometry = Editor.selection[0].geometry; var exporter = new THREE.DRACOExporter(); if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { var arraybuffer = exporter.parse(geometry); FileSystem.writeFileArrayBuffer(files[0].path, arraybuffer); } }, ".drc", true); } else { FileSystem.chooseFileName(function(fname) { var arraybuffer = exporter.parse(geometry); FileSystem.writeFileArrayBuffer(fname, arraybuffer); }, ".drc"); } } else { Editor.alert(Locale.needsObjectGeometry); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export Collada exportMenu.addOption("Collada", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.ColladaExporter(); exporter.parse(Editor.getScene(), function(result) { //TODO <PROCESS result.textures> FileSystem.writeFile(files[0].path, result.data); }, {binary: false}); } }, ".dae", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.ColladaExporter(); exporter.parse(Editor.getScene(), function(result) { //TODO <PROCESS result.textures>b FileSystem.writeFile(fname, result.data); }, {binary: false}); }, ".dae"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export PLY exportMenu.addOption("PLY", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.PLYExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFile(files[0].path, result); }, {binary: false}); } }, ".ply", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.PLYExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFile(fname, result); }, {binary: false}); }, ".ply"); } }, Global.FILE_PATH + "icons/misc/scene.png"); exportMenu.addOption("PLY (Binary)", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.PLYExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFileArrayBuffer(files[0].path, result); }, {binary: true}); } }, ".ply", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.PLYExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFileArrayBuffer(fname, result); }, {binary: true}); }, ".ply"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export STL exportMenu.addOption("STL", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.STLExporter(); var data = exporter.parse(Editor.getScene()); FileSystem.writeFile(files[0].path, data); } }, ".stl", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.STLExporter(); var data = exporter.parse(Editor.getScene()); FileSystem.writeFile(fname, data); }, ".stl"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export Binary STL exportMenu.addOption("STL (Binary)", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { var exporter = new THREE.STLExporter(); var data = exporter.parse(Editor.program, {binary: true}); FileSystem.writeFileArrayBuffer(files[0].path, data.buffer); } }, ".stl", true); } else { FileSystem.chooseFileName(function(fname) { var exporter = new THREE.STLExporter(); var data = exporter.parse(Editor.program, {binary: true}); FileSystem.writeFileArrayBuffer(fname, data.buffer); }, ".stl"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Exit if(Nunu.runningOnDesktop()) { fileMenu.addOption(Locale.exit, function() { if(Editor.confirm(Locale.unsavedChangesExit)) { Editor.exit(); } }, Global.FILE_PATH + "icons/misc/exit.png"); } fileMenu.updateInterface(); //Editor var editMenu = new DropdownMenu(this); editMenu.setText("Edit"); editMenu.size.set(100, this.size.y); editMenu.position.set(120,0); editMenu.addOption(Locale.undo, function() { Editor.undo(); }, Global.FILE_PATH + "icons/misc/undo.png"); editMenu.addOption(Locale.redo, function() { Editor.redo(); }, Global.FILE_PATH + "icons/misc/redo.png"); editMenu.addOption(Locale.copy, function() { Editor.copyObject(); }, Global.FILE_PATH + "icons/misc/copy.png"); editMenu.addOption(Locale.cut, function() { Editor.cutObject(); }, Global.FILE_PATH + "icons/misc/cut.png"); editMenu.addOption(Locale.paste, function() { Editor.pasteObject(); }, Global.FILE_PATH + "icons/misc/paste.png"); editMenu.addOption(Locale.delete, function() { if(Editor.hasObjectSelected()) { var del = Editor.confirm(Locale.deleteObjects); if(del) { Editor.deleteObject(); } } }, Global.FILE_PATH + "icons/misc/delete.png"); var csg = editMenu.addMenu("CSG", Global.FILE_PATH + "icons/models/figures.png"); //Create BSP for CSG operation function createBSP(object) { var geometry = object.geometry; if(geometry instanceof THREE.BufferGeometry) { geometry = new THREE.Geometry().fromBufferGeometry(geometry); } else { geometry = geometry.clone(); } geometry.applyMatrix(object.matrixWorld); return new ThreeBSP(geometry); } //Verify is CSG operation is possible function verifyCSG() { if(Editor.selection.length < 2) { Editor.alert(Locale.needsTwoObjects); return false; } for(var i = 0; i < 2; i++) { if(Editor.selection[i].geometry === undefined) { Editor.alert(Locale.needsTwoObjectGeometry); return false; } } return true; } //Create CSG action function createCSGAction(mesh, a, b) { mesh.material = Editor.defaultMaterial; mesh.name = a.name; var actions = []; actions.push(new RemoveAction(a)); actions.push(new RemoveAction(b)); actions.push(new AddAction(mesh, a.getScene())); Editor.addAction(new ActionBundle(actions)); } csg.addOption(Locale.intersect, function() { if(verifyCSG()) { var a = createBSP(Editor.selection[0]); var b = createBSP(Editor.selection[1]); createCSGAction(a.intersect(b).toMesh(), Editor.selection[0], Editor.selection[1]); } }, Global.FILE_PATH + "icons/misc/intersect.png"); csg.addOption(Locale.subtract, function() { if(verifyCSG()) { var a = createBSP(Editor.selection[0]); var b = createBSP(Editor.selection[1]); createCSGAction(a.subtract(b).toMesh(), Editor.selection[0], Editor.selection[1]); } }, Global.FILE_PATH + "icons/misc/subtract.png"); csg.addOption(Locale.union, function() { if(verifyCSG()) { var a = createBSP(Editor.selection[0]); var b = createBSP(Editor.selection[1]); createCSGAction(a.union(b).toMesh(), Editor.selection[0], Editor.selection[1]); } }, Global.FILE_PATH + "icons/misc/union.png"); var modifiers = editMenu.addMenu("Modifiers", Global.FILE_PATH + "icons/models/figures.png"); modifiers.addOption(Locale.simplify, function() { if(Editor.selection.length < 1 || Editor.selection[0].geometry === undefined) { Editor.alert(Locale.needsObjectGeometry); return; } var simplifier = new THREE.SimplifyModifier(); var level = parseFloat(Editor.prompt("Simplification level in %")) / 100; if(isNaN(level) || level > 100 || level < 0) { Editor.alert("Level has to be a numeric value"); return; } var original = Editor.selection[0].geometry; if(original instanceof THREE.BufferGeometry) { var vertices = original.getAttribute("position").array.length / 3; } else { var vertices = original.vertices.length; } var geometry = simplifier.modify(original, Math.ceil(vertices * level)); var mesh = new Mesh(geometry, Editor.defaultMaterial); Editor.addObject(mesh); Editor.alert("Reduced from " + vertices + " to " + Math.ceil(vertices * level) + " vertex."); }, Global.FILE_PATH + "icons/models/figures.png"); modifiers.addOption("Subdivide", function() { if(Editor.selection.length < 1 || Editor.selection[0].geometry === undefined) { Editor.alert(Locale.needsObjectGeometry); return; } var modifier = new THREE.SubdivisionModifier(); var geometry = modifier.modify(Editor.selection[0].geometry); var mesh = new Mesh(geometry, Editor.defaultMaterial); Editor.addObject(mesh); }, Global.FILE_PATH + "icons/models/figures.png"); //Compute mesh normals editMenu.addOption(Locale.computeNormals, function() { if(Editor.selection.length < 1) { Editor.alert(Locale.needsObjectMesh); return; } Editor.selection[0].geometry.computeVertexNormals(); }, Global.FILE_PATH + "icons/misc/probe.png"); //Apply tranformation editMenu.addOption(Locale.applyTransformation, function() { if(Editor.selection.length < 1) { Editor.alert(Locale.needsObjectMesh); return; } var obj = Editor.selection[0]; obj.geometry.applyMatrix(obj.matrixWorld); obj.position.set(0, 0, 0); obj.scale.set(1, 1, 1); obj.rotation.set(0, 0, 0); }, Global.FILE_PATH + "icons/tools/move.png"); //Merge geometries editMenu.addOption("Merge geometries", function() { if(Editor.selection.length < 2) { Editor.alert(Locale.needsTwoObjectMesh); return; } var geometry = new THREE.Geometry(); for(var i = 0; i < Editor.selection.length; i++) { var obj = Editor.selection[i]; if(obj.geometry !== undefined) { //Convert to geometry and merge if(obj.geometry instanceof THREE.BufferGeometry) { var converted = new THREE.Geometry(); converted.fromBufferGeometry(obj.geometry); geometry.merge(converted, obj.matrixWorld) } //Merge geometry else { geometry.merge(obj.geometry, obj.matrixWorld) } } } var mesh = new Mesh(geometry, Editor.defaultMaterial); mesh.name = "merged"; Editor.addObject(mesh); }, Global.FILE_PATH + "icons/misc/union.png"); editMenu.updateInterface(); //Project var projectMenu = new DropdownMenu(this); projectMenu.setText(Locale.project); projectMenu.size.set(100, this.size.y); projectMenu.position.set(220,0); projectMenu.addOption(Locale.createScene, function() { Editor.addDefaultScene(); }, Global.FILE_PATH + "icons/misc/add.png"); projectMenu.addOption("Execute script", function() { FileSystem.chooseFile(function(files) { try { if(files.length > 0) { var code = FileSystem.readFile(files[0].path); var func = Function(code); func(); } } catch(error) { Editor.alert("Error: " + error); } }, ".js"); }, Global.FILE_PATH + "icons/script/script.png"); projectMenu.updateInterface(); //About var about = new ButtonText(this); about.setText(Locale.about); about.size.set(100, this.size.y); about.position.set(320, 0); about.updateInterface(); about.setOnClick(function() { var tab = Editor.gui.tab.getTab(AboutTab); if(tab === null) { tab = Editor.gui.tab.addTab(AboutTab, true); } tab.select(); }); //Run this.run = new ButtonText(this); this.run.setText(Locale.run); this.run.size.set(100, this.size.y); this.run.position.set(420, 0); this.run.updateInterface(); this.run.setOnClick(function() { Editor.runProject(); }); } MainMenu.prototype = Object.create(Element.prototype); MainMenu.prototype.updateInterface = function() { this.updateVisibility(); };
source/editor/MainMenu.js
"use strict"; function MainMenu(parent) { Element.call(this, parent, "div"); this.element.style.overflow = "visible"; this.element.style.backgroundColor = Editor.theme.barColor; this.element.style.top = "0px"; this.element.style.left = "0px"; this.element.style.width = "100%"; this.element.style.height = "25px"; this.size.set(0, 25); this.preventDragEvents(); //Editor Logo var logo = document.createElement("img"); logo.style.display = "block"; logo.style.position = "absolute"; logo.style.pointerEvents = "none"; logo.style.width = "108px"; logo.style.height = "18px"; logo.style.top = "3px"; logo.style.right = "3px"; logo.src = Global.FILE_PATH + "logo.png"; this.element.appendChild(logo); //File var fileMenu = new DropdownMenu(this); fileMenu.setText("File"); fileMenu.size.set(120, this.size.y); fileMenu.position.set(0, 0); //New project fileMenu.addOption(Locale.new, function() { Editor.gui.newProgram(); }, Global.FILE_PATH + "icons/misc/new.png"); //Save project fileMenu.addOption(Locale.save, function() { if(Editor.openFile !== null) { Editor.saveProgram(undefined, true); } else { Editor.gui.saveProgram(); } }, Global.FILE_PATH + "icons/misc/save.png"); //Save project fileMenu.addOption(Locale.saveAs, function() { Editor.gui.saveProgram(); }, Global.FILE_PATH + "icons/misc/save.png").setAltText("CTRL+S"); //Save readable legacy format if(Nunu.developmentMode() && Nunu.runningOnDesktop()) { fileMenu.addOption("Save ISP", function() { FileSystem.chooseFile(function(files) { Editor.saveProgram(files[0].path, false, true); }, ".isp", true); }, Global.FILE_PATH + "icons/misc/save.png"); } //Load Project fileMenu.addOption(Locale.load, function() { Editor.gui.loadProgram(); }, Global.FILE_PATH + "icons/misc/load.png").setAltText("CTRL+L"); //Settings fileMenu.addOption(Locale.settings, function() { var tab = Editor.gui.tab.getTab(SettingsTab); if(tab === null) { tab = Editor.gui.tab.addTab(SettingsTab, true); } tab.select(); }, Global.FILE_PATH + "icons/misc/settings.png"); //Publish var publish = fileMenu.addMenu(Locale.publish, Global.FILE_PATH + "icons/misc/publish.png"); if(Nunu.runningOnDesktop()) { //Publish web publish.addOption("Web", function() { FileSystem.chooseFile(function(files) { try { Editor.exportWebProject(files[0].path); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, "", Editor.program.name); }, Global.FILE_PATH + "icons/platform/web.png"); //Android if(Nunu.developmentMode()) { var android = publish.addMenu("Android", Global.FILE_PATH + "icons/platform/android.png"); android.addOption(Locale.run, function() { try { Editor.exportAndroid(Editor.ANDROID_RUN); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }); android.addOption("Unsigned APK", function() { FileSystem.chooseFile(function(files) { try { Editor.exportAndroid(Editor.ANDROID_EXPORT_UNSIGNED, files[0].path); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, ".apk", Editor.program.name); }); } //Publish windows if(Editor.canExportWindows()) { publish.addOption("Windows", function() { FileSystem.chooseFile(function(files) { try { Editor.exportWindows(files[0].path); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, "", Editor.program.name); }, Global.FILE_PATH + "icons/platform/windows.png"); } //Publish linux if(Editor.canExportLinux()) { publish.addOption("Linux", function() { FileSystem.chooseFile(function(files) { try { Editor.exportLinux(files[0].path); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, "", Editor.program.name); }, Global.FILE_PATH + "icons/platform/linux.png"); } //Publish macos if(Editor.canExportMacOS()) { publish.addOption("macOS", function() { FileSystem.chooseFile(function(files) { try { Editor.exportMacOS(files[0].path); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, "", Editor.program.name); }, Global.FILE_PATH + "icons/platform/osx.png"); } } //Running on web browser else { publish.addOption("Web", function() { FileSystem.chooseFileName(function(fname) { try { Editor.exportWebProjectZip(fname); Editor.alert(Locale.projectExported); } catch(e) { Editor.alert(Locale.errorExportingProject + "\n(" + e + ")"); } }, ".zip"); }, Global.FILE_PATH + "icons/platform/web.png"); } //Import fileMenu.addOption(Locale.import, function() { FileSystem.chooseFile(function(files) { if(files.length > 0) { var file = files[0]; var binary = file.name.endsWith(".nsp"); var loader = new ObjectLoader(); var reader = new FileReader(); reader.onload = function() { if(binary) { var pson = new dcodeIO.PSON.StaticPair(); var data = pson.decode(reader.result); var program = loader.parse(data); } else { var program = loader.parse(JSON.parse(reader.result)); } var actions = []; for(var i = 0; i < program.children.length; i++) { actions.push(new AddAction(program.children[i], Editor.program)); } Editor.addAction(new ActionBundle(actions)); }; if(binary) { reader.readAsArrayBuffer(file); } else { reader.readAsText(file); } } }, ".isp, .nsp"); }, Global.FILE_PATH + "icons/misc/import.png"); //Export menu var exportMenu = fileMenu.addMenu(Locale.export, Global.FILE_PATH + "icons/misc/export.png"); //Export OBJ exportMenu.addOption("OBJ", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.OBJExporter(); var data = exporter.parse(Editor.getScene()); FileSystem.writeFile(files[0].path, data); } }, ".obj", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.OBJExporter(); var data = exporter.parse(Editor.getScene()); FileSystem.writeFile(fname, data); }, ".obj"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export GLTF exportMenu.addOption("GLTF", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.GLTFExporter(); exporter.parse(Editor.getScene(), function(result) { var data = JSON.stringify(result, null, 2); FileSystem.writeFile(files[0].path, data); }); } }, ".gltf", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.GLTFExporter(); exporter.parse(Editor.getScene(), function(result) { var data = JSON.stringify(result, null, 2); FileSystem.writeFile(fname, data); }) }, ".gltf"); } }, Global.FILE_PATH + "icons/gltf.png"); //Export GLB exportMenu.addOption("GLB", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.GLTFExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFileArrayBuffer(files[0].path, result); }, {binary: true, forceIndices: true, forcePowerOfTwoTextures: true}); } }, ".glb", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.GLTFExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFileArrayBuffer(fname, result); }, {binary: true, forceIndices: true, forcePowerOfTwoTextures: true}); }, ".glb"); } }, Global.FILE_PATH + "icons/gltf.png"); //Export Google Draco exportMenu.addOption("Draco", function() { if(Editor.selection.length > 0 && Editor.selection[0].geometry !== undefined) { var geometry = Editor.selection[0].geometry; var exporter = new THREE.DRACOExporter(); if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { var arraybuffer = exporter.parse(geometry); FileSystem.writeFileArrayBuffer(files[0].path, arraybuffer); } }, ".drc", true); } else { FileSystem.chooseFileName(function(fname) { var arraybuffer = exporter.parse(geometry); FileSystem.writeFileArrayBuffer(fname, arraybuffer); }, ".drc"); } } else { Editor.alert(Locale.needsObjectGeometry); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export Collada exportMenu.addOption("Collada", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.ColladaExporter(); exporter.parse(Editor.getScene(), function(result) { //TODO <PROCESS result.textures> FileSystem.writeFile(files[0].path, result.data); }, {binary: false}); } }, ".dae", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.ColladaExporter(); exporter.parse(Editor.getScene(), function(result) { //TODO <PROCESS result.textures>b FileSystem.writeFile(fname, result.data); }, {binary: false}); }, ".dae"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export PLY exportMenu.addOption("PLY", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.PLYExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFile(files[0].path, result); }, {binary: false}); } }, ".ply", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.PLYExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFile(fname, result); }, {binary: false}); }, ".ply"); } }, Global.FILE_PATH + "icons/misc/scene.png"); exportMenu.addOption("PLY (Binary)", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.PLYExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFileArrayBuffer(files[0].path, result); }, {binary: true}); } }, ".ply", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.PLYExporter(); exporter.parse(Editor.getScene(), function(result) { FileSystem.writeFileArrayBuffer(fname, result); }, {binary: true}); }, ".ply"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export STL exportMenu.addOption("STL", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.STLExporter(); var data = exporter.parse(Editor.getScene()); FileSystem.writeFile(files[0].path, data); } }, ".stl", true); } else { FileSystem.chooseFileName(function(fname) { //TODO <SELECT SCENE TO EXPORT> var exporter = new THREE.STLExporter(); var data = exporter.parse(Editor.getScene()); FileSystem.writeFile(fname, data); }, ".stl"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Export Binary STL exportMenu.addOption("STL (Binary)", function() { if(Nunu.runningOnDesktop()) { FileSystem.chooseFile(function(files) { if(files.length > 0) { var exporter = new THREE.STLExporter(); var data = exporter.parse(Editor.program, {binary: true}); FileSystem.writeFileArrayBuffer(files[0].path, data.buffer); } }, ".stl", true); } else { FileSystem.chooseFileName(function(fname) { var exporter = new THREE.STLExporter(); var data = exporter.parse(Editor.program, {binary: true}); FileSystem.writeFileArrayBuffer(fname, data.buffer); }, ".stl"); } }, Global.FILE_PATH + "icons/misc/scene.png"); //Exit if(Nunu.runningOnDesktop()) { fileMenu.addOption(Locale.exit, function() { if(Editor.confirm(Locale.unsavedChangesExit)) { Editor.exit(); } }, Global.FILE_PATH + "icons/misc/exit.png"); } fileMenu.updateInterface(); //Editor var editMenu = new DropdownMenu(this); editMenu.setText("Edit"); editMenu.size.set(100, this.size.y); editMenu.position.set(120,0); editMenu.addOption(Locale.undo, function() { Editor.undo(); }, Global.FILE_PATH + "icons/misc/undo.png"); editMenu.addOption(Locale.redo, function() { Editor.redo(); }, Global.FILE_PATH + "icons/misc/redo.png"); editMenu.addOption(Locale.copy, function() { Editor.copyObject(); }, Global.FILE_PATH + "icons/misc/copy.png"); editMenu.addOption(Locale.cut, function() { Editor.cutObject(); }, Global.FILE_PATH + "icons/misc/cut.png"); editMenu.addOption(Locale.paste, function() { Editor.pasteObject(); }, Global.FILE_PATH + "icons/misc/paste.png"); editMenu.addOption(Locale.delete, function() { if(Editor.hasObjectSelected()) { var del = Editor.confirm(Locale.deleteObjects); if(del) { Editor.deleteObject(); } } }, Global.FILE_PATH + "icons/misc/delete.png"); var csg = editMenu.addMenu("CSG", Global.FILE_PATH + "icons/models/figures.png"); //Create BSP for CSG operation function createBSP(object) { var geometry = object.geometry; if(geometry instanceof THREE.BufferGeometry) { geometry = new THREE.Geometry().fromBufferGeometry(geometry); } else { geometry = geometry.clone(); } geometry.applyMatrix(object.matrixWorld); return new ThreeBSP(geometry); } //Verify is CSG operation is possible function verifyCSG() { if(Editor.selection.length < 2) { Editor.alert(Locale.needsTwoObjects); return false; } for(var i = 0; i < 2; i++) { if(Editor.selection[i].geometry === undefined) { Editor.alert(Locale.needsTwoObjectGeometry); return false; } } return true; } //Create CSG action function createCSGAction(mesh, a, b) { mesh.material = Editor.defaultMaterial; mesh.name = a.name; var actions = []; actions.push(new RemoveAction(a)); actions.push(new RemoveAction(b)); actions.push(new AddAction(mesh, a.getScene())); Editor.addAction(new ActionBundle(actions)); } csg.addOption(Locale.intersect, function() { if(verifyCSG()) { var a = createBSP(Editor.selection[0]); var b = createBSP(Editor.selection[1]); createCSGAction(a.intersect(b).toMesh(), Editor.selection[0], Editor.selection[1]); } }, Global.FILE_PATH + "icons/misc/intersect.png"); csg.addOption(Locale.subtract, function() { if(verifyCSG()) { var a = createBSP(Editor.selection[0]); var b = createBSP(Editor.selection[1]); createCSGAction(a.subtract(b).toMesh(), Editor.selection[0], Editor.selection[1]); } }, Global.FILE_PATH + "icons/misc/subtract.png"); csg.addOption(Locale.union, function() { if(verifyCSG()) { var a = createBSP(Editor.selection[0]); var b = createBSP(Editor.selection[1]); createCSGAction(a.union(b).toMesh(), Editor.selection[0], Editor.selection[1]); } }, Global.FILE_PATH + "icons/misc/union.png"); var modifiers = editMenu.addMenu("Modifiers", Global.FILE_PATH + "icons/models/figures.png"); modifiers.addOption(Locale.simplify, function() { if(Editor.selection.length < 1 || Editor.selection[0].geometry === undefined) { Editor.alert(Locale.needsObjectGeometry); return; } var simplifier = new THREE.SimplifyModifier(); var level = parseFloat(Editor.prompt("Simplification level in %")) / 100; if(isNaN(level) || level > 100 || level < 0) { Editor.alert("Level has to be a numeric value"); return; } var original = Editor.selection[0].geometry; if(original instanceof THREE.BufferGeometry) { var vertices = original.getAttribute("position").array.length / 3; } else { var vertices = original.vertices.length; } var geometry = simplifier.modify(original, Math.ceil(vertices * level)); var mesh = new Mesh(geometry, Editor.defaultMaterial); Editor.addObject(mesh); Editor.alert("Reduced from " + vertices + " to " + Math.ceil(vertices * level) + " vertex."); }, Global.FILE_PATH + "icons/models/figures.png"); modifiers.addOption("Subdivide", function() { if(Editor.selection.length < 1 || Editor.selection[0].geometry === undefined) { Editor.alert(Locale.needsObjectGeometry); return; } var modifier = new THREE.SubdivisionModifier(); var geometry = modifier.modify(Editor.selection[0].geometry); var mesh = new Mesh(geometry, Editor.defaultMaterial); Editor.addObject(mesh); }, Global.FILE_PATH + "icons/models/figures.png"); //Compute mesh normals editMenu.addOption(Locale.computeNormals, function() { if(Editor.selection.length < 1) { Editor.alert(Locale.needsObjectMesh); return; } Editor.selection[0].geometry.computeVertexNormals(); }, Global.FILE_PATH + "icons/misc/probe.png"); //Apply tranformation editMenu.addOption(Locale.applyTransformation, function() { if(Editor.selection.length < 1) { Editor.alert(Locale.needsObjectMesh); return; } var obj = Editor.selection[0]; obj.geometry.applyMatrix(obj.matrixWorld); obj.position.set(0, 0, 0); obj.scale.set(1, 1, 1); obj.rotation.set(0, 0, 0); }, Global.FILE_PATH + "icons/tools/move.png"); //Merge geometries editMenu.addOption("Merge geometries", function() { if(Editor.selection.length < 2) { Editor.alert(Locale.needsTwoObjectMesh); return; } var geometry = new THREE.Geometry(); for(var i = 0; i < Editor.selection.length; i++) { var obj = Editor.selection[i]; if(obj.geometry !== undefined) { //Convert to geometry and merge if(obj.geometry instanceof THREE.BufferGeometry) { var converted = new THREE.Geometry(); converted.fromBufferGeometry(obj.geometry); geometry.merge(converted, obj.matrixWorld) } //Merge geometry else { geometry.merge(obj.geometry, obj.matrixWorld) } } } var mesh = new Mesh(geometry, Editor.defaultMaterial); mesh.name = "merged"; Editor.addObject(mesh); }, Global.FILE_PATH + "icons/misc/union.png"); editMenu.updateInterface(); //Project var projectMenu = new DropdownMenu(this); projectMenu.setText(Locale.project); projectMenu.size.set(100, this.size.y); projectMenu.position.set(220,0); projectMenu.addOption(Locale.createScene, function() { Editor.addDefaultScene(); }, Global.FILE_PATH + "icons/misc/add.png"); projectMenu.addOption("Execute script", function() { FileSystem.chooseFile(function(files) { try { if(files.length > 0) { var code = FileSystem.readFile(files[0].path); var func = Function(code); func(); } } catch(error) { Editor.alert("Error: " + error); } }, ".js"); }, Global.FILE_PATH + "icons/script/script.png"); projectMenu.updateInterface(); //About var about = new ButtonText(this); about.setText(Locale.about); about.size.set(100, this.size.y); about.position.set(320, 0); about.updateInterface(); about.setOnClick(function() { var tab = Editor.gui.tab.getTab(AboutTab); if(tab === null) { tab = Editor.gui.tab.addTab(AboutTab, true); } tab.select(); }); //Run this.run = new ButtonText(this); this.run.setText(Locale.run); this.run.size.set(100, this.size.y); this.run.position.set(420, 0); this.run.updateInterface(); this.run.setOnClick(function() { Editor.runProject(); }); } MainMenu.prototype = Object.create(Element.prototype); MainMenu.prototype.updateInterface = function() { this.updateVisibility(); };
Clean up (GLTF json with tab)
source/editor/MainMenu.js
Clean up (GLTF json with tab)
<ide><path>ource/editor/MainMenu.js <ide> var exporter = new THREE.GLTFExporter(); <ide> exporter.parse(Editor.getScene(), function(result) <ide> { <del> var data = JSON.stringify(result, null, 2); <del> FileSystem.writeFile(files[0].path, data); <add> FileSystem.writeFile(files[0].path, JSON.stringify(result, null, "\t")); <ide> }); <ide> } <ide> }, ".gltf", true); <ide> var exporter = new THREE.GLTFExporter(); <ide> exporter.parse(Editor.getScene(), function(result) <ide> { <del> var data = JSON.stringify(result, null, 2); <del> FileSystem.writeFile(fname, data); <add> FileSystem.writeFile(fname, JSON.stringify(result, null, "\t")); <ide> }) <ide> }, ".gltf"); <ide> }
Java
apache-2.0
c6a479a6e3fd2190cb64bec5f54f2a3ac09ca2fd
0
christapley/windows-symbol-store-mojo
package org.tapley.windows.symbolstore; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class SymbolStoreActionCLI implements ISymbolStoreAction { public List<String> getAddCommand(File symStorePath, File repositoryPath, String symbolsPath, String applicationName, String applicationVersion, String comment, boolean recursive, boolean compress, boolean verboseOutput) { List<String> commandList = new ArrayList<>(); commandList.add("\"" + symStorePath.getAbsolutePath() + "\""); commandList.add("add"); if(recursive) { commandList.add("/r"); } if(verboseOutput) { commandList.add("/o"); } commandList.add("/s"); commandList.add(repositoryPath.getAbsolutePath()); commandList.add("/f"); commandList.add(symbolsPath); if(applicationName != null && !applicationName.isEmpty()) { commandList.add("/t"); commandList.add(applicationName); } if(applicationVersion != null && !applicationVersion.isEmpty()) { commandList.add("/v"); commandList.add(applicationVersion); } if(comment != null && !comment.isEmpty()) { commandList.add("/c"); commandList.add(comment); } if(compress) { commandList.add("/compress"); } return commandList; } @Override public String addPath(File symStorePath, File repositoryPath, String symbolsPath, String applicationName, String applicationVersion, String comment, boolean recursive, boolean compress, boolean verboseOutput) throws SymbolStoreException { try { return runCommand(getAddCommand(symStorePath, repositoryPath, symbolsPath, applicationName, applicationVersion, comment, recursive, compress, verboseOutput)); } catch(Exception ex) { throw new SymbolStoreException("Unable to add symbols from " + symbolsPath, ex); } } private List<String> getDeleteCommand(File symStorePath, File repositoryPath, String transactionId) { List<String> commandList = new ArrayList<>(); commandList.add(symStorePath.getAbsolutePath()); commandList.add("del"); commandList.add("/i"); commandList.add(transactionId); commandList.add("/s"); commandList.add(repositoryPath.getAbsolutePath()); return commandList; } private String runCommand(List<String> commandList) { CommandRunner runner = new CommandRunner(commandList); runner.run(); if(runner.getExitValue() != 0) { throw new IllegalStateException(String.format("Command '%s' exited with code %d. Output was '%s'", commandList, runner.getExitValue(), runner.getOutput())); } return runner.getOutput(); } @Override public String deleteTransaction(File symStorePath, File repositoryPath, String transactionId) throws SymbolStoreException { try { return runCommand(getDeleteCommand(symStorePath, repositoryPath, transactionId)); } catch(Exception ex) { throw new SymbolStoreException("Unable to delete transaction " + transactionId, ex); } } private File getServerListPath(File repositoryPath) { return new File(repositoryPath + File.separator + "000Admin", "server.txt"); } public TransactionEntry constructFromStringList(List<String> items) { TransactionEntry entry = new TransactionEntry(); entry.setTransactionId(items.get(0)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss"); entry.setInsertingTime(LocalDateTime.parse(String.format("%s %s", items.get(3), items.get(4)), formatter)); entry.setApplicationName(items.get(5)); entry.setApplicationVersion(items.get(6)); entry.setComment(items.get(7)); return entry; } @Override public List<TransactionEntry> getActiveTransactionList(File symStorePath, File repositoryPath) throws SymbolStoreException { try { List<TransactionEntry> transactionEntries = new ArrayList<>(); File serverTxt = getServerListPath(repositoryPath); if(serverTxt.exists()) { try (Stream<String> stream = Files.lines(Paths.get(serverTxt.getAbsolutePath()))) { stream.forEach((line) -> { List<String> items = Arrays.asList(line.split("\\s*,\\s*")); if(items != null && items.size() == 8) { transactionEntries.add(constructFromStringList(items)); } }); } } return transactionEntries; } catch(Exception ex) { throw new SymbolStoreException(String.format("Unable to parse transaction list from symbol path %s", symStorePath), ex); } } }
src/main/java/org/tapley/windows/symbolstore/SymbolStoreActionCLI.java
package org.tapley.windows.symbolstore; import java.io.File; import java.nio.file.Files; import java.nio.file.Paths; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class SymbolStoreActionCLI implements ISymbolStoreAction { private List<String> getAddCommand(File symStorePath, File repositoryPath, String symbolsPath, String applicationName, String applicationVersion, String comment, boolean recursive, boolean compress, boolean verboseOutput) { List<String> commandList = new ArrayList<>(); commandList.add("\"" + symStorePath.getAbsolutePath() + "\""); commandList.add("add"); if(recursive) { commandList.add("/r"); } if(verboseOutput) { commandList.add("/o"); } commandList.add("/s"); commandList.add(repositoryPath.getAbsolutePath()); commandList.add("/f"); commandList.add(symbolsPath); if(applicationName != null && !applicationName.isEmpty()) { commandList.add("/t"); commandList.add(applicationName); } if(applicationVersion != null && !applicationVersion.isEmpty()) { commandList.add("/v"); commandList.add(applicationVersion); } if(comment != null && !comment.isEmpty()) { commandList.add("/c"); commandList.add(comment); } if(compress) { commandList.add("/compress"); } return commandList; } @Override public String addPath(File symStorePath, File repositoryPath, String symbolsPath, String applicationName, String applicationVersion, String comment, boolean recursive, boolean compress, boolean verboseOutput) throws SymbolStoreException { try { return runCommand(getAddCommand(symStorePath, repositoryPath, symbolsPath, applicationName, applicationVersion, comment, recursive, compress, verboseOutput)); } catch(Exception ex) { throw new SymbolStoreException("Unable to add symbols from " + symbolsPath, ex); } } private List<String> getDeleteCommand(File symStorePath, File repositoryPath, String transactionId) { List<String> commandList = new ArrayList<>(); commandList.add(symStorePath.getAbsolutePath()); commandList.add("del"); commandList.add("/i"); commandList.add(transactionId); commandList.add("/s"); commandList.add(repositoryPath.getAbsolutePath()); return commandList; } private String runCommand(List<String> commandList) { CommandRunner runner = new CommandRunner(commandList); runner.run(); if(runner.getExitValue() != 0) { throw new IllegalStateException(String.format("Command '%s' exited with code %d. Output was '%s'", commandList, runner.getExitValue(), runner.getOutput())); } return runner.getOutput(); } @Override public String deleteTransaction(File symStorePath, File repositoryPath, String transactionId) throws SymbolStoreException { try { return runCommand(getDeleteCommand(symStorePath, repositoryPath, transactionId)); } catch(Exception ex) { throw new SymbolStoreException("Unable to delete transaction " + transactionId, ex); } } private File getServerListPath(File repositoryPath) { return new File(repositoryPath + File.separator + "000Admin", "server.txt"); } public TransactionEntry constructFromStringList(List<String> items) { TransactionEntry entry = new TransactionEntry(); entry.setTransactionId(items.get(0)); DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM/dd/yyyy HH:mm:ss"); entry.setInsertingTime(LocalDateTime.parse(String.format("%s %s", items.get(3), items.get(4)), formatter)); entry.setApplicationName(items.get(5)); entry.setApplicationVersion(items.get(6)); entry.setComment(items.get(7)); return entry; } @Override public List<TransactionEntry> getActiveTransactionList(File symStorePath, File repositoryPath) throws SymbolStoreException { try { List<TransactionEntry> transactionEntries = new ArrayList<>(); File serverTxt = getServerListPath(repositoryPath); if(serverTxt.exists()) { try (Stream<String> stream = Files.lines(Paths.get(serverTxt.getAbsolutePath()))) { stream.forEach((line) -> { List<String> items = Arrays.asList(line.split("\\s*,\\s*")); if(items != null && items.size() == 8) { transactionEntries.add(constructFromStringList(items)); } }); } } return transactionEntries; } catch(Exception ex) { throw new SymbolStoreException(String.format("Unable to parse transaction list from symbol path %s", symStorePath), ex); } } }
getCommand public
src/main/java/org/tapley/windows/symbolstore/SymbolStoreActionCLI.java
getCommand public
<ide><path>rc/main/java/org/tapley/windows/symbolstore/SymbolStoreActionCLI.java <ide> <ide> public class SymbolStoreActionCLI implements ISymbolStoreAction { <ide> <del> private List<String> getAddCommand(File symStorePath, File repositoryPath, String symbolsPath, String applicationName, String applicationVersion, String comment, boolean recursive, boolean compress, boolean verboseOutput) { <add> public List<String> getAddCommand(File symStorePath, File repositoryPath, String symbolsPath, String applicationName, String applicationVersion, String comment, boolean recursive, boolean compress, boolean verboseOutput) { <ide> List<String> commandList = new ArrayList<>(); <ide> <ide> commandList.add("\"" + symStorePath.getAbsolutePath() + "\"");
Java
unlicense
d69f9372ce56f48aa2fe1a9c5a3417c620ec6aec
0
Samourai-Wallet/sentinel-android
package com.samourai.sentinel; import android.animation.ObjectAnimator; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.InputType; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnticipateInterpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; //import android.util.Log; import org.apache.commons.codec.DecoderException; import org.apache.commons.lang3.StringUtils; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ECKey; import org.bitcoinj.crypto.BIP38PrivateKey; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.core.Coin; import org.bitcoinj.params.MainNetParams; import org.json.JSONException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.sentinel.access.AccessFactory; import com.samourai.sentinel.api.APIFactory; import com.samourai.sentinel.api.Tx; import com.samourai.sentinel.hd.HD_Account; import com.samourai.sentinel.hd.HD_Wallet; import com.samourai.sentinel.hd.HD_WalletFactory; import com.samourai.sentinel.service.WebSocketService; import com.samourai.sentinel.sweep.PrivKeyReader; import com.samourai.sentinel.sweep.SweepUtil; import com.samourai.sentinel.util.AddressFactory; import com.samourai.sentinel.util.AppUtil; import com.samourai.sentinel.util.BlockExplorerUtil; import com.samourai.sentinel.util.CharSequenceX; import com.samourai.sentinel.util.DateUtil; import com.samourai.sentinel.util.ExchangeRateFactory; import com.samourai.sentinel.util.MonetaryUtil; import com.samourai.sentinel.util.PrefsUtil; import com.samourai.sentinel.util.TimeOutUtil; import com.samourai.sentinel.util.TypefaceUtil; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu; import net.sourceforge.zbar.Symbol; public class BalanceActivity extends Activity { private final static int SCAN_COLD_STORAGE = 2011; private LinearLayout tvBalanceBar = null; private TextView tvBalanceAmount = null; private TextView tvBalanceUnits = null; private ListView txList = null; private List<Tx> txs = null; private HashMap<String, Boolean> txStates = null; private TransactionAdapter txAdapter = null; private SwipeRefreshLayout swipeRefreshLayout = null; private FloatingActionsMenu ibQuickSend = null; private FloatingActionButton actionReceive = null; private FloatingActionButton actionXPUB = null; private boolean isBTC = true; private static String[] account_selections = null; private static ArrayAdapter<String> adapter = null; private static ActionBar.OnNavigationListener navigationListener = null; public static final String ACTION_INTENT = "com.samourai.sentinel.BalanceFragment.REFRESH"; private ProgressDialog progress = null; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { refreshTx(false); } }); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance); BalanceActivity.this.getActionBar().setTitle(R.string.app_name); // // account selection // account_selections = new String[1]; account_selections[0] = ""; adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, account_selections); getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); navigationListener = new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { SamouraiSentinel.getInstance(BalanceActivity.this).setCurrentSelectedAccount(itemPosition); refreshTx(false); return false; } }; getActionBar().setListNavigationCallbacks(adapter, navigationListener); LayoutInflater inflator = BalanceActivity.this.getLayoutInflater(); tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null); tvBalanceBar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { isBTC = (isBTC) ? false : true; displayBalance(); txAdapter.notifyDataSetChanged(); return false; } }); tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount); tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits); ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu); actionReceive = (FloatingActionButton)findViewById(R.id.receive); actionReceive.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { confirmAccountSelection(false); } }); actionXPUB = (FloatingActionButton)findViewById(R.id.xpub); actionXPUB.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, XPUBListActivity.class); startActivity(intent); } }); txList = (ListView)findViewById(R.id.txList); txAdapter = new TransactionAdapter(); txList.setAdapter(txAdapter); txList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if(position == 0) { return; } long viewId = view.getId(); View v = (View)view.getParent(); Tx tx = txs.get(position - 1); ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount); if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) { if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } } else { String strTx = tx.getHash(); if(strTx != null) { int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0); CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerUrls()[sel]; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strTx)); startActivity(browserIntent); } } } }); swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swiperefresh); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().post(new Runnable() { @Override public void run() { refreshTx(true); } }); } }); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { BalanceActivity.this.startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } restoreWatchOnly(); } @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); } @Override public void onPause() { super.onPause(); LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.getItem(0).setVisible(false); menu.getItem(1).setVisible(false); menu.getItem(2).setVisible(true); restoreActionBar(); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { doSettings(); } else if (id == R.id.action_sweep) { confirmAccountSelection(true); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); doPrivKey(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AccessFactory.getInstance(BalanceActivity.this).setIsLoggedIn(false); TimeOutUtil.getInstance().reset(); dialog.dismiss(); Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); }}); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); }}); alert.show(); return true; } else { ; } return false; } public void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(R.string.app_name); } private void doSettings() { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class); startActivity(intent); } private class TransactionAdapter extends BaseAdapter { private LayoutInflater inflater = null; private static final int TYPE_ITEM = 0; private static final int TYPE_BALANCE = 1; TransactionAdapter() { inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } return txs.size() + 1; } @Override public String getItem(int position) { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } if(position == 0) { return ""; } return txs.get(position - 1).toString(); } @Override public long getItemId(int position) { return position - 1; } @Override public int getItemViewType(int position) { return position == 0 ? TYPE_BALANCE : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { View view = null; int type = getItemViewType(position); if(convertView == null) { if(type == TYPE_BALANCE) { view = tvBalanceBar; } else { view = inflater.inflate(R.layout.tx_layout_simple, parent, false); } } else { view = convertView; } if(type == TYPE_BALANCE) { ; } else { view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); Tx tx = txs.get(position - 1); TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel); String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS()); if(position == 1) { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } else { Tx prevTx = txs.get(position - 2); String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS()); if(strPrevDateGroup.equals(strDateGroup)) { tvTodayLabel.setVisibility(View.GONE); } else { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } } String strDetails = null; String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS()); long _amount = 0L; if(tx.getAmount() < 0.0) { _amount = Math.abs((long)tx.getAmount()); strDetails = BalanceActivity.this.getString(R.string.you_sent); } else { _amount = (long)tx.getAmount(); strDetails = BalanceActivity.this.getString(R.string.you_received); } String strAmount = null; String strUnits = null; if(isBTC) { strAmount = getBTCDisplayAmount(_amount); strUnits = getBTCDisplayUnits(); } else { strAmount = getFiatDisplayAmount(_amount); strUnits = getFiatDisplayUnits(); } TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection); TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2); TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails); ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount); tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface()); if(tx.getAmount() < 0.0) { tvDirection.setTextColor(Color.RED); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up)); } else { tvDirection.setTextColor(Color.GREEN); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down)); } if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits); tvDetails.setText(strTS); } return view; } } public void refreshTx(final boolean dragged) { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); int idx = SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount(); List<String> _xpubs = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); if(idx == 0) { APIFactory.getInstance(BalanceActivity.this).getXPUB(_xpubs.toArray(new String[_xpubs.size()])); } else { APIFactory.getInstance(BalanceActivity.this).getXPUB(new String[] { _xpubs.get(idx - 1) } ); } if(idx == 0) { txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs(); } else { txs = APIFactory.getInstance(BalanceActivity.this).getXpubTxs().get(_xpubs.get(idx - 1)); } try { if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null) { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get(); for(int i = 0; i < hdw.getAccounts().size(); i++) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(i).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestTxReceiveIdx(i)); } } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.FIRST_RUN, false); handler.post(new Runnable() { public void run() { if(dragged) { swipeRefreshLayout.setRefreshing(false); } txAdapter.notifyDataSetChanged(); displayBalance(); } }); Looper.loop(); } }).start(); } public void displayBalance() { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); int idx = SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount(); long balance = 0L; List<String> _xpubs = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); if(idx == 0) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance(); } else if(_xpubs.get(idx - 1) != null && APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(_xpubs.get(idx - 1)) != null) { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(_xpubs.get(idx - 1)) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(_xpubs.get(idx - 1)); } } else { ; } double btc_balance = (((double)balance) / 1e8); double fiat_balance = btc_fx * btc_balance; if(isBTC) { tvBalanceAmount.setText(getDisplayAmount(balance)); tvBalanceUnits.setText(getDisplayUnits()); } else { tvBalanceAmount.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(fiat_balance)); tvBalanceUnits.setText(strFiat); } } public String getDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat("#"); df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); int unit = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = df.format(((double)(value * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = df.format(((double)(value * 1000L)) / 1e8); break; default: strAmount = Coin.valueOf(value).toPlainString(); break; } return strAmount; } public String getDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) { if(heads) { if(confirmations == 0) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_query_builder_white); tvConfirmationCount.setVisibility(View.GONE); } else if(confirmations > 3) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_done_white); tvConfirmationCount.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } } else { if(confirmations < 100) { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText("\u221e"); ivTxStatus.setVisibility(View.GONE); } } } private void rotateTxStatus(View view, boolean clockwise) { float degrees = 360f; if(!clockwise) { degrees = -360f; } ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees); animation.setDuration(1000); animation.setRepeatCount(0); animation.setInterpolator(new AnticipateInterpolator()); animation.start(); } private void doSweepViaScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_COLD_STORAGE); } private void doSweep() { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.action_sweep) .setCancelable(false) .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final EditText privkey = new EditText(BalanceActivity.this); privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.enter_privkey) .setView(privkey) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String strPrivKey = privkey.getText().toString(); if(strPrivKey != null && strPrivKey.length() > 0) { doPrivKey(strPrivKey); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doSweepViaScan(); } }); if(!isFinishing()) { dlg.show(); } } private void doPrivKey(final String data) { // Log.d("BalanceActivity", "privkey:" + data); PrivKeyReader privKeyReader = null; String format = null; try { privKeyReader = new PrivKeyReader(new CharSequenceX(data), null); format = privKeyReader.getFormat(); // Log.d("BalanceActivity", "privkey format:" + format); } catch(Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } if(format != null) { if(format.equals(PrivKeyReader.BIP38)) { final PrivKeyReader pvr = privKeyReader; final EditText password38 = new EditText(BalanceActivity.this); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.bip38_pw) .setView(password38) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = password38.getText().toString(); ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.decrypting_bip38)); progress.show(); boolean keyDecoded = false; try { BIP38PrivateKey bip38 = new BIP38PrivateKey(MainNetParams.get(), data); final ECKey ecKey = bip38.decrypt(password); if(ecKey != null && ecKey.hasPrivKey()) { if(progress != null && progress.isShowing()) { progress.cancel(); } pvr.setPassword(new CharSequenceX(password)); keyDecoded = true; Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(MainNetParams.get()).toString(), Toast.LENGTH_SHORT).show(); } } catch(Exception e) { e.printStackTrace(); Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.cancel(); } if(keyDecoded) { String strReceiveAddress = SamouraiSentinel.getInstance(BalanceActivity.this).getReceiveAddress(); if(strReceiveAddress != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, strReceiveAddress); } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } }); if(!isFinishing()) { dlg.show(); } } else if(privKeyReader != null) { String strReceiveAddress = SamouraiSentinel.getInstance(BalanceActivity.this).getReceiveAddress(); Log.d("BalanceActivity", "receive address:" + strReceiveAddress); if(strReceiveAddress != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, strReceiveAddress); } } else { ; } } else { Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); } } private void confirmAccountSelection(final boolean isSweep) { final List<String> xpubList = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); if(xpubList.size() == 1) { SamouraiSentinel.getInstance(BalanceActivity.this).setCurrentSelectedAccount(1); Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); return; } final String[] accounts = new String[xpubList.size()]; for(int i = 0; i < xpubList.size(); i++) { if(xpubList.get(i).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().containsKey(xpubList.get(i))) { accounts[i] = SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().get(xpubList.get(i)); } else if(xpubList.get(i).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().containsKey(xpubList.get(i))) { accounts[i] = SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().get(xpubList.get(i)); } else { accounts[i] = SamouraiSentinel.getInstance(BalanceActivity.this).getLegacy().get(xpubList.get(i)); } } int sel = SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount() == 0 ? 0 : SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount() - 1; new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.deposit_into) .setSingleChoiceItems(accounts, sel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); SamouraiSentinel.getInstance(BalanceActivity.this).setCurrentSelectedAccount(which + 1); getActionBar().setSelectedNavigationItem(which + 1); if(isSweep) { doSweep(); } else { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } } } ).show(); } private void restoreWatchOnly() { final List<String> xpubList = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); final Handler handler = new Handler(); if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.please_wait)); progress.show(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); List<String> _xpubs = new ArrayList<String>(); for(String xpub : xpubList) { if(xpub.startsWith("xpub")) { _xpubs.add(xpub); } } if(_xpubs.size() > 0) { try { String xpubs = StringUtils.join(_xpubs.toArray(new String[_xpubs.size()]), ":"); // Log.i("BalanceActivity", xpubs); if(_xpubs.size() > 0) { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).restoreWallet(xpubs, null, 1); if(hdw != null) { List<HD_Account> accounts = hdw.getAccounts(); for(int i = 0; i < accounts.size(); i++) { AddressFactory.getInstance().account2xpub().put(i, _xpubs.get(i)); AddressFactory.getInstance().xpub2account().put(_xpubs.get(i), i); } } } } catch(DecoderException de) { PrefsUtil.getInstance(BalanceActivity.this).clear(); Toast.makeText(BalanceActivity.this, R.string.xpub_error, Toast.LENGTH_SHORT).show(); de.printStackTrace(); } catch(AddressFormatException afe) { PrefsUtil.getInstance(BalanceActivity.this).clear(); Toast.makeText(BalanceActivity.this, R.string.xpub_error, Toast.LENGTH_SHORT).show(); afe.printStackTrace(); } finally { ; } } if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } handler.post(new Runnable() { @Override public void run() { if(xpubList.size() == 1) { account_selections = new String[1]; if(xpubList.get(0).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().containsKey(xpubList.get(0))) { account_selections[0] = SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().get(xpubList.get(0)); } else if(xpubList.get(0).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().containsKey(xpubList.get(0))) { account_selections[0] = SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().get(xpubList.get(0)); } else { account_selections[0] = SamouraiSentinel.getInstance(BalanceActivity.this).getLegacy().get(xpubList.get(0)); } } else { account_selections = new String[xpubList.size() + 1]; account_selections[0] = BalanceActivity.this.getString(R.string.total_title); for(int i = 0; i < xpubList.size(); i++) { if(xpubList.get(i).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().containsKey(xpubList.get(i))) { account_selections[i + 1] = SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().get(xpubList.get(i)); } else if(xpubList.get(i).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().containsKey(xpubList.get(i))) { account_selections[i + 1] = SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().get(xpubList.get(i)); } else { account_selections[i + 1] = SamouraiSentinel.getInstance(BalanceActivity.this).getLegacy().get(xpubList.get(i)); } } } if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, account_selections); } else { adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.spinner_dropdown, account_selections); } getActionBar().setListNavigationCallbacks(adapter, navigationListener); adapter.notifyDataSetChanged(); if(account_selections.length == 1) { SamouraiSentinel.getInstance(BalanceActivity.this).setCurrentSelectedAccount(0); } refreshTx(false); try { SamouraiSentinel.getInstance(BalanceActivity.this).serialize(SamouraiSentinel.getInstance(BalanceActivity.this).toJSON(), null); } catch(IOException ioe) { ; } catch(JSONException je) { ; } } }); Looper.loop(); } }).start(); } private String getBTCDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat("#"); df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); int unit = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = df.format(((double)(value * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = df.format(((double)(value * 1000L)) / 1e8); break; default: strAmount = Coin.valueOf(value).toPlainString(); break; } return strAmount; } private String getBTCDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private String getFiatDisplayAmount(long value) { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); String strAmount = MonetaryUtil.getInstance().getFiatFormat(strFiat).format(btc_fx * (((double)value) / 1e8)); return strAmount; } private String getFiatDisplayUnits() { return PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); } }
app/src/main/java/com/samourai/sentinel/BalanceActivity.java
package com.samourai.sentinel; import android.animation.ObjectAnimator; import android.app.ActionBar; import android.app.Activity; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Color; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.v4.content.LocalBroadcastManager; import android.support.v4.widget.SwipeRefreshLayout; import android.text.InputType; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.animation.AnticipateInterpolator; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; //import android.util.Log; import org.apache.commons.codec.DecoderException; import org.apache.commons.lang3.StringUtils; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.ECKey; import org.bitcoinj.crypto.BIP38PrivateKey; import org.bitcoinj.crypto.MnemonicException; import org.bitcoinj.core.Coin; import org.bitcoinj.params.MainNetParams; import org.json.JSONException; import com.dm.zbar.android.scanner.ZBarConstants; import com.dm.zbar.android.scanner.ZBarScannerActivity; import com.samourai.sentinel.access.AccessFactory; import com.samourai.sentinel.api.APIFactory; import com.samourai.sentinel.api.Tx; import com.samourai.sentinel.hd.HD_Account; import com.samourai.sentinel.hd.HD_Wallet; import com.samourai.sentinel.hd.HD_WalletFactory; import com.samourai.sentinel.service.WebSocketService; import com.samourai.sentinel.sweep.PrivKeyReader; import com.samourai.sentinel.sweep.SweepUtil; import com.samourai.sentinel.util.AddressFactory; import com.samourai.sentinel.util.AppUtil; import com.samourai.sentinel.util.BlockExplorerUtil; import com.samourai.sentinel.util.CharSequenceX; import com.samourai.sentinel.util.DateUtil; import com.samourai.sentinel.util.ExchangeRateFactory; import com.samourai.sentinel.util.MonetaryUtil; import com.samourai.sentinel.util.PrefsUtil; import com.samourai.sentinel.util.TimeOutUtil; import com.samourai.sentinel.util.TypefaceUtil; import java.io.IOException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Set; import net.i2p.android.ext.floatingactionbutton.FloatingActionButton; import net.i2p.android.ext.floatingactionbutton.FloatingActionsMenu; import net.sourceforge.zbar.Symbol; public class BalanceActivity extends Activity { private final static int SCAN_COLD_STORAGE = 2011; private LinearLayout tvBalanceBar = null; private TextView tvBalanceAmount = null; private TextView tvBalanceUnits = null; private ListView txList = null; private List<Tx> txs = null; private HashMap<String, Boolean> txStates = null; private TransactionAdapter txAdapter = null; private SwipeRefreshLayout swipeRefreshLayout = null; private FloatingActionsMenu ibQuickSend = null; private FloatingActionButton actionReceive = null; private FloatingActionButton actionXPUB = null; private boolean isBTC = true; private static String[] account_selections = null; private static ArrayAdapter<String> adapter = null; private static ActionBar.OnNavigationListener navigationListener = null; public static final String ACTION_INTENT = "com.samourai.sentinel.BalanceFragment.REFRESH"; private ProgressDialog progress = null; protected BroadcastReceiver receiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if(ACTION_INTENT.equals(intent.getAction())) { BalanceActivity.this.runOnUiThread(new Runnable() { @Override public void run() { displayBalance(); refreshTx(false); } }); } } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_balance); BalanceActivity.this.getActionBar().setTitle(R.string.app_name); // // account selection // account_selections = new String[1]; account_selections[0] = ""; adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, account_selections); getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); navigationListener = new ActionBar.OnNavigationListener() { @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { SamouraiSentinel.getInstance(BalanceActivity.this).setCurrentSelectedAccount(itemPosition); refreshTx(false); return false; } }; getActionBar().setListNavigationCallbacks(adapter, navigationListener); LayoutInflater inflator = BalanceActivity.this.getLayoutInflater(); tvBalanceBar = (LinearLayout)inflator.inflate(R.layout.balance_layout, null); tvBalanceBar.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { isBTC = (isBTC) ? false : true; displayBalance(); txAdapter.notifyDataSetChanged(); return false; } }); tvBalanceAmount = (TextView)tvBalanceBar.findViewById(R.id.BalanceAmount); tvBalanceUnits = (TextView)tvBalanceBar.findViewById(R.id.BalanceUnits); ibQuickSend = (FloatingActionsMenu)findViewById(R.id.wallet_menu); actionReceive = (FloatingActionButton)findViewById(R.id.receive); actionReceive.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { confirmAccountSelection(false); } }); actionXPUB = (FloatingActionButton)findViewById(R.id.xpub); actionXPUB.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, XPUBListActivity.class); startActivity(intent); } }); txList = (ListView)findViewById(R.id.txList); txAdapter = new TransactionAdapter(); txList.setAdapter(txAdapter); txList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, final View view, int position, long id) { if(position == 0) { return; } long viewId = view.getId(); View v = (View)view.getParent(); Tx tx = txs.get(position - 1); ImageView ivTxStatus = (ImageView)v.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)v.findViewById(R.id.ConfirmationCount); if(viewId == R.id.ConfirmationCount || viewId == R.id.TransactionStatus) { if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == true) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } } else { String strTx = tx.getHash(); if(strTx != null) { int sel = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BLOCK_EXPLORER, 0); CharSequence url = BlockExplorerUtil.getInstance().getBlockExplorerUrls()[sel]; Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url + strTx)); startActivity(browserIntent); } } } }); swipeRefreshLayout = (SwipeRefreshLayout)findViewById(R.id.swiperefresh); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().post(new Runnable() { @Override public void run() { refreshTx(true); } }); } }); swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_bright, android.R.color.holo_green_light, android.R.color.holo_orange_light, android.R.color.holo_red_light); if(!AppUtil.getInstance(BalanceActivity.this.getApplicationContext()).isServiceRunning(WebSocketService.class)) { BalanceActivity.this.startService(new Intent(BalanceActivity.this.getApplicationContext(), WebSocketService.class)); } restoreWatchOnly(); } @Override public void onResume() { super.onResume(); IntentFilter filter = new IntentFilter(ACTION_INTENT); LocalBroadcastManager.getInstance(BalanceActivity.this).registerReceiver(receiver, filter); AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); displayBalance(); refreshTx(false); } @Override public void onPause() { super.onPause(); LocalBroadcastManager.getInstance(BalanceActivity.this).unregisterReceiver(receiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); menu.getItem(0).setVisible(false); menu.getItem(1).setVisible(false); menu.getItem(2).setVisible(true); restoreActionBar(); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { doSettings(); } else if (id == R.id.action_sweep) { confirmAccountSelection(true); } else { ; } return super.onOptionsItemSelected(item); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(resultCode == Activity.RESULT_OK && requestCode == SCAN_COLD_STORAGE) { if(data != null && data.getStringExtra(ZBarConstants.SCAN_RESULT) != null) { final String strResult = data.getStringExtra(ZBarConstants.SCAN_RESULT); doPrivKey(strResult); } } else if(resultCode == Activity.RESULT_CANCELED && requestCode == SCAN_COLD_STORAGE) { ; } else { ; } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if(keyCode == KeyEvent.KEYCODE_BACK) { AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.ask_you_sure_exit).setCancelable(false); AlertDialog alert = builder.create(); alert.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { AccessFactory.getInstance(BalanceActivity.this).setIsLoggedIn(false); TimeOutUtil.getInstance().reset(); dialog.dismiss(); Intent intent = new Intent(BalanceActivity.this, ExodusActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); }}); alert.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.cancel), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); }}); alert.show(); return true; } else { ; } return false; } public void restoreActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(true); actionBar.setTitle(R.string.app_name); } private void doSettings() { TimeOutUtil.getInstance().updatePin(); Intent intent = new Intent(BalanceActivity.this, SettingsActivity.class); startActivity(intent); } private class TransactionAdapter extends BaseAdapter { private LayoutInflater inflater = null; private static final int TYPE_ITEM = 0; private static final int TYPE_BALANCE = 1; TransactionAdapter() { inflater = (LayoutInflater)BalanceActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } return txs.size() + 1; } @Override public String getItem(int position) { if(txs == null) { txs = new ArrayList<Tx>(); txStates = new HashMap<String, Boolean>(); } if(position == 0) { return ""; } return txs.get(position - 1).toString(); } @Override public long getItemId(int position) { return position - 1; } @Override public int getItemViewType(int position) { return position == 0 ? TYPE_BALANCE : TYPE_ITEM; } @Override public int getViewTypeCount() { return 2; } @Override public View getView(final int position, View convertView, final ViewGroup parent) { View view = null; int type = getItemViewType(position); if(convertView == null) { if(type == TYPE_BALANCE) { view = tvBalanceBar; } else { view = inflater.inflate(R.layout.tx_layout_simple, parent, false); } } else { view = convertView; } if(type == TYPE_BALANCE) { ; } else { view.findViewById(R.id.TransactionStatus).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); view.findViewById(R.id.ConfirmationCount).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { ((ListView)parent).performItemClick(v, position, 0); } }); Tx tx = txs.get(position - 1); TextView tvTodayLabel = (TextView)view.findViewById(R.id.TodayLabel); String strDateGroup = DateUtil.getInstance(BalanceActivity.this).group(tx.getTS()); if(position == 1) { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } else { Tx prevTx = txs.get(position - 2); String strPrevDateGroup = DateUtil.getInstance(BalanceActivity.this).group(prevTx.getTS()); if(strPrevDateGroup.equals(strDateGroup)) { tvTodayLabel.setVisibility(View.GONE); } else { tvTodayLabel.setText(strDateGroup); tvTodayLabel.setVisibility(View.VISIBLE); } } String strDetails = null; String strTS = DateUtil.getInstance(BalanceActivity.this).formatted(tx.getTS()); long _amount = 0L; if(tx.getAmount() < 0.0) { _amount = Math.abs((long)tx.getAmount()); strDetails = BalanceActivity.this.getString(R.string.you_sent); } else { _amount = (long)tx.getAmount(); strDetails = BalanceActivity.this.getString(R.string.you_received); } String strAmount = null; String strUnits = null; if(isBTC) { strAmount = getBTCDisplayAmount(_amount); strUnits = getBTCDisplayUnits(); } else { strAmount = getFiatDisplayAmount(_amount); strUnits = getFiatDisplayUnits(); } TextView tvDirection = (TextView)view.findViewById(R.id.TransactionDirection); TextView tvDirection2 = (TextView)view.findViewById(R.id.TransactionDirection2); TextView tvDetails = (TextView)view.findViewById(R.id.TransactionDetails); ImageView ivTxStatus = (ImageView)view.findViewById(R.id.TransactionStatus); TextView tvConfirmationCount = (TextView)view.findViewById(R.id.ConfirmationCount); tvDirection.setTypeface(TypefaceUtil.getInstance(BalanceActivity.this).getAwesomeTypeface()); if(tx.getAmount() < 0.0) { tvDirection.setTextColor(Color.RED); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_up)); } else { tvDirection.setTextColor(Color.GREEN); tvDirection.setText(Character.toString((char) TypefaceUtil.awesome_arrow_down)); } if(txStates.containsKey(tx.getHash()) && txStates.get(tx.getHash()) == false) { txStates.put(tx.getHash(), false); displayTxStatus(false, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } else { txStates.put(tx.getHash(), true); displayTxStatus(true, tx.getConfirmations(), tvConfirmationCount, ivTxStatus); } tvDirection2.setText(strDetails + " " + strAmount + " " + strUnits); tvDetails.setText(strTS); } return view; } } public void refreshTx(final boolean dragged) { final Handler handler = new Handler(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); int idx = SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount(); List<String> _xpubs = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); APIFactory.getInstance(BalanceActivity.this).getXPUB(_xpubs.toArray(new String[_xpubs.size()])); if(idx == 0) { txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs(); } else { txs = APIFactory.getInstance(BalanceActivity.this).getXpubTxs().get(_xpubs.get(idx - 1)); } try { if(HD_WalletFactory.getInstance(BalanceActivity.this).get() != null) { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).get(); for(int i = 0; i < hdw.getAccounts().size(); i++) { HD_WalletFactory.getInstance(BalanceActivity.this).get().getAccount(i).getReceive().setAddrIdx(AddressFactory.getInstance().getHighestTxReceiveIdx(i)); } } } catch(IOException ioe) { ; } catch(MnemonicException.MnemonicLengthException mle) { ; } PrefsUtil.getInstance(BalanceActivity.this).setValue(PrefsUtil.FIRST_RUN, false); handler.post(new Runnable() { public void run() { if(dragged) { swipeRefreshLayout.setRefreshing(false); } txAdapter.notifyDataSetChanged(); displayBalance(); } }); Looper.loop(); } }).start(); } public void displayBalance() { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); int idx = SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount(); long balance = 0L; List<String> _xpubs = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); if(idx == 0) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubBalance(); } else if(_xpubs.get(idx - 1) != null && APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(_xpubs.get(idx - 1)) != null) { if(APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(_xpubs.get(idx - 1)) != null) { balance = APIFactory.getInstance(BalanceActivity.this).getXpubAmounts().get(_xpubs.get(idx - 1)); } } else { ; } double btc_balance = (((double)balance) / 1e8); double fiat_balance = btc_fx * btc_balance; if(isBTC) { tvBalanceAmount.setText(getDisplayAmount(balance)); tvBalanceUnits.setText(getDisplayUnits()); } else { tvBalanceAmount.setText(MonetaryUtil.getInstance().getFiatFormat(strFiat).format(fiat_balance)); tvBalanceUnits.setText(strFiat); } } public String getDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat("#"); df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); int unit = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = df.format(((double)(value * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = df.format(((double)(value * 1000L)) / 1e8); break; default: strAmount = Coin.valueOf(value).toPlainString(); break; } return strAmount; } public String getDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private void displayTxStatus(boolean heads, long confirmations, TextView tvConfirmationCount, ImageView ivTxStatus) { if(heads) { if(confirmations == 0) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_query_builder_white); tvConfirmationCount.setVisibility(View.GONE); } else if(confirmations > 3) { rotateTxStatus(tvConfirmationCount, true); ivTxStatus.setVisibility(View.VISIBLE); ivTxStatus.setImageResource(R.drawable.ic_done_white); tvConfirmationCount.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } } else { if(confirmations < 100) { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText(Long.toString(confirmations)); ivTxStatus.setVisibility(View.GONE); } else { rotateTxStatus(ivTxStatus, false); tvConfirmationCount.setVisibility(View.VISIBLE); tvConfirmationCount.setText("\u221e"); ivTxStatus.setVisibility(View.GONE); } } } private void rotateTxStatus(View view, boolean clockwise) { float degrees = 360f; if(!clockwise) { degrees = -360f; } ObjectAnimator animation = ObjectAnimator.ofFloat(view, "rotationY", 0.0f, degrees); animation.setDuration(1000); animation.setRepeatCount(0); animation.setInterpolator(new AnticipateInterpolator()); animation.start(); } private void doSweepViaScan() { Intent intent = new Intent(BalanceActivity.this, ZBarScannerActivity.class); intent.putExtra(ZBarConstants.SCAN_MODES, new int[]{ Symbol.QRCODE } ); startActivityForResult(intent, SCAN_COLD_STORAGE); } private void doSweep() { AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.action_sweep) .setCancelable(false) .setPositiveButton(R.string.enter_privkey, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final EditText privkey = new EditText(BalanceActivity.this); privkey.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.enter_privkey) .setView(privkey) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { final String strPrivKey = privkey.getText().toString(); if(strPrivKey != null && strPrivKey.length() > 0) { doPrivKey(strPrivKey); } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { dialog.dismiss(); } }); if(!isFinishing()) { dlg.show(); } } }).setNegativeButton(R.string.scan, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { doSweepViaScan(); } }); if(!isFinishing()) { dlg.show(); } } private void doPrivKey(final String data) { // Log.d("BalanceActivity", "privkey:" + data); PrivKeyReader privKeyReader = null; String format = null; try { privKeyReader = new PrivKeyReader(new CharSequenceX(data), null); format = privKeyReader.getFormat(); // Log.d("BalanceActivity", "privkey format:" + format); } catch(Exception e) { Toast.makeText(BalanceActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show(); return; } if(format != null) { if(format.equals(PrivKeyReader.BIP38)) { final PrivKeyReader pvr = privKeyReader; final EditText password38 = new EditText(BalanceActivity.this); AlertDialog.Builder dlg = new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.app_name) .setMessage(R.string.bip38_pw) .setView(password38) .setCancelable(false) .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String password = password38.getText().toString(); ProgressDialog progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.decrypting_bip38)); progress.show(); boolean keyDecoded = false; try { BIP38PrivateKey bip38 = new BIP38PrivateKey(MainNetParams.get(), data); final ECKey ecKey = bip38.decrypt(password); if(ecKey != null && ecKey.hasPrivKey()) { if(progress != null && progress.isShowing()) { progress.cancel(); } pvr.setPassword(new CharSequenceX(password)); keyDecoded = true; Toast.makeText(BalanceActivity.this, pvr.getFormat(), Toast.LENGTH_SHORT).show(); Toast.makeText(BalanceActivity.this, pvr.getKey().toAddress(MainNetParams.get()).toString(), Toast.LENGTH_SHORT).show(); } } catch(Exception e) { e.printStackTrace(); Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } if(progress != null && progress.isShowing()) { progress.cancel(); } if(keyDecoded) { String strReceiveAddress = SamouraiSentinel.getInstance(BalanceActivity.this).getReceiveAddress(); if(strReceiveAddress != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(pvr, strReceiveAddress); } } } }).setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Toast.makeText(BalanceActivity.this, R.string.bip38_pw_error, Toast.LENGTH_SHORT).show(); } }); if(!isFinishing()) { dlg.show(); } } else if(privKeyReader != null) { String strReceiveAddress = SamouraiSentinel.getInstance(BalanceActivity.this).getReceiveAddress(); Log.d("BalanceActivity", "receive address:" + strReceiveAddress); if(strReceiveAddress != null) { SweepUtil.getInstance(BalanceActivity.this).sweep(privKeyReader, strReceiveAddress); } } else { ; } } else { Toast.makeText(BalanceActivity.this, R.string.cannot_recognize_privkey, Toast.LENGTH_SHORT).show(); } } private void confirmAccountSelection(final boolean isSweep) { final List<String> xpubList = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); if(xpubList.size() == 1) { SamouraiSentinel.getInstance(BalanceActivity.this).setCurrentSelectedAccount(1); Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); return; } final String[] accounts = new String[xpubList.size()]; for(int i = 0; i < xpubList.size(); i++) { if(xpubList.get(i).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().containsKey(xpubList.get(i))) { accounts[i] = SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().get(xpubList.get(i)); } else if(xpubList.get(i).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().containsKey(xpubList.get(i))) { accounts[i] = SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().get(xpubList.get(i)); } else { accounts[i] = SamouraiSentinel.getInstance(BalanceActivity.this).getLegacy().get(xpubList.get(i)); } } int sel = SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount() == 0 ? 0 : SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount() - 1; new AlertDialog.Builder(BalanceActivity.this) .setTitle(R.string.deposit_into) .setSingleChoiceItems(accounts, sel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); SamouraiSentinel.getInstance(BalanceActivity.this).setCurrentSelectedAccount(which + 1); getActionBar().setSelectedNavigationItem(which + 1); if(isSweep) { doSweep(); } else { Intent intent = new Intent(BalanceActivity.this, ReceiveActivity.class); startActivity(intent); } } } ).show(); } private void restoreWatchOnly() { final List<String> xpubList = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); final Handler handler = new Handler(); if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } progress = new ProgressDialog(BalanceActivity.this); progress.setCancelable(false); progress.setTitle(R.string.app_name); progress.setMessage(getString(R.string.please_wait)); progress.show(); new Thread(new Runnable() { @Override public void run() { Looper.prepare(); List<String> _xpubs = new ArrayList<String>(); for(String xpub : xpubList) { if(xpub.startsWith("xpub")) { _xpubs.add(xpub); } } if(_xpubs.size() > 0) { try { String xpubs = StringUtils.join(_xpubs.toArray(new String[_xpubs.size()]), ":"); // Log.i("BalanceActivity", xpubs); if(_xpubs.size() > 0) { HD_Wallet hdw = HD_WalletFactory.getInstance(BalanceActivity.this).restoreWallet(xpubs, null, 1); if(hdw != null) { List<HD_Account> accounts = hdw.getAccounts(); for(int i = 0; i < accounts.size(); i++) { AddressFactory.getInstance().account2xpub().put(i, _xpubs.get(i)); AddressFactory.getInstance().xpub2account().put(_xpubs.get(i), i); } } } } catch(DecoderException de) { PrefsUtil.getInstance(BalanceActivity.this).clear(); Toast.makeText(BalanceActivity.this, R.string.xpub_error, Toast.LENGTH_SHORT).show(); de.printStackTrace(); } catch(AddressFormatException afe) { PrefsUtil.getInstance(BalanceActivity.this).clear(); Toast.makeText(BalanceActivity.this, R.string.xpub_error, Toast.LENGTH_SHORT).show(); afe.printStackTrace(); } finally { ; } } if (progress != null && progress.isShowing()) { progress.dismiss(); progress = null; } handler.post(new Runnable() { @Override public void run() { if(xpubList.size() == 1) { account_selections = new String[1]; if(xpubList.get(0).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().containsKey(xpubList.get(0))) { account_selections[0] = SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().get(xpubList.get(0)); } else if(xpubList.get(0).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().containsKey(xpubList.get(0))) { account_selections[0] = SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().get(xpubList.get(0)); } else { account_selections[0] = SamouraiSentinel.getInstance(BalanceActivity.this).getLegacy().get(xpubList.get(0)); } } else { account_selections = new String[xpubList.size() + 1]; account_selections[0] = BalanceActivity.this.getString(R.string.total_title); for(int i = 0; i < xpubList.size(); i++) { if(xpubList.get(i).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().containsKey(xpubList.get(i))) { account_selections[i + 1] = SamouraiSentinel.getInstance(BalanceActivity.this).getXPUBs().get(xpubList.get(i)); } else if(xpubList.get(i).startsWith("xpub") && SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().containsKey(xpubList.get(i))) { account_selections[i + 1] = SamouraiSentinel.getInstance(BalanceActivity.this).getBIP49().get(xpubList.get(i)); } else { account_selections[i + 1] = SamouraiSentinel.getInstance(BalanceActivity.this).getLegacy().get(xpubList.get(i)); } } } if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, account_selections); } else { adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.spinner_dropdown, account_selections); } getActionBar().setListNavigationCallbacks(adapter, navigationListener); adapter.notifyDataSetChanged(); if(account_selections.length == 1) { SamouraiSentinel.getInstance(BalanceActivity.this).setCurrentSelectedAccount(0); } refreshTx(false); try { SamouraiSentinel.getInstance(BalanceActivity.this).serialize(SamouraiSentinel.getInstance(BalanceActivity.this).toJSON(), null); } catch(IOException ioe) { ; } catch(JSONException je) { ; } } }); Looper.loop(); } }).start(); } private String getBTCDisplayAmount(long value) { String strAmount = null; DecimalFormat df = new DecimalFormat("#"); df.setMinimumIntegerDigits(1); df.setMinimumFractionDigits(1); df.setMaximumFractionDigits(8); int unit = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC); switch(unit) { case MonetaryUtil.MICRO_BTC: strAmount = df.format(((double)(value * 1000000L)) / 1e8); break; case MonetaryUtil.MILLI_BTC: strAmount = df.format(((double)(value * 1000L)) / 1e8); break; default: strAmount = Coin.valueOf(value).toPlainString(); break; } return strAmount; } private String getBTCDisplayUnits() { return (String) MonetaryUtil.getInstance().getBTCUnits()[PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.BTC_UNITS, MonetaryUtil.UNIT_BTC)]; } private String getFiatDisplayAmount(long value) { String strFiat = PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); double btc_fx = ExchangeRateFactory.getInstance(BalanceActivity.this).getAvgPrice(strFiat); String strAmount = MonetaryUtil.getInstance().getFiatFormat(strFiat).format(btc_fx * (((double)value) / 1e8)); return strAmount; } private String getFiatDisplayUnits() { return PrefsUtil.getInstance(BalanceActivity.this).getValue(PrefsUtil.CURRENT_FIAT, "USD"); } }
BalanceActivity: optimize multiaddr calls
app/src/main/java/com/samourai/sentinel/BalanceActivity.java
BalanceActivity: optimize multiaddr calls
<ide><path>pp/src/main/java/com/samourai/sentinel/BalanceActivity.java <ide> BalanceActivity.this.runOnUiThread(new Runnable() { <ide> @Override <ide> public void run() { <del> displayBalance(); <ide> refreshTx(false); <ide> } <ide> }); <ide> <ide> AppUtil.getInstance(BalanceActivity.this).checkTimeOut(); <ide> <del> displayBalance(); <del> refreshTx(false); <del> <ide> } <ide> <ide> @Override <ide> int idx = SamouraiSentinel.getInstance(BalanceActivity.this).getCurrentSelectedAccount(); <ide> <ide> List<String> _xpubs = SamouraiSentinel.getInstance(BalanceActivity.this).getAllAddrsSorted(); <del> APIFactory.getInstance(BalanceActivity.this).getXPUB(_xpubs.toArray(new String[_xpubs.size()])); <add> if(idx == 0) { <add> APIFactory.getInstance(BalanceActivity.this).getXPUB(_xpubs.toArray(new String[_xpubs.size()])); <add> } <add> else { <add> APIFactory.getInstance(BalanceActivity.this).getXPUB(new String[] { _xpubs.get(idx - 1) } ); <add> } <ide> <ide> if(idx == 0) { <ide> txs = APIFactory.getInstance(BalanceActivity.this).getAllXpubTxs();
Java
apache-2.0
1dc1373f5d580dd95dee1ad20467ba863a4be2b3
0
cherryhill/collectionspace-services,cherryhill/collectionspace-services
/** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * * http://www.collectionspace.org * http://wiki.collectionspace.org * * Copyright (c) 2009 Regents of the University of California * * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt * * 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.collectionspace.services.client.test; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.collectionspace.services.client.AcquisitionClient; import org.collectionspace.services.client.CollectionSpaceClient; import org.collectionspace.services.client.PayloadOutputPart; import org.collectionspace.services.client.PoxPayloadIn; import org.collectionspace.services.client.PoxPayloadOut; import org.collectionspace.services.jaxb.AbstractCommonList; import org.collectionspace.services.acquisition.AcquisitionsCommon; import org.collectionspace.services.acquisition.AcquisitionDateList; import org.collectionspace.services.acquisition.AcquisitionSourceList; import org.collectionspace.services.acquisition.OwnerList; import org.jboss.resteasy.client.ClientResponse; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.testng.Assert; import org.testng.annotations.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * AcquisitionServiceTest, carries out tests against a * deployed and running Acquisition Service. * * $LastChangedRevision: 621 $ * $LastChangedDate: 2009-09-02 16:49:01 -0700 (Wed, 02 Sep 2009) $ */ public class AcquisitionServiceTest extends AbstractServiceTestImpl { /** The logger. */ private final String CLASS_NAME = AcquisitionServiceTest.class.getName(); private final Logger logger = LoggerFactory.getLogger(CLASS_NAME); // Instance variables specific to this test. /** The known resource id. */ private String knownResourceId = null; @Override public String getServicePathComponent() { return AcquisitionClient.SERVICE_PATH_COMPONENT; } @Override protected String getServiceName() { return AcquisitionClient.SERVICE_NAME; } /* (non-Javadoc) * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance() */ @Override protected CollectionSpaceClient getClientInstance() { return new AcquisitionClient(); } /* (non-Javadoc) * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse) */ @Override protected AbstractCommonList getAbstractCommonList( ClientResponse<AbstractCommonList> response) { return response.getEntity(AbstractCommonList.class); } // --------------------------------------------------------------- // CRUD tests : CREATE tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.ServiceTest#create(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class) public void create(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup, such as initializing the type of service request // (e.g. CREATE, DELETE), its valid and expected status codes, and // its associated HTTP method name (e.g. POST, DELETE). setupCreate(); // Submit the request to the service and store the response. String identifier = createIdentifier(); AcquisitionClient client = new AcquisitionClient(); PoxPayloadOut multipart = createAcquisitionInstance(identifier); ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? // // Specifically: // Does it fall within the set of valid status codes? // Does it exactly match the expected status code? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Store the ID returned from the first resource created // for additional tests below. if (knownResourceId == null){ knownResourceId = extractId(res); if (logger.isDebugEnabled()) { logger.debug(testName + ": knownResourceId=" + knownResourceId); } } // Store the IDs from every resource created by tests, // so they can be deleted after tests have been run. allResourceIdsCreated.add(extractId(res)); } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createList(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"create"}) public void createList(String testName) throws Exception { for(int i = 0; i < 3; i++){ create(testName); } } /* * Tests to diagnose and fix CSPACE-2578. * * This is a bug identified in release 1.0 alpha, after first implementing an * Acquisition Funding repeatable group of fields, in which record creation * fails if there is whitespace (or more generally, a text node) between * the acquisitionFunding container element and its first child field. */ // Verify that record creation occurs successfully when there is NO whitespace // between the acquisitionFunding tag and its first child element tag @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}, groups = {"cspace2578group"}) public void createFromXmlNoWhitespaceAfterRepeatableGroupTag(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } String testDataDir = System.getProperty("test-data.fileName"); String newId = createFromXmlFile(testName, testDataDir + "/cspace-2578-no-whitespace.xml", false); testSubmitRequest(newId); } // Verify that record creation occurs successfully when there is whitespace // between the acquisitionFunding tag and its first child element tag // FIXME: This test currently fails. @Test annotation is currently commented // out for check-in, to prevent service tests from failing. Can uncomment to test // fixes, and also after the issue is resolved, to help detect any regressions. @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}, groups = {"cspace2578group"}) public void createFromXmlWhitespaceAfterRepeatableGroupTag(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } String testDataDir = System.getProperty("test-data.fileName"); String newId = createFromXmlFile(testName, testDataDir + "/cspace-2578-whitespace.xml", false); AcquisitionsCommon acquisition = readAcquisitionCommonPart(newId); testSubmitRequest(newId); } // Failure outcomes // Placeholders until the three tests below can be uncommented. // See Issue CSPACE-401. /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createWithEmptyEntityBody(java.lang.String) */ @Override public void createWithEmptyEntityBody(String testName) throws Exception { //Should this really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createWithMalformedXml(java.lang.String) */ @Override public void createWithMalformedXml(String testName) throws Exception { //Should this really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createWithWrongXmlSchema(java.lang.String) */ @Override public void createWithWrongXmlSchema(String testName) throws Exception { //Should this really be empty? } /* @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithMalformedXml(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupCreateWithMalformedXml(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); final String entity = MALFORMED_XML_DATA; // Constant from base class. int statusCode = submitRequest(method, url, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithWrongXmlSchema(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupCreateWithWrongXmlSchema(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); final String entity = WRONG_XML_SCHEMA_DATA; int statusCode = submitRequest(method, url, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } */ // --------------------------------------------------------------- // CRUD tests : READ tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#read(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"create"}) public void read(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupRead(); AcquisitionClient client = new AcquisitionClient(); // Submit the request to the service and store the response. ClientResponse<String> res = client.read(knownResourceId); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); AcquisitionsCommon acquisitionObject = (AcquisitionsCommon) extractPart(input, client.getCommonPartName(), AcquisitionsCommon.class); Assert.assertNotNull(acquisitionObject); // Verify the number and contents of values in repeatable fields, // as created in the instance record used for testing. List<String> acqSources = acquisitionObject.getAcquisitionSources().getAcquisitionSource(); Assert.assertTrue(acqSources.size() > 0); Assert.assertNotNull(acqSources.get(0)); List<String> acqDates = acquisitionObject.getAcquisitionDates().getAcquisitionDate(); Assert.assertTrue(acqDates.size() > 0); Assert.assertNotNull(acqDates.get(0)); List<String> owners = acquisitionObject.getOwners().getOwner(); Assert.assertTrue(owners.size() > 0); Assert.assertNotNull(owners.get(0)); } // Failure outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#readNonExistent(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void readNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupReadNonExistent(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<String> res = client.read(NON_EXISTENT_ID); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // --------------------------------------------------------------- // CRUD tests : READ_LIST tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#readList(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"createList", "read"}) public void readList(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupReadList(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<AbstractCommonList> res = client.readList(); AbstractCommonList list = res.getEntity(); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Optionally output additional data about list members for debugging. boolean iterateThroughList = true; if(iterateThroughList && logger.isDebugEnabled()){ List<AbstractCommonList.ListItem> items = list.getListItem(); int i = 0; for(AbstractCommonList.ListItem item : items){ List<Element> elList = item.getAny(); StringBuilder elementStrings = new StringBuilder(); for(Element el : elList) { Node textEl = el.getFirstChild(); elementStrings.append("["+el.getNodeName()+":"+((textEl!=null)?textEl.getNodeValue():"NULL")+"] "); } logger.debug(testName + ": list-item[" + i + "]: "+elementStrings.toString()); i++; } } } // Failure outcomes // None at present. // --------------------------------------------------------------- // CRUD tests : UPDATE tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#update(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void update(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupUpdate(); // Retrieve the contents of a resource to update. AcquisitionClient client = new AcquisitionClient(); ClientResponse<String> res = client.read(knownResourceId); if(logger.isDebugEnabled()){ logger.debug(testName + ": read status = " + res.getStatus()); } Assert.assertEquals(res.getStatus(), EXPECTED_STATUS_CODE); if(logger.isDebugEnabled()){ logger.debug("got object to update with ID: " + knownResourceId); } PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input, client.getCommonPartName(), AcquisitionsCommon.class); Assert.assertNotNull(acquisition); // Update the content of this resource. acquisition.setAcquisitionReferenceNumber("updated-" + acquisition.getAcquisitionReferenceNumber()); if(logger.isDebugEnabled()){ logger.debug("updated object"); logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class)); } // Submit the request to the service and store the response. PoxPayloadOut output = new PoxPayloadOut(AcquisitionClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = output.addPart(acquisition, MediaType.APPLICATION_XML_TYPE); commonPart.setLabel(client.getCommonPartName()); res = client.update(knownResourceId, output); int statusCode = res.getStatus(); // Check the status code of the response: does it match the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); input = new PoxPayloadIn(res.getEntity()); AcquisitionsCommon updatedAcquisition = (AcquisitionsCommon) extractPart(input, client.getCommonPartName(), AcquisitionsCommon.class); Assert.assertNotNull(updatedAcquisition); Assert.assertEquals(updatedAcquisition.getAcquisitionReferenceNumber(), acquisition.getAcquisitionReferenceNumber(), "Data in updated object did not match submitted data."); } // Failure outcomes // Placeholders until the three tests below can be uncommented. // See Issue CSPACE-401. /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithEmptyEntityBody(java.lang.String) */ @Override public void updateWithEmptyEntityBody(String testName) throws Exception { //Should this really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithMalformedXml(java.lang.String) */ @Override public void updateWithMalformedXml(String testName) throws Exception { //Should this really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithWrongXmlSchema(java.lang.String) */ @Override public void updateWithWrongXmlSchema(String testName) throws Exception { //Should this really be empty? } /* @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithEmptyEntityBody(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupUpdateWithEmptyEntityBody(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); String mediaType = MediaType.APPLICATION_XML; final String entity = ""; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ (testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithEmptyEntityBody(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupCreateWithEmptyEntityBody(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); String mediaType = MediaType.APPLICATION_XML; final String entity = ""; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithMalformedXml(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupUpdateWithMalformedXml(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); final String entity = MALFORMED_XML_DATA; int statusCode = submitRequest(method, url, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithWrongXmlSchema(String testName) { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupUpdateWithWrongXmlSchema(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); final String entity = WRONG_XML_SCHEMA_DATA; int statusCode = submitRequest(method, url, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } */ /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateNonExistent(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"update", "testSubmitRequest"}) public void updateNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupUpdateNonExistent(); // Submit the request to the service and store the response. // Note: The ID used in this 'create' call may be arbitrary. // The only relevant ID may be the one used in update(), below. AcquisitionClient client = new AcquisitionClient(); PoxPayloadOut multipart = createAcquisitionInstance(NON_EXISTENT_ID); ClientResponse<String> res = client.update(NON_EXISTENT_ID, multipart); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // --------------------------------------------------------------- // CRUD tests : DELETE tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#delete(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"create", "read", "update"}) public void delete(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupDelete(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<Response> res = client.delete(knownResourceId); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // Failure outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#deleteNonExistent(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"delete"}) public void deleteNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupDeleteNonExistent(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<Response> res = client.delete(NON_EXISTENT_ID); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // --------------------------------------------------------------- // Utility tests : tests of code used in tests above // --------------------------------------------------------------- /** * Tests the code for manually submitting data that is used by several * of the methods above. * @throws Exception */ @Test(dependsOnMethods = {"create", "read"}) public void testSubmitRequest() throws Exception { testSubmitRequest(knownResourceId); } /** * Test submit request. * * @param resourceId the resource id * @throws Exception the exception */ private void testSubmitRequest(String resourceId) throws Exception { // Expected status code: 200 OK final int EXPECTED_STATUS = Response.Status.OK.getStatusCode(); // Submit the request to the service and store the response. String method = ServiceRequestType.READ.httpMethodName(); String url = getResourceURL(resourceId); int statusCode = submitRequest(method, url); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug("testSubmitRequest: url=" + url + " status=" + statusCode); } Assert.assertEquals(statusCode, EXPECTED_STATUS); } // --------------------------------------------------------------- // Utility methods used by tests above // --------------------------------------------------------------- @Override protected PoxPayloadOut createInstance(String identifier) { return createAcquisitionInstance(identifier); } /** * Creates the acquisition instance. * * @param identifier the identifier * @return the multipart output */ private PoxPayloadOut createAcquisitionInstance(String identifier) { AcquisitionsCommon acquisition = new AcquisitionsCommon(); acquisition.setAcquisitionReferenceNumber("acquisitionReferenceNumber-" + identifier); AcquisitionSourceList acqSourcesList = new AcquisitionSourceList(); List<String> acqSources = acqSourcesList.getAcquisitionSource(); // FIXME Use properly formatted refNames for representative acquisition // sources in this example test record. The following are mere placeholders. acqSources.add("Donor Acquisition Source-" + identifier); acqSources.add("Museum Acquisition Source-" + identifier); acquisition.setAcquisitionSources(acqSourcesList); AcquisitionDateList acqDatesList = new AcquisitionDateList(); List<String> acqDates = acqDatesList.getAcquisitionDate(); // FIXME Use properly timestamps for representative acquisition // dates in this example test record. The following are mere placeholders. acqDates.add("First Acquisition Date -" + identifier); acqDates.add("Second Acquisition Date-" + identifier); acquisition.setAcquisitionDates(acqDatesList); OwnerList ownersList = new OwnerList(); List<String> owners = ownersList.getOwner(); // FIXME Use properly formatted refNames for representative owners // in this example test record. The following are mere placeholders. owners.add("First Owner -" + identifier); owners.add("Second Owner-" + identifier); acquisition.setOwners(ownersList); PoxPayloadOut multipart = new PoxPayloadOut(AcquisitionClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE); commonPart.setLabel(new AcquisitionClient().getCommonPartName()); if(logger.isDebugEnabled()){ logger.debug("to be created, acquisition common"); logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class)); } return multipart; } // FIXME: The following methods might be made generic and moved to a common package. /** * Retrives an XML document from the given file, and uses * the JAXB unmarshaller to create a Java object representation * and ultimately a multipart payload that can be submitted in * a create or update request. * * @param commonPartName * @param commonPartFileName * @return * @throws Exception */ private PoxPayloadOut createAcquisitionInstanceFromXml(String testName, String commonPartName, String commonPartFileName) throws Exception { AcquisitionsCommon acquisition = (AcquisitionsCommon) getObjectFromFile(AcquisitionsCommon.class, commonPartFileName); PoxPayloadOut multipart = new PoxPayloadOut(AcquisitionClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE); commonPart.setLabel(commonPartName); if (logger.isDebugEnabled()) { logger.debug(testName + " to be created, acquisitions common"); logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class)); } return multipart; } /** * Creates a record / resource from the data in an XML file. * * @param testName the test name * @param fileName the file name * @param useJaxb the use jaxb * @return the string * @throws Exception the exception */ private String createFromXmlFile(String testName, String fileName, boolean useJaxb) throws Exception { // Perform setup. setupCreate(); PoxPayloadOut multipart = null; AcquisitionClient client = new AcquisitionClient(); if (useJaxb) { multipart = createAcquisitionInstanceFromXml(testName, client.getCommonPartName(), fileName); } else { multipart = createAcquisitionInstanceFromRawXml(testName, client.getCommonPartName(), fileName); } ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); String newId = extractId(res); allResourceIdsCreated.add(newId); return newId; } /** * Returns a multipart payload that can be submitted with a * create or update request, by reading from an XML file. * * @param commonPartName * @param commonPartFileName * @return * @throws Exception */ private PoxPayloadOut createAcquisitionInstanceFromRawXml(String testName, String commonPartName, String commonPartFileName) throws Exception { PoxPayloadOut multipart = new PoxPayloadOut(AcquisitionClient.SERVICE_PAYLOAD_NAME); String stringObject = getXmlDocumentAsString(commonPartFileName); if (logger.isDebugEnabled()) { logger.debug(testName + " to be created, acquisition common " + "\n" + stringObject); } PayloadOutputPart commonPart = multipart.addPart(stringObject, stringObject); commonPart.setLabel(commonPartName); return multipart; } // FIXME: This duplicates code in read(), and should be consolidated. // This is an expedient to support reading and verifying the contents // of resources that have been created from test data XML files. private AcquisitionsCommon readAcquisitionCommonPart(String csid) throws Exception { String testName = "readAcquisitionCommonPart"; setupRead(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<String> res = client.read(csid); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); if (logger.isDebugEnabled()) { logger.debug(testName + ": Reading Common part ..."); } AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input, client.getCommonPartName(), AcquisitionsCommon.class); Assert.assertNotNull(acquisition); return acquisition; } }
services/acquisition/client/src/test/java/org/collectionspace/services/client/test/AcquisitionServiceTest.java
/** * This document is a part of the source code and related artifacts * for CollectionSpace, an open source collections management system * for museums and related institutions: * * http://www.collectionspace.org * http://wiki.collectionspace.org * * Copyright (c) 2009 Regents of the University of California * * Licensed under the Educational Community License (ECL), Version 2.0. * You may not use this file except in compliance with this License. * * You may obtain a copy of the ECL 2.0 License at * https://source.collectionspace.org/collection-space/LICENSE.txt * * 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.collectionspace.services.client.test; import java.util.List; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import org.collectionspace.services.client.AcquisitionClient; import org.collectionspace.services.client.CollectionSpaceClient; import org.collectionspace.services.client.PayloadOutputPart; import org.collectionspace.services.client.PoxPayloadIn; import org.collectionspace.services.client.PoxPayloadOut; import org.collectionspace.services.jaxb.AbstractCommonList; import org.collectionspace.services.acquisition.AcquisitionsCommon; import org.collectionspace.services.acquisition.AcquisitionDateList; import org.collectionspace.services.acquisition.AcquisitionSourceList; import org.collectionspace.services.acquisition.OwnerList; import org.jboss.resteasy.client.ClientResponse; import org.testng.Assert; import org.testng.annotations.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * AcquisitionServiceTest, carries out tests against a * deployed and running Acquisition Service. * * $LastChangedRevision: 621 $ * $LastChangedDate: 2009-09-02 16:49:01 -0700 (Wed, 02 Sep 2009) $ */ public class AcquisitionServiceTest extends AbstractServiceTestImpl { /** The logger. */ private final String CLASS_NAME = AcquisitionServiceTest.class.getName(); private final Logger logger = LoggerFactory.getLogger(CLASS_NAME); // Instance variables specific to this test. /** The known resource id. */ private String knownResourceId = null; @Override public String getServicePathComponent() { return AcquisitionClient.SERVICE_PATH_COMPONENT; } @Override protected String getServiceName() { return AcquisitionClient.SERVICE_NAME; } /* (non-Javadoc) * @see org.collectionspace.services.client.test.BaseServiceTest#getClientInstance() */ @Override protected CollectionSpaceClient getClientInstance() { return new AcquisitionClient(); } /* (non-Javadoc) * @see org.collectionspace.services.client.test.BaseServiceTest#getAbstractCommonList(org.jboss.resteasy.client.ClientResponse) */ @Override protected AbstractCommonList getAbstractCommonList( ClientResponse<AbstractCommonList> response) { return response.getEntity(AbstractCommonList.class); } // --------------------------------------------------------------- // CRUD tests : CREATE tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.ServiceTest#create(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class) public void create(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup, such as initializing the type of service request // (e.g. CREATE, DELETE), its valid and expected status codes, and // its associated HTTP method name (e.g. POST, DELETE). setupCreate(); // Submit the request to the service and store the response. String identifier = createIdentifier(); AcquisitionClient client = new AcquisitionClient(); PoxPayloadOut multipart = createAcquisitionInstance(identifier); ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? // // Specifically: // Does it fall within the set of valid status codes? // Does it exactly match the expected status code? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Store the ID returned from the first resource created // for additional tests below. if (knownResourceId == null){ knownResourceId = extractId(res); if (logger.isDebugEnabled()) { logger.debug(testName + ": knownResourceId=" + knownResourceId); } } // Store the IDs from every resource created by tests, // so they can be deleted after tests have been run. allResourceIdsCreated.add(extractId(res)); } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createList(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"create"}) public void createList(String testName) throws Exception { for(int i = 0; i < 3; i++){ create(testName); } } /* * Tests to diagnose and fix CSPACE-2578. * * This is a bug identified in release 1.0 alpha, after first implementing an * Acquisition Funding repeatable group of fields, in which record creation * fails if there is whitespace (or more generally, a text node) between * the acquisitionFunding container element and its first child field. */ // Verify that record creation occurs successfully when there is NO whitespace // between the acquisitionFunding tag and its first child element tag @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}, groups = {"cspace2578group"}) public void createFromXmlNoWhitespaceAfterRepeatableGroupTag(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } String testDataDir = System.getProperty("test-data.fileName"); String newId = createFromXmlFile(testName, testDataDir + "/cspace-2578-no-whitespace.xml", false); testSubmitRequest(newId); } // Verify that record creation occurs successfully when there is whitespace // between the acquisitionFunding tag and its first child element tag // FIXME: This test currently fails. @Test annotation is currently commented // out for check-in, to prevent service tests from failing. Can uncomment to test // fixes, and also after the issue is resolved, to help detect any regressions. @Test(dataProvider = "testName", dataProviderClass = AbstractServiceTestImpl.class, dependsOnMethods = {"create", "testSubmitRequest"}, groups = {"cspace2578group"}) public void createFromXmlWhitespaceAfterRepeatableGroupTag(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } String testDataDir = System.getProperty("test-data.fileName"); String newId = createFromXmlFile(testName, testDataDir + "/cspace-2578-whitespace.xml", false); AcquisitionsCommon acquisition = readAcquisitionCommonPart(newId); testSubmitRequest(newId); } // Failure outcomes // Placeholders until the three tests below can be uncommented. // See Issue CSPACE-401. /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createWithEmptyEntityBody(java.lang.String) */ @Override public void createWithEmptyEntityBody(String testName) throws Exception { //Should this really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createWithMalformedXml(java.lang.String) */ @Override public void createWithMalformedXml(String testName) throws Exception { //Should this really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#createWithWrongXmlSchema(java.lang.String) */ @Override public void createWithWrongXmlSchema(String testName) throws Exception { //Should this really be empty? } /* @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithMalformedXml(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupCreateWithMalformedXml(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); final String entity = MALFORMED_XML_DATA; // Constant from base class. int statusCode = submitRequest(method, url, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithWrongXmlSchema(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupCreateWithWrongXmlSchema(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); final String entity = WRONG_XML_SCHEMA_DATA; int statusCode = submitRequest(method, url, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } */ // --------------------------------------------------------------- // CRUD tests : READ tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#read(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"create"}) public void read(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupRead(); AcquisitionClient client = new AcquisitionClient(); // Submit the request to the service and store the response. ClientResponse<String> res = client.read(knownResourceId); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); AcquisitionsCommon acquisitionObject = (AcquisitionsCommon) extractPart(input, client.getCommonPartName(), AcquisitionsCommon.class); Assert.assertNotNull(acquisitionObject); // Verify the number and contents of values in repeatable fields, // as created in the instance record used for testing. List<String> acqSources = acquisitionObject.getAcquisitionSources().getAcquisitionSource(); Assert.assertTrue(acqSources.size() > 0); Assert.assertNotNull(acqSources.get(0)); List<String> acqDates = acquisitionObject.getAcquisitionDates().getAcquisitionDate(); Assert.assertTrue(acqDates.size() > 0); Assert.assertNotNull(acqDates.get(0)); List<String> owners = acquisitionObject.getOwners().getOwner(); Assert.assertTrue(owners.size() > 0); Assert.assertNotNull(owners.get(0)); } // Failure outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#readNonExistent(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void readNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupReadNonExistent(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<String> res = client.read(NON_EXISTENT_ID); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // --------------------------------------------------------------- // CRUD tests : READ_LIST tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#readList(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"createList", "read"}) public void readList(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupReadList(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<AbstractCommonList> res = client.readList(); AbstractCommonList list = res.getEntity(); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); // Optionally output additional data about list members for debugging. boolean iterateThroughList = false; if(iterateThroughList && logger.isDebugEnabled()){ List<AbstractCommonList.ListItem> items = list.getListItem(); int i = 0; for(AbstractCommonList.ListItem item : items){ logger.debug(testName + ": list-item[" + i + "] " + item.toString()); i++; } } } // Failure outcomes // None at present. // --------------------------------------------------------------- // CRUD tests : UPDATE tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#update(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"read"}) public void update(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupUpdate(); // Retrieve the contents of a resource to update. AcquisitionClient client = new AcquisitionClient(); ClientResponse<String> res = client.read(knownResourceId); if(logger.isDebugEnabled()){ logger.debug(testName + ": read status = " + res.getStatus()); } Assert.assertEquals(res.getStatus(), EXPECTED_STATUS_CODE); if(logger.isDebugEnabled()){ logger.debug("got object to update with ID: " + knownResourceId); } PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input, client.getCommonPartName(), AcquisitionsCommon.class); Assert.assertNotNull(acquisition); // Update the content of this resource. acquisition.setAcquisitionReferenceNumber("updated-" + acquisition.getAcquisitionReferenceNumber()); if(logger.isDebugEnabled()){ logger.debug("updated object"); logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class)); } // Submit the request to the service and store the response. PoxPayloadOut output = new PoxPayloadOut(AcquisitionClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = output.addPart(acquisition, MediaType.APPLICATION_XML_TYPE); commonPart.setLabel(client.getCommonPartName()); res = client.update(knownResourceId, output); int statusCode = res.getStatus(); // Check the status code of the response: does it match the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); input = new PoxPayloadIn(res.getEntity()); AcquisitionsCommon updatedAcquisition = (AcquisitionsCommon) extractPart(input, client.getCommonPartName(), AcquisitionsCommon.class); Assert.assertNotNull(updatedAcquisition); Assert.assertEquals(updatedAcquisition.getAcquisitionReferenceNumber(), acquisition.getAcquisitionReferenceNumber(), "Data in updated object did not match submitted data."); } // Failure outcomes // Placeholders until the three tests below can be uncommented. // See Issue CSPACE-401. /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithEmptyEntityBody(java.lang.String) */ @Override public void updateWithEmptyEntityBody(String testName) throws Exception { //Should this really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithMalformedXml(java.lang.String) */ @Override public void updateWithMalformedXml(String testName) throws Exception { //Should this really be empty? } /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateWithWrongXmlSchema(java.lang.String) */ @Override public void updateWithWrongXmlSchema(String testName) throws Exception { //Should this really be empty? } /* @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithEmptyEntityBody(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupUpdateWithEmptyEntityBody(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); String mediaType = MediaType.APPLICATION_XML; final String entity = ""; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ (testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "testSubmitRequest"}) public void createWithEmptyEntityBody(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupCreateWithEmptyEntityBody(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getServiceRootURL(); String mediaType = MediaType.APPLICATION_XML; final String entity = ""; int statusCode = submitRequest(method, url, mediaType, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTest.class, dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithMalformedXml(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupUpdateWithMalformedXml(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); final String entity = MALFORMED_XML_DATA; int statusCode = submitRequest(method, url, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } @Override @Test(dependsOnMethods = {"create", "update", "testSubmitRequest"}) public void updateWithWrongXmlSchema(String testName) { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); }; // Perform setup. setupUpdateWithWrongXmlSchema(); // Submit the request to the service and store the response. String method = REQUEST_TYPE.httpMethodName(); String url = getResourceURL(knownResourceId); final String entity = WRONG_XML_SCHEMA_DATA; int statusCode = submitRequest(method, url, entity); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": url=" + url + " status=" + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } */ /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#updateNonExistent(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"update", "testSubmitRequest"}) public void updateNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupUpdateNonExistent(); // Submit the request to the service and store the response. // Note: The ID used in this 'create' call may be arbitrary. // The only relevant ID may be the one used in update(), below. AcquisitionClient client = new AcquisitionClient(); PoxPayloadOut multipart = createAcquisitionInstance(NON_EXISTENT_ID); ClientResponse<String> res = client.update(NON_EXISTENT_ID, multipart); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // --------------------------------------------------------------- // CRUD tests : DELETE tests // --------------------------------------------------------------- // Success outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#delete(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"create", "read", "update"}) public void delete(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupDelete(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<Response> res = client.delete(knownResourceId); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // Failure outcomes /* (non-Javadoc) * @see org.collectionspace.services.client.test.AbstractServiceTestImpl#deleteNonExistent(java.lang.String) */ @Override @Test(dataProvider="testName", dataProviderClass=AbstractServiceTestImpl.class, dependsOnMethods = {"delete"}) public void deleteNonExistent(String testName) throws Exception { if (logger.isDebugEnabled()) { logger.debug(testBanner(testName, CLASS_NAME)); } // Perform setup. setupDeleteNonExistent(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<Response> res = client.delete(NON_EXISTENT_ID); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if(logger.isDebugEnabled()){ logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); } // --------------------------------------------------------------- // Utility tests : tests of code used in tests above // --------------------------------------------------------------- /** * Tests the code for manually submitting data that is used by several * of the methods above. * @throws Exception */ @Test(dependsOnMethods = {"create", "read"}) public void testSubmitRequest() throws Exception { testSubmitRequest(knownResourceId); } /** * Test submit request. * * @param resourceId the resource id * @throws Exception the exception */ private void testSubmitRequest(String resourceId) throws Exception { // Expected status code: 200 OK final int EXPECTED_STATUS = Response.Status.OK.getStatusCode(); // Submit the request to the service and store the response. String method = ServiceRequestType.READ.httpMethodName(); String url = getResourceURL(resourceId); int statusCode = submitRequest(method, url); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug("testSubmitRequest: url=" + url + " status=" + statusCode); } Assert.assertEquals(statusCode, EXPECTED_STATUS); } // --------------------------------------------------------------- // Utility methods used by tests above // --------------------------------------------------------------- @Override protected PoxPayloadOut createInstance(String identifier) { return createAcquisitionInstance(identifier); } /** * Creates the acquisition instance. * * @param identifier the identifier * @return the multipart output */ private PoxPayloadOut createAcquisitionInstance(String identifier) { AcquisitionsCommon acquisition = new AcquisitionsCommon(); acquisition.setAcquisitionReferenceNumber("acquisitionReferenceNumber-" + identifier); AcquisitionSourceList acqSourcesList = new AcquisitionSourceList(); List<String> acqSources = acqSourcesList.getAcquisitionSource(); // FIXME Use properly formatted refNames for representative acquisition // sources in this example test record. The following are mere placeholders. acqSources.add("Donor Acquisition Source-" + identifier); acqSources.add("Museum Acquisition Source-" + identifier); acquisition.setAcquisitionSources(acqSourcesList); AcquisitionDateList acqDatesList = new AcquisitionDateList(); List<String> acqDates = acqDatesList.getAcquisitionDate(); // FIXME Use properly timestamps for representative acquisition // dates in this example test record. The following are mere placeholders. acqDates.add("First Acquisition Date -" + identifier); acqDates.add("Second Acquisition Date-" + identifier); acquisition.setAcquisitionDates(acqDatesList); OwnerList ownersList = new OwnerList(); List<String> owners = ownersList.getOwner(); // FIXME Use properly formatted refNames for representative owners // in this example test record. The following are mere placeholders. owners.add("First Owner -" + identifier); owners.add("Second Owner-" + identifier); acquisition.setOwners(ownersList); PoxPayloadOut multipart = new PoxPayloadOut(AcquisitionClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE); commonPart.setLabel(new AcquisitionClient().getCommonPartName()); if(logger.isDebugEnabled()){ logger.debug("to be created, acquisition common"); logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class)); } return multipart; } // FIXME: The following methods might be made generic and moved to a common package. /** * Retrives an XML document from the given file, and uses * the JAXB unmarshaller to create a Java object representation * and ultimately a multipart payload that can be submitted in * a create or update request. * * @param commonPartName * @param commonPartFileName * @return * @throws Exception */ private PoxPayloadOut createAcquisitionInstanceFromXml(String testName, String commonPartName, String commonPartFileName) throws Exception { AcquisitionsCommon acquisition = (AcquisitionsCommon) getObjectFromFile(AcquisitionsCommon.class, commonPartFileName); PoxPayloadOut multipart = new PoxPayloadOut(AcquisitionClient.SERVICE_PAYLOAD_NAME); PayloadOutputPart commonPart = multipart.addPart(acquisition, MediaType.APPLICATION_XML_TYPE); commonPart.setLabel(commonPartName); if (logger.isDebugEnabled()) { logger.debug(testName + " to be created, acquisitions common"); logger.debug(objectAsXmlString(acquisition, AcquisitionsCommon.class)); } return multipart; } /** * Creates a record / resource from the data in an XML file. * * @param testName the test name * @param fileName the file name * @param useJaxb the use jaxb * @return the string * @throws Exception the exception */ private String createFromXmlFile(String testName, String fileName, boolean useJaxb) throws Exception { // Perform setup. setupCreate(); PoxPayloadOut multipart = null; AcquisitionClient client = new AcquisitionClient(); if (useJaxb) { multipart = createAcquisitionInstanceFromXml(testName, client.getCommonPartName(), fileName); } else { multipart = createAcquisitionInstanceFromRawXml(testName, client.getCommonPartName(), fileName); } ClientResponse<Response> res = client.create(multipart); int statusCode = res.getStatus(); if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); String newId = extractId(res); allResourceIdsCreated.add(newId); return newId; } /** * Returns a multipart payload that can be submitted with a * create or update request, by reading from an XML file. * * @param commonPartName * @param commonPartFileName * @return * @throws Exception */ private PoxPayloadOut createAcquisitionInstanceFromRawXml(String testName, String commonPartName, String commonPartFileName) throws Exception { PoxPayloadOut multipart = new PoxPayloadOut(AcquisitionClient.SERVICE_PAYLOAD_NAME); String stringObject = getXmlDocumentAsString(commonPartFileName); if (logger.isDebugEnabled()) { logger.debug(testName + " to be created, acquisition common " + "\n" + stringObject); } PayloadOutputPart commonPart = multipart.addPart(stringObject, stringObject); commonPart.setLabel(commonPartName); return multipart; } // FIXME: This duplicates code in read(), and should be consolidated. // This is an expedient to support reading and verifying the contents // of resources that have been created from test data XML files. private AcquisitionsCommon readAcquisitionCommonPart(String csid) throws Exception { String testName = "readAcquisitionCommonPart"; setupRead(); // Submit the request to the service and store the response. AcquisitionClient client = new AcquisitionClient(); ClientResponse<String> res = client.read(csid); int statusCode = res.getStatus(); // Check the status code of the response: does it match // the expected response(s)? if (logger.isDebugEnabled()) { logger.debug(testName + ": status = " + statusCode); } Assert.assertTrue(REQUEST_TYPE.isValidStatusCode(statusCode), invalidStatusCodeMessage(REQUEST_TYPE, statusCode)); Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); PoxPayloadIn input = new PoxPayloadIn(res.getEntity()); if (logger.isDebugEnabled()) { logger.debug(testName + ": Reading Common part ..."); } AcquisitionsCommon acquisition = (AcquisitionsCommon) extractPart(input, client.getCommonPartName(), AcquisitionsCommon.class); Assert.assertNotNull(acquisition); return acquisition; } }
NOJIRA - provide example of how to pull apart CommonList payloads in java client.
services/acquisition/client/src/test/java/org/collectionspace/services/client/test/AcquisitionServiceTest.java
NOJIRA - provide example of how to pull apart CommonList payloads in java client.
<ide><path>ervices/acquisition/client/src/test/java/org/collectionspace/services/client/test/AcquisitionServiceTest.java <ide> import org.collectionspace.services.acquisition.AcquisitionSourceList; <ide> import org.collectionspace.services.acquisition.OwnerList; <ide> import org.jboss.resteasy.client.ClientResponse; <add>import org.w3c.dom.Element; <add>import org.w3c.dom.Node; <ide> <ide> import org.testng.Assert; <ide> import org.testng.annotations.Test; <ide> Assert.assertEquals(statusCode, EXPECTED_STATUS_CODE); <ide> <ide> // Optionally output additional data about list members for debugging. <del> boolean iterateThroughList = false; <add> boolean iterateThroughList = true; <ide> if(iterateThroughList && logger.isDebugEnabled()){ <ide> List<AbstractCommonList.ListItem> items = <ide> list.getListItem(); <ide> int i = 0; <ide> for(AbstractCommonList.ListItem item : items){ <del> logger.debug(testName + ": list-item[" + i + "] " + <del> item.toString()); <add> List<Element> elList = item.getAny(); <add> StringBuilder elementStrings = new StringBuilder(); <add> for(Element el : elList) { <add> Node textEl = el.getFirstChild(); <add> elementStrings.append("["+el.getNodeName()+":"+((textEl!=null)?textEl.getNodeValue():"NULL")+"] "); <add> } <add> logger.debug(testName + ": list-item[" + i + "]: "+elementStrings.toString()); <ide> i++; <ide> } <ide> }
Java
mit
5306dccc58612fe136042930beec8043462ab7e2
0
blckshrk/MavenDataExtraction,blckshrk/MavenDataExtraction
package fr.lille1.maven_data_extraction; import java.io.File; public class Project { private final String groupId; private final String artifactId; private final String version; private final File pom; public Project(String groupId, String artifactId, String version, File pom){ this.groupId = groupId; this.artifactId = artifactId; this.version = version; this.pom = pom; } public String getGroupId() { return groupId; } public String getArtifactId() { return artifactId; } public String getVersion() { return version; } public File getPom() { return pom; } @Override public String toString() { return groupId + ":" + artifactId + ":" + version + ":" + pom.getPath(); } @Override public boolean equals(Object obj) { Project project = (Project) obj; if (project == null) { return false; } if (!project.getArtifactId().equals(artifactId)) { return false; } if (!project.getGroupId().equals(groupId)) { return false; } if (!project.getPom().equals(pom)) { return false; } if (!project.getVersion().equals(version)) { return false; } return true; } }
src/main/java/fr/lille1/maven_data_extraction/Project.java
package fr.lille1.maven_data_extraction; import java.io.File; public class Project { private String groupId; private String artifactId; private String version; private File pom; public Project(String groupId, String artifactId, String version, File pom){ this.groupId = groupId; this.artifactId = artifactId; this.version = version; this.pom = pom; } public String getGroupId() { return groupId; } public void setGroupId(String groupId) { this.groupId = groupId; } public String getArtifactId() { return artifactId; } public void setArtifactId(String artifactId) { this.artifactId = artifactId; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public File getPom() { return pom; } public void setPom(File pom) { this.pom = pom; } @Override public String toString() { return groupId + ":" + artifactId + ":" + version + ":" + pom; } }
Implementation of equals() method and suppressing of setters
src/main/java/fr/lille1/maven_data_extraction/Project.java
Implementation of equals() method and suppressing of setters
<ide><path>rc/main/java/fr/lille1/maven_data_extraction/Project.java <ide> import java.io.File; <ide> <ide> public class Project { <del> private String groupId; <del> private String artifactId; <del> private String version; <del> private File pom; <add> private final String groupId; <add> private final String artifactId; <add> private final String version; <add> private final File pom; <ide> <add> <ide> public Project(String groupId, String artifactId, String version, File pom){ <ide> this.groupId = groupId; <ide> this.artifactId = artifactId; <ide> return groupId; <ide> } <ide> <del> public void setGroupId(String groupId) { <del> this.groupId = groupId; <del> } <del> <ide> public String getArtifactId() { <ide> return artifactId; <ide> } <ide> <del> public void setArtifactId(String artifactId) { <del> this.artifactId = artifactId; <del> } <del> <ide> public String getVersion() { <ide> return version; <del> } <del> <del> public void setVersion(String version) { <del> this.version = version; <ide> } <ide> <ide> public File getPom() { <ide> return pom; <ide> } <ide> <del> public void setPom(File pom) { <del> this.pom = pom; <add> @Override <add> public String toString() { <add> return groupId + ":" + artifactId + ":" + version + ":" + pom.getPath(); <ide> } <ide> <ide> @Override <del> public String toString() { <del> return groupId + ":" + artifactId + ":" + version + ":" + pom; <add> public boolean equals(Object obj) { <add> Project project = (Project) obj; <add> <add> if (project == null) { <add> return false; <add> } <add> <add> if (!project.getArtifactId().equals(artifactId)) { <add> return false; <add> } <add> <add> if (!project.getGroupId().equals(groupId)) { <add> return false; <add> } <add> <add> if (!project.getPom().equals(pom)) { <add> return false; <add> } <add> <add> if (!project.getVersion().equals(version)) { <add> return false; <add> } <add> <add> return true; <ide> } <del> <del> <ide> }
JavaScript
agpl-3.0
af6a894a601c9e57534c8c7668a589312ab03d67
0
ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs,ONLYOFFICE/sdkjs
"use strict"; (function(window, undefined){ // Import var g_memory = AscFonts.g_memory; var CellValueType = AscCommon.CellValueType; var c_oAscBorderStyles = AscCommon.c_oAscBorderStyles; var fSortAscending = AscCommon.fSortAscending; var fSortDescending = AscCommon.fSortDescending; var parserHelp = AscCommon.parserHelp; var oNumFormatCache = AscCommon.oNumFormatCache; var gc_nMaxRow0 = AscCommon.gc_nMaxRow0; var gc_nMaxCol0 = AscCommon.gc_nMaxCol0; var g_oCellAddressUtils = AscCommon.g_oCellAddressUtils; var CellAddress = AscCommon.CellAddress; var isRealObject = AscCommon.isRealObject; var History = AscCommon.History; var UndoRedoItemSerializable = AscCommonExcel.UndoRedoItemSerializable; var UndoRedoData_CellSimpleData = AscCommonExcel.UndoRedoData_CellSimpleData; var UndoRedoData_CellValueData = AscCommonExcel.UndoRedoData_CellValueData; var UndoRedoData_FromToRowCol = AscCommonExcel.UndoRedoData_FromToRowCol; var UndoRedoData_FromTo = AscCommonExcel.UndoRedoData_FromTo; var UndoRedoData_IndexSimpleProp = AscCommonExcel.UndoRedoData_IndexSimpleProp; var UndoRedoData_BBox = AscCommonExcel.UndoRedoData_BBox; var UndoRedoData_SheetAdd = AscCommonExcel.UndoRedoData_SheetAdd; var UndoRedoData_SheetPositions = AscCommonExcel.UndoRedoData_SheetPositions; var UndoRedoData_DefinedNames = AscCommonExcel.UndoRedoData_DefinedNames; var UndoRedoData_DefinedNamesChange = AscCommonExcel.UndoRedoData_DefinedNamesChange; var g_oDefaultFormat = AscCommonExcel.g_oDefaultFormat; var Border = AscCommonExcel.Border; var RangeDataManagerElem = AscCommonExcel.RangeDataManagerElem; var RangeDataManager = AscCommonExcel.RangeDataManager; var cElementType = AscCommonExcel.cElementType; var cArea3D = AscCommonExcel.cArea3D; var cRef3D = AscCommonExcel.cRef3D; var parserFormula = AscCommonExcel.parserFormula; var c_oAscError = Asc.c_oAscError; var c_oAscInsertOptions = Asc.c_oAscInsertOptions; var c_oAscDeleteOptions = Asc.c_oAscDeleteOptions; var c_oAscGetDefinedNamesList = Asc.c_oAscGetDefinedNamesList; var c_oAscDefinedNameReason = Asc.c_oAscDefinedNameReason; var g_nVerticalTextAngle = 255; //определяется в WorksheetView.js var oDefaultMetrics = { ColWidthChars: 0, RowHeight: 0 }; var g_sNewSheetNamePattern = "Sheet"; var g_nSheetNameMaxLength = 31; var g_nAllColIndex = -1; var g_nAllRowIndex = -1; var aStandartNumFormats = []; var aStandartNumFormatsId = {}; var arrRecalc = {}, arrDefNameRecalc = {}; var oFormulaLocaleInfo = { Parse: true, DigitSep: true }; (function(){ aStandartNumFormats[0] = "General"; aStandartNumFormats[1] = "0"; aStandartNumFormats[2] = "0.00"; aStandartNumFormats[3] = "#,##0"; aStandartNumFormats[4] = "#,##0.00"; aStandartNumFormats[9] = "0%"; aStandartNumFormats[10] = "0.00%"; aStandartNumFormats[11] = "0.00E+00"; aStandartNumFormats[12] = "# ?/?"; aStandartNumFormats[13] = "# ??/??"; aStandartNumFormats[14] = "m/d/yyyy"; aStandartNumFormats[15] = "d-mmm-yy"; aStandartNumFormats[16] = "d-mmm"; aStandartNumFormats[17] = "mmm-yy"; aStandartNumFormats[18] = "h:mm AM/PM"; aStandartNumFormats[19] = "h:mm:ss AM/PM"; aStandartNumFormats[20] = "h:mm"; aStandartNumFormats[21] = "h:mm:ss"; aStandartNumFormats[22] = "m/d/yyyy h:mm"; aStandartNumFormats[37] = "#,##0_);(#,##0)"; aStandartNumFormats[38] = "#,##0_);[Red](#,##0)"; aStandartNumFormats[39] = "#,##0.00_);(#,##0.00)"; aStandartNumFormats[40] = "#,##0.00_);[Red](#,##0.00)"; aStandartNumFormats[45] = "mm:ss"; aStandartNumFormats[46] = "[h]:mm:ss"; aStandartNumFormats[47] = "mm:ss.0"; aStandartNumFormats[48] = "##0.0E+0"; aStandartNumFormats[49] = "@"; for(var i in aStandartNumFormats) { aStandartNumFormatsId[aStandartNumFormats[i]] = i - 0; } })(); var c_oRangeType = { Range:0, Col:1, Row:2, All:3 }; function getRangeType(oBBox){ if(null == oBBox) oBBox = this.bbox; if(oBBox.c1 == 0 && gc_nMaxCol0 == oBBox.c2 && oBBox.r1 == 0 && gc_nMaxRow0 == oBBox.r2) return c_oRangeType.All; if(oBBox.c1 == 0 && gc_nMaxCol0 == oBBox.c2) return c_oRangeType.Row; else if(oBBox.r1 == 0 && gc_nMaxRow0 == oBBox.r2) return c_oRangeType.Col; else return c_oRangeType.Range; } /** @constructor */ function DependencyGraph( wb ) { this.wb = wb; this.nodesId = null; this.nodesCell = null; this.nodesArea = null; this.defNameList = {}; this.defNameSheets = {}; this.nodeslength = null; this.bSetRefError = false; this.oChangeNodeSlave = null; this.sTableNamePattern = "Table"; this.nTableNameMaxIndex = 0; this.clear(); } DependencyGraph.prototype = { clear:function () { this.nodesId = {}; this.nodesCell = {}; this.nodesArea = {}; this.nodeslength = 0; this.bSetRefError = false; }, nodeExist:function ( node ) { return this.nodeExist2( node.sheetId, node.cellId ); }, nodeExist2:function ( sheetId, cellId ) { return null != this.getNode( sheetId, cellId ); }, nodeExistWithArea:function ( sheetId, cellId ) { var bRes = this.nodeExist2( sheetId, cellId ); if ( !bRes ) { var nodesSheetArea = this.nodesArea[sheetId]; if ( null != nodesSheetArea ) { var bbox = AscCommonExcel.g_oRangeCache.getAscRange( cellId ); bRes = nodesSheetArea.get( bbox ).all.length > 0; } } return bRes; }, getNode3:function ( nodeId ) { return this.nodesId[nodeId]; }, getNode2:function ( node ) { return this.nodesId[node.nodeId]; }, getNode:function ( sheetId, cellId ) { return this.nodesId[getVertexId( sheetId, cellId )]; }, addNode2:function ( node ) { return this.addNode( node.sheetId, node.cellId ); }, addNode:function ( sheetId, cellId ) { var _this = this; var nodeId = getVertexId( sheetId, cellId ); var oRes = this.nodesId[nodeId]; if ( null == oRes ) { var node = new Vertex( sheetId, cellId, this.wb ); var oBBoxNode = node.getBBox(); if ( node.isArea ) { var nodesSheetArea = this.nodesArea[node.sheetId]; if ( null == nodesSheetArea ) { nodesSheetArea = new RangeDataManager(function(data, from, to){_this._changeNode(data, from, to);}); this.nodesArea[node.sheetId] = nodesSheetArea; } nodesSheetArea.add( oBBoxNode, node ); } else { var nodesSheetCell = this.nodesCell[node.sheetId]; if ( null == nodesSheetCell ) { nodesSheetCell = new AscCommonExcel.CellArea(function(data, from, to){_this._changeNode(data, from, to);}); this.nodesCell[node.sheetId] = nodesSheetCell; } nodesSheetCell.add( oBBoxNode.r1, oBBoxNode.c1, node ); } oRes = node; } return oRes; }, addEdge2:function ( nodeFrom, nodeTo ) { nodeFrom.addMasterEdge( nodeTo ); nodeTo.addSlaveEdge( nodeFrom ); }, addEdge:function ( sheetIdFrom, cellIdFrom, sheetIdTo, cellIdTo ) { var n1 = this.addNode( sheetIdFrom, cellIdFrom ), n2 = this.addNode( sheetIdTo, cellIdTo ); this.addEdge2( n1, n2 ); }, getNodeBySheetId:function ( sheetId ) { var arr = []; var nodesSheetCell = this.nodesCell[sheetId]; if ( nodesSheetCell ) { var aNodes = nodesSheetCell.getAll(); for ( var i = 0, length = aNodes.length; i < length; i++ ) { var node = aNodes[i].data; var n = node.getSlaveEdges(); if ( n ) { arr.push( node ); } } } var nodesSheetArea = this.nodesArea[sheetId]; if ( nodesSheetArea ) { var aNodes = nodesSheetArea.getAll(); for ( var i = 0, length = aNodes.length; i < length; i++ ) { var node = aNodes[i].data; var n = node.getSlaveEdges(); if ( n ) { arr.push( node ); } } } return arr; }, getNodeBySheetIdAll:function ( sheetId ) { var arr = []; var nodesSheetCell = this.nodesCell[sheetId]; if ( nodesSheetCell ) { var aNodes = nodesSheetCell.getAll(); for ( var i = 0, length = aNodes.length; i < length; i++ ) { arr.push( aNodes[i].data ); } } var nodesSheetArea = this.nodesArea[sheetId]; if ( nodesSheetArea ) { var aNodes = nodesSheetArea.getAll(); for ( var i = 0, length = aNodes.length; i < length; i++ ) { arr.push( aNodes[i].data ); } } return arr; }, deleteNode:function ( node ) { if(node.isDefinedName) return; if ( node.isArea ) { var nodesSheetArea = this.nodesArea[node.sheetId]; if ( nodesSheetArea ) nodesSheetArea.removeElement( new RangeDataManagerElem( node.getBBox(), node ) ); } else { var nodesSheetCell = this.nodesCell[node.sheetId]; if ( nodesSheetCell ) nodesSheetCell.removeElement( new RangeDataManagerElem( node.getBBox(), node ) ); } }, deleteNodes : function(sheetId, bbox){ var bSetRefErrorOld = this.bSetRefError; this.bSetRefError = true; this.oChangeNodeSlave = { toDelete: {}, toMove: {} }; var nodesSheetArea = this.nodesArea[sheetId]; var oGetRes; if(nodesSheetArea) { oGetRes = nodesSheetArea.get(bbox); for(var i = 0, length = oGetRes.inner.length; i < length; ++i) nodesSheetArea.removeElement(oGetRes.inner[i]); } var nodesSheetCell = this.nodesCell[sheetId]; if(nodesSheetCell) { oGetRes = nodesSheetCell.get(bbox); for(var i = 0, length = oGetRes.length; i < length; ++i) nodesSheetCell.removeElement(oGetRes[i]); } this.changeNodeEnd(); this.bSetRefError = bSetRefErrorOld; }, deleteMasterNodes:function ( sheetId, cellId ) { var node = this.getNode( sheetId, cellId ); if ( node ) { var arr = node.deleteAllMasterEdges(); for ( var i in arr ) { var nodeMaster = arr[i]; if ( nodeMaster.refCount <= 0 ) this.deleteNode( nodeMaster ); } } return node; }, deleteMasterNodes2 : function(sheetId, cellId){ var node = this.deleteMasterNodes(sheetId, cellId); if(node && node.refCount <= 0) this.deleteNode(node); return node; }, deleteMasterNodes3:function ( node ) { var arr = node.deleteAllMasterEdges(); for (var i in arr) { var nodeMaster = arr[i]; if (nodeMaster.refCount <= 0) this.deleteNode(nodeMaster); } }, getSlaveNodes:function ( sheetId, cellId ) { //todo return null; }, getMasterNodes:function ( sheetId, cellId ) { //todo return null; }, getNodesLength:function () { return this.nodeslength; }, checkOffset:function ( BBox, offset, wsId, noDelete ) { var _this = this, bHor = 0 != offset.offsetCol, toDelete = offset.offsetCol < 0 || offset.offsetRow < 0, bSetRefErrorOld = this.bSetRefError; this.bSetRefError = true; var oShiftGetBBox = AscCommonExcel.shiftGetBBox(BBox, bHor); var sShiftGetBBoxName = oShiftGetBBox.getName(); this.wb.needRecalc.nodes[getVertexId(wsId, sShiftGetBBoxName)] = [wsId, sShiftGetBBoxName]; this.wb.needRecalc.length++; this.oChangeNodeSlave = { toDelete: {}, toMove: {}}; var nodesSheetArea = this.nodesArea[wsId]; if(nodesSheetArea) nodesSheetArea.shift(BBox, !toDelete, bHor); var nodesSheetCell = this.nodesCell[wsId]; if(nodesSheetCell) nodesSheetCell.shift( BBox, !toDelete, bHor ); this.changeNodeEnd(); this.bSetRefError = bSetRefErrorOld; }, changeNodeProcessDelete: function (node, oFormulas, toDelete) { //todo deleteAllSlaveEdges deleteMasterNodes var oSlaves = node.deleteAllSlaveEdges(), slave, formula; if (this.bSetRefError) { //выставляем #REF! for (var i in oSlaves) { slave = oSlaves[i]; if( slave instanceof DefNameVertex ){ if(!slave.isTable) this.wb.delDefinesNames(slave.getAscCDefName()); continue; } if (null == toDelete || slave != toDelete[slave.nodeId]) { formula = slave.setRefError(node); if (null != formula) { if (oFormulas) oFormulas[slave.nodeId] = { node: slave, formula: formula }; else slave.setFormula(formula, true, false); } } } } this.deleteMasterNodes3(node); }, changeNodeProcessMove: function (node, from, to, oFormulas, toDelete) { if (null == toDelete || node != toDelete[node.nodeId]) node.moveOuter(from, to, oFormulas); }, changeNodeEnd : function(){ var oChangeNodeSlave = this.oChangeNodeSlave; //обнуляем, потому что в цикле можем опять попасть в _changeNode со старым this.oChangeNodeSlave this.oChangeNodeSlave = null; //накапливаем формулы, потому что когда мы меняем формулу мы удаляем masterNodes, а эти node могут быть необработаными и влиять на формулу(C2=A2+B2 -> C1=A1+B2) var oFormulas = {}; for (var i in oChangeNodeSlave.toDelete) { var elem = oChangeNodeSlave.toDelete[i]; this.changeNodeProcessDelete(elem.node, oFormulas, oChangeNodeSlave.toDelete); } for (var i in oChangeNodeSlave.toMove) { var elem = oChangeNodeSlave.toMove[i]; this.changeNodeProcessMove(elem.node, elem.from, elem.to, oFormulas, oChangeNodeSlave.toDelete); } for (var i in oFormulas) { var elem = oFormulas[i]; if (null == elem.formula) { var node = elem.node; var cell = node.returnCell(); if (cell && cell.formulaParsed) { this.wb.dependencyFormulas.deleteMasterNodes2(node.sheetId, node.cellId); addToArrRecalc(node.sheetId, cell); } } else elem.node.setFormula(elem.formula, true, false); } }, _changeNode : function(node, from, to){ var toDelete = null == to; var toAdd = null == from; var wsId = node.sheetId; var sOldCellId = node.cellId; if(toAdd) { this.nodesId[node.nodeId] = node; this.nodeslength++; } else if(toDelete) { if (this.oChangeNodeSlave) this.oChangeNodeSlave.toDelete[node.nodeId] = { node: node, from: from, to: to }; else { this.changeNodeProcessDelete(node, null); } delete this.nodesId[node.nodeId]; this.nodeslength--; } else { var sOldnodeId = node.nodeId; node.moveInner(to); if (this.oChangeNodeSlave) this.oChangeNodeSlave.toMove[node.nodeId] = { node: node, from: from, to: to }; else this.changeNodeProcessMove(node, from, to, null); delete this.nodesId[sOldnodeId]; this.nodesId[node.nodeId] = node; } //важно что ячейки уже сдвинулись, поэтому до вызова returnCell нужно сделать node.move и сдвинуть ячейки в aGCells if(!node.isArea) { var cwf = this.wb.cwf[wsId]; if(cwf) { if(!toAdd) delete cwf.cells[sOldCellId]; if(!toDelete) { var cell = node.returnCell(); if ( cell && cell.formulaParsed ) cwf.cells[node.cellId] = node.cellId; } } } }, getCellInRange : function(sheetId, bbox){ var res = [], oGetRes, nodesSheetCell = this.nodesCell[sheetId]; if ( nodesSheetCell ) { oGetRes = nodesSheetCell.get(bbox); for ( var i = 0, length = oGetRes.length; i < length; i++ ) { res.push(oGetRes[i].data); } } return res; }, getAreaInRange : function(sheetId, bbox){ var res = [], oGetRes, nodesSheetArea = this.nodesArea[sheetId]; if(nodesSheetArea) { oGetRes = nodesSheetArea.get(bbox); for(var i = 0, length = oGetRes.all.length; i < length; i++) { res.push(oGetRes.all[i].data); } } return res; }, getInRange : function(sheetId, bbox){ return this.getCellInRange(sheetId, bbox).concat(this.getAreaInRange(sheetId, bbox)); }, helper : function(BBoxFrom, oBBoxTo, wsId){ var oGetRes, node, nodesSheetCell = this.nodesCell[wsId], nodesSheetArea = this.nodesArea[wsId]; var offset = { offsetCol: oBBoxTo.c1 - BBoxFrom.c1, offsetRow: oBBoxTo.r1 - BBoxFrom.r1 }; this.oChangeNodeSlave = { toDelete: {}, toMove: {} }; var elem, bbox; if(nodesSheetCell) oGetRes = nodesSheetCell.move(BBoxFrom, oBBoxTo); if(nodesSheetArea) oGetRes = nodesSheetArea.move(BBoxFrom, oBBoxTo); this.changeNodeEnd(); }, drawDep:function ( cellId, se ) { // ToDo неиспользуемая функция, реализовать после выпуска if ( !cellId ) return; var _wsV = this.wb.oApi.wb.getWorksheet(), _cc = _wsV.cellCommentator, ctx = _wsV.overlayCtx, _wsVM = _wsV.model, nodeId = getVertexId( _wsVM.getId(), cellId ), node = this.getNode( _wsVM.getId(), cellId ), cell; function gCM( _this, col, row ) { var metrics = { top:0, left:0, width:0, height:0, result:false }; // px var fvr = _this.getFirstVisibleRow(); var fvc = _this.getFirstVisibleCol(); var mergedRange = _wsVM.getMergedByCell( row, col ); if ( mergedRange && (fvc < mergedRange.c2) && (fvr < mergedRange.r2) ) { var startCol = (mergedRange.c1 > fvc) ? mergedRange.c1 : fvc; var startRow = (mergedRange.r1 > fvr) ? mergedRange.r1 : fvr; metrics.top = _this.getCellTop( startRow, 0 ) - _this.getCellTop( fvr, 0 ) + _this.getCellTop( 0, 0 ); metrics.left = _this.getCellLeft( startCol, 0 ) - _this.getCellLeft( fvc, 0 ) + _this.getCellLeft( 0, 0 ); for ( var i = startCol; i <= mergedRange.c2; i++ ) { metrics.width += _this.getColumnWidth( i, 0 ) } for ( var i = startRow; i <= mergedRange.r2; i++ ) { metrics.height += _this.getRowHeight( i, 0 ) } metrics.result = true; } else { metrics.top = _this.getCellTop( row, 0 ) - _this.getCellTop( fvr, 0 ) + _this.getCellTop( 0, 0 ); metrics.left = _this.getCellLeft( col, 0 ) - _this.getCellLeft( fvc, 0 ) + _this.getCellLeft( 0, 0 ); metrics.width = _this.getColumnWidth( col, 0 ); metrics.height = _this.getRowHeight( row, 0 ); metrics.result = true; } return metrics; } if ( !node ) return; cell = node.returnCell(); if ( !cell ) return; var m = [cell.nRow, cell.nCol], rc = [], me = se ? node.getSlaveEdges() : node.getMasterEdges(); for ( var id in me ) { if ( me[id].sheetId != node.sheetId ) return; if ( !me[id].isArea ) { var _t1 = gCM( _wsV, me[id].returnCell().nCol, me[id].returnCell().nRow ) rc.push( { t:_t1.top, l:_t1.left, w:_t1.width, h:_t1.height, apt:_t1.top + _t1.height / 2, apl:_t1.left + _t1.width / 4} ); } else { var _t1 = gCM( _wsV, me[id].getBBox().c1, me[id].getBBox().r1 ), _t2 = gCM( _wsV, me[id].getBBox().c2, me[id].getBBox().r2 ); rc.push( { t:_t1.top, l:_t1.left, w:_t2.left + _t2.width - _t1.left, h:_t2.top + _t2.height - _t1.top, apt:_t1.top + _t1.height / 2, apl:_t1.left + _t1.width / 4 } ); } } if ( rc.length == 0 ) return; var color = new AscCommon.CColor( 0, 0, 255 ); function draw_arrow( context, fromx, fromy, tox, toy ) { var headlen = 9; var dx = tox - fromx; var dy = toy - fromy; var angle = Math.atan2( dy, dx ), _a = Math.PI / 18; // ToDo посмотреть на четкость moveTo, lineTo context.save() .setLineWidth( 1 ) .beginPath() .moveTo( _cc.pxToPt( fromx ), _cc.pxToPt( fromy ) ) .lineTo( _cc.pxToPt( tox ), _cc.pxToPt( toy ) ); // .dashLine(_cc.pxToPt(fromx-.5), _cc.pxToPt(fromy-.5), _cc.pxToPt(tox-.5), _cc.pxToPt(toy-.5), 15, 5) context .moveTo( _cc.pxToPt( tox - headlen * Math.cos( angle - _a ) ), _cc.pxToPt( toy - headlen * Math.sin( angle - _a ) ) ) .lineTo( _cc.pxToPt( tox ), _cc.pxToPt( toy ) ) .lineTo( _cc.pxToPt( tox - headlen * Math.cos( angle + _a ) ), _cc.pxToPt( toy - headlen * Math.sin( angle + _a ) ) ) .lineTo( _cc.pxToPt( tox - headlen * Math.cos( angle - _a ) ), _cc.pxToPt( toy - headlen * Math.sin( angle - _a ) ) ) .setStrokeStyle( color ) .setFillStyle( color ) .stroke() .fill() .closePath() .restore(); } function h( m, rc ) { var m = gCM( _wsV, m[1], m[0] ); var arrowPointTop = 10, arrowPointLeft = 10; for ( var i = 0; i < rc.length; i++ ) { var m2 = rc[i], x1 = Math.floor( m2.apl ), y1 = Math.floor( m2.apt ), x2 = Math.floor( m.left + m.width / 4 ), y2 = Math.floor( m.top + m.height / 2 ); if ( x1 < 0 && x2 < 0 || y1 < 0 && y2 < 0 ) continue; // ToDo посмотреть на четкость rect if ( m2.apl > 0 && m2.apt > 0 ) ctx.save() .setLineWidth( 1 ) .setStrokeStyle( color ) .rect( _cc.pxToPt( m2.l ), _cc.pxToPt( m2.t ), _cc.pxToPt( m2.w - 1 ), _cc.pxToPt( m2.h - 1 ) ) .stroke() .restore(); if ( y1 < 0 && x1 != x2 ) x1 = x1 - Math.floor( Math.sqrt( ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) * y1 * y1 / ((y2 - y1) * (y2 - y1)) ) / 2 ) if ( x1 < 0 && y1 != y2 ) y1 = y1 - Math.floor( Math.sqrt( ((y1 - y2) * (y1 - y2) + (x1 - x2) * (x1 - x2)) * x1 * x1 / ((x2 - x1) * (x2 - x1)) ) / 2 ) draw_arrow( ctx, x1 < 0 ? _wsV.getCellLeft( 0, 0 ) : x1, y1 < 0 ? _wsV.getCellTop( 0, 0 ) : y1, x2, y2 ); if ( m2.apl > 0 && m2.apt > 0 ) ctx.save() .beginPath() .arc( _cc.pxToPt( Math.floor( m2.apl ) ), _cc.pxToPt( Math.floor( m2.apt ) ), 3, 0, 2 * Math.PI, false, -0.5, -0.5 ) .setFillStyle( color ) .fill() .closePath() .restore(); } } ctx.clear(); _wsV._drawSelection(); if ( se ) { for ( var i = 0; i < rc.length; i++ ) h( rc[i], [m] ); } else h( m, rc ); }, removeNodeBySheetId: function (sheetId) { this.oChangeNodeSlave = { toDelete: {}, toMove: {} }; var nodesSheetArea = this.nodesArea[sheetId]; if(nodesSheetArea) nodesSheetArea.removeAll(); var nodesSheetCell = this.nodesCell[sheetId]; if(nodesSheetCell) nodesSheetCell.removeAll(); this.changeNodeEnd(); }, getNodeDependence:function ( aElems, aDefinedNames ) { var oRes = { oMasterNodes: {}, oMasterAreaNodes: {}, oMasterAreaNodesRestricted: {}, oWeightMap: {}, oNodeToArea: {}, nCounter: 0 }, aWeightMapMasters = [], aWeightMapMastersNodes = [], node, elem, oSheetRanges = {}, oSheetWithArea = {};//все sheet на которых есть area для пересчета while ( null != aElems || null != aDefinedNames ) { if(null != aElems){ for ( var i in aElems ) { elem = aElems[i]; var sheetId = elem[0]; var cellId = elem[1]; //нужно обавлять в oSheetRanges даже несушествующие node, чтобы поддержать именении ячеек в SUM(A1:B2) this._getNodeDependenceNodeToRange(sheetId, AscCommonExcel.g_oRangeCache.getAscRange(cellId), oSheetRanges); node = this.getNode(sheetId, cellId); if ( node && null == oRes.oWeightMap[node.nodeId] ) { //все node из aElems записываем в master var oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 0, gray: false, bad: false, master: true, area: node.isArea }; if (node.isArea) oSheetWithArea[node.sheetId] = 1; aWeightMapMasters.push( oWeightMapElem ); aWeightMapMastersNodes.push( node ); oRes.oWeightMap[node.nodeId] = oWeightMapElem; this._getNodeDependence( oRes, oSheetRanges, node ); } } } if(null != aDefinedNames){ for(var i = 0; i < aDefinedNames.length; ++i){ var node = aDefinedNames[i]; if ( node && null == oRes.oWeightMap[node.nodeId] ) { //все node из aDefinedNames записываем в master var oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 0, gray: false, bad: false, master: true, area: false }; aWeightMapMasters.push( oWeightMapElem ); aWeightMapMastersNodes.push( node ); oRes.oWeightMap[node.nodeId] = oWeightMapElem; this._getNodeDependence( oRes, oSheetRanges, node ); } } } aElems = null; aDefinedNames = null; //расширяем за счет area nodes for ( var i in oSheetRanges ) { var oSheetRange = oSheetRanges[i]; if ( oSheetRange.changed ) { oSheetRange.changed = false; var nodesSheetArea = this.nodesArea[i]; if ( null != nodesSheetArea ) { var aAllOuter = null; if ( null == oSheetRange.prevRange ) { var oGetRes = nodesSheetArea.get( oSheetRange.range ); if ( oGetRes.all.length > 0 ) aAllOuter = oGetRes.all; } else { var aEdgeBBox = []; var bLeft = oSheetRange.range.c1 < oSheetRange.prevRange.c1; var bRight = oSheetRange.range.c2 > oSheetRange.prevRange.c2; var bTop = oSheetRange.range.r1 < oSheetRange.prevRange.r1; var bBottom = oSheetRange.range.r2 > oSheetRange.prevRange.r2; if (bLeft) aEdgeBBox.push(new Asc.Range(oSheetRange.range.c1, oSheetRange.range.r1, oSheetRange.prevRange.c1 - 1, oSheetRange.range.r2)); if (bRight) aEdgeBBox.push(new Asc.Range(oSheetRange.prevRange.c2 + 1, oSheetRange.range.r1, oSheetRange.range.c2, oSheetRange.range.r2)); if (bTop || bBottom){ var nNewC1, nNewC2; if(bLeft) nNewC1 = oSheetRange.range.c1 + 1; else nNewC1 = oSheetRange.range.c1; if(bRight) nNewC2 = oSheetRange.range.c2 - 1; else nNewC2 = oSheetRange.range.c2; if(bTop) aEdgeBBox.push(new Asc.Range(nNewC1, oSheetRange.range.r1, nNewC2, oSheetRange.prevRange.r1 - 1)); if(bBottom) aEdgeBBox.push(new Asc.Range(nNewC1, oSheetRange.prevRange.r2 + 1, nNewC2, oSheetRange.range.r2)); } aAllOuter = []; for ( var j = 0, length = aEdgeBBox.length; j < length; j++ ) { var bbox = aEdgeBBox[j]; var oGetRes = nodesSheetArea.get( bbox ); if ( oGetRes.all.length > 0 ) aAllOuter = aAllOuter.concat( oGetRes.all ); } } if ( aAllOuter && aAllOuter.length > 0 ) { if ( null == aElems ) aElems = []; for ( var j in aAllOuter ) { var node = aAllOuter[j].data; aElems[node.nodeId] = [node.sheetId, node.cellId]; } } } } } } var bMasterAreaNodesExist = false; var oAllMasterAreaNodes = {}; for ( var i = 0, length = aWeightMapMasters.length; i < length; i++ ) { var oWeightMapElem = aWeightMapMasters[i]; //возвращаем только настощие master if ( oWeightMapElem.master ) { node = aWeightMapMastersNodes[i]; if (oWeightMapElem.area) { bMasterAreaNodesExist = true; oAllMasterAreaNodes[node.nodeId] = node; } else oRes.oMasterNodes[node.nodeId] = node; } } if (bMasterAreaNodesExist) { //заносим все одинарные ячейки для пересчета в CellArea, чтобы определить какие из них лежат внутри area var oCellsForCalculation = {}; for (var i in oRes.oWeightMap) { var elem = oRes.oWeightMap[i]; if (!elem.area && !elem.isDefinedName) { var node = this.wb.dependencyFormulas.nodesId[i]; //если ячейка из oMasterNodes, даже если в ней формула, то она не может иметь master из oWeightMap(иначе она бы перестала быть master) - такие ячейки не добавляем //остальные ячейки имеют master из oWeightMap их надо проверять if (node && oSheetWithArea[node.sheetId] && !oRes.oMasterNodes[node.nodeId]) { var oCellsForCalculationSheet = oCellsForCalculation[node.sheetId]; if (null == oCellsForCalculationSheet) { oCellsForCalculationSheet = new AscCommonExcel.CellArea(null); oCellsForCalculation[node.sheetId] = oCellsForCalculationSheet; } var bbox = node.getBBox(); oCellsForCalculationSheet.add(bbox.r1, bbox.c1, node); } } } //делим oAllMasterAreaNodes на те что можно посчитать сразу и те что имеют внутри себя непосчитанные ячейки. //заполняем oNodeToArea ячейками и ссылками на AreaNode в которых ини лежат for (var i in oAllMasterAreaNodes) { var nodeMaster = oAllMasterAreaNodes[i]; //элемент запоминает сколько node надо посечить прежде чем считать nodeMaster var nodeMasterElement = { node: nodeMaster, cur: 0, max: 0 }; var bRestricted = false; var oCellsForCalculationSheet = oCellsForCalculation[nodeMaster.sheetId]; if (oCellsForCalculationSheet) { var oGetRes = oCellsForCalculationSheet.get(nodeMaster.getBBox()); if (oGetRes.length > 0) { bRestricted = true; for (var j = 0; j < oGetRes.length; ++j) { var node = oGetRes[j].data; var oNodeToAreaElement = oRes.oNodeToArea[node.nodeId]; if (null == oNodeToAreaElement) { oNodeToAreaElement = []; oRes.oNodeToArea[node.nodeId] = oNodeToAreaElement; } nodeMasterElement.max++; oNodeToAreaElement.push(nodeMasterElement); } } } if (bRestricted) oRes.oMasterAreaNodesRestricted[nodeMaster.nodeId] = nodeMasterElement; else oRes.oMasterAreaNodes[nodeMaster.nodeId] = nodeMaster; } } return oRes; }, _getNodeDependence:function ( oRes, oSheetRanges, node ) { var oResMapCycle = null; var bStop = false; var oWeightMapElem = oRes.oWeightMap[node.nodeId]; if ( null == oWeightMapElem ) { if(node.isDefinedName) oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 1, gray: false, bad: false, master: false, area: false }; else oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 1, gray: false, bad: false, master: false, area: node.isArea }; oRes.oWeightMap[node.nodeId] = oWeightMapElem; } else { oWeightMapElem.max++; //если пришли в gray node, то это цикл if (oWeightMapElem.gray) { bStop = true; oResMapCycle = {}; oResMapCycle[oWeightMapElem.id] = oWeightMapElem; oWeightMapElem.bad = true; oWeightMapElem.max--; } else if (oWeightMapElem.master && oWeightMapElem.max > 1) { bStop = true; //если повторно пришли в master node, то не считаем ее master oWeightMapElem.master = false; oWeightMapElem.max--; } } if (!bStop && 1 == oWeightMapElem.max && !node.isDefinedName ) this._getNodeDependenceNodeToRange( node.sheetId, node.getBBox(), oSheetRanges ); if (!bStop && oWeightMapElem.max <= 1) { oWeightMapElem.gray = true; var aNext = node.getSlaveEdges(); for (var i in aNext) { var oCurMapCycle = this._getNodeDependence(oRes, oSheetRanges, aNext[i], oWeightMapElem); if (null != oCurMapCycle) { oWeightMapElem.bad = true; for (var i in oCurMapCycle) { var oCurElem = oCurMapCycle[i]; if (oWeightMapElem != oCurElem) { if (null == oResMapCycle) oResMapCycle = {}; oResMapCycle[oCurElem.id] = oCurElem; } } } } oWeightMapElem.gray = false; } return oResMapCycle; }, _getNodeDependenceNodeToRange:function ( sheetId, bbox, oSheetRanges ) { var oSheetRange = oSheetRanges[sheetId]; if ( null == oSheetRange ) { oSheetRange = {range:null, changed:false, prevRange:null}; oSheetRanges[sheetId] = oSheetRange; } if ( null == oSheetRange.range || !oSheetRange.range.containsRange( bbox ) ) { if ( null == oSheetRange.range ) oSheetRange.range = bbox.clone(); else { if ( !oSheetRange.changed ) oSheetRange.prevRange = oSheetRange.range.clone(); oSheetRange.range.union2( bbox ); } oSheetRange.changed = true; } }, getAll:function () { return this.nodesId; }, /*Defined Names section*/ getDefNameNode:function ( node ) { var ret = this.defNameList[node]; return ret ? ret : null; }, getDefNameNodeByName:function ( name, sheetId ) { name = name.toLowerCase(); var sheetNodeList, nodeId, oRes = false; if ( !AscCommon.rx_defName.test( name ) ) { return oRes ; } if ( null != sheetId ) { sheetNodeList = this.defNameSheets[sheetId]; if ( sheetNodeList ) { nodeId = getDefNameVertexId( sheetId, name ); oRes = sheetNodeList[nodeId]; if ( oRes && oRes.Ref ) return oRes; } } sheetNodeList = this.defNameSheets["WB"]; if( sheetNodeList ){ nodeId = getDefNameVertexId( null, name ); oRes = sheetNodeList[nodeId]; } if ( oRes && !oRes.Ref ) oRes = false; return oRes; }, getDefNameNodeByRef:function ( ref, sheetId ) { var sheetNodeList; if ( null != sheetId ) { sheetNodeList = this.defNameSheets[sheetId]; for ( var id in sheetNodeList ) { if ( sheetNodeList[id].Ref == ref ) { return sheetNodeList[id].Name; } } } sheetNodeList = this.defNameSheets["WB"]; for ( var id in sheetNodeList ) { if ( sheetNodeList[id].Ref === ref ) { return sheetNodeList[id].Name; } } return false; }, addDefinedNameNode:function ( defName, sheetId, defRef, defHidden, bUndo ) { var ws = this.wb.getWorksheet( sheetId ) ws ? sheetId = ws.getId() : null; var nodeId = getDefNameVertexId( sheetId, defName ), oRes = this.defNameList[nodeId], dfv, defNameSheetsList; if ( null == oRes || ( null == oRes.Ref && null == defRef ) ) { dfv = new DefNameVertex( sheetId, defName, defRef, defHidden, this.wb ); oRes = (this.defNameList[dfv.nodeId] = dfv); defNameSheetsList = this.defNameSheets[dfv.sheetId]; if ( defNameSheetsList == null ) { defNameSheetsList = {}; this.defNameSheets[dfv.sheetId] = defNameSheetsList; } defNameSheetsList[dfv.nodeId] = dfv; } else if( null == oRes.Ref && null != defRef ){ oRes.Ref = defRef; oRes.isTable = undefined; addToArrDefNameRecalc(oRes); } /*поставить зависимость между ячейками и текущим ИД*/ if ( bUndo ) { oRes.Ref = defRef; } if( !oRes.isTable && oRes.Ref != undefined && oRes.Ref != null ){ addToArrDefNameRecalc(oRes); } return oRes; }, removeDefName:function ( sheetId, name ) { var ws = this.wb.getWorksheet( sheetId ); ws ? sheetId = ws.getId() : null; var nodeId = getDefNameVertexId( sheetId, name ), oRes = this.defNameList[nodeId], ret = null; if ( oRes ) { this.defNameList[nodeId].Ref = null; ret = oRes; addToArrDefNameRecalc(oRes); } return ret; }, removeDefNameBySheet:function ( sheetId ) { var nodesList = this.defNameList, retRes = {}, defN, seUndoRedo = [], nSE, wsIndex, ws = this.wb.getWorksheetById(sheetId ), wsName = ws.getName(); for ( var id in nodesList ) { defN = nodesList[id]; if ( defN.isTable && defN.Ref ){ var a = defN.Ref.split("!")[0]; if( a.localeCompare(parserHelp.getEscapeSheetName(wsName)) == 0 ){ History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesDelete, null, null, new UndoRedoData_DefinedNames( defN.Name, defN.Ref, undefined, defN.isTable ) ); defN.Ref = null; } continue; } if ( !defN.isTable && defN.parsedRef && defN.parsedRef.removeSheet( sheetId ) ) { seUndoRedo = []; nSE = defN.getSlaveEdges(); for ( var nseID in nSE ) { seUndoRedo.push( nseID ); } wsIndex = this.wb.getWorksheetById( defN.sheetId ); History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesDelete, null, null, new UndoRedoData_DefinedNames( defN.Name, defN.Ref, wsIndex ? wsIndex.getIndex() : undefined, defN.isTable, seUndoRedo ) ); if ( defN.sheetId == sheetId ) { defN.Ref = null; defN.parsedRef = null; retRes[id] = defN; } else if( defN.Ref ){ defN.Ref = defN.parsedRef.Formula = defN.parsedRef.assemble( true ); retRes[id] = defN; } addToArrDefNameRecalc(defN); } } return retRes; }, changeDefName:function ( oldDefName, newDefName ) { var ws = this.wb.getWorksheet( oldDefName.LocalSheetId ); var sheetId = ws ? ws.getId() : null; var oldN = this.getDefNameNodeByName( oldDefName.Name, sheetId ), sheetNodeList, nodeId, name = oldDefName.Name; sheetNodeList = this.defNameSheets[sheetId || "WB"]; nodeId = getDefNameVertexId( sheetId || "WB", name ); sheetNodeList ? delete sheetNodeList[nodeId] : null; delete this.defNameList[nodeId]; if(!oldN){ return false; } oldN.changeDefName( newDefName ); this.defNameList[oldN.nodeId] = oldN; sheetNodeList[oldN.nodeId] = oldN; if (oldDefName.isTable) { var dataRange = parserHelp.parse3DRef(oldDefName.Ref); if (dataRange) { var sheetDefName = this.wb.getWorksheetByName(dataRange.sheet); if (sheetDefName) { var tableParts = sheetDefName.TableParts; for (var i = 0; i < tableParts.length; i++) { if (tableParts[i].DisplayName == name) { tableParts[i].DisplayName = oldN.Name; } } } } } else { oldN.deleteAllMasterEdges(); addToArrDefNameRecalc(oldN); } return oldN; }, copyDefNameByWorksheet:function( oldSheetId, newSheetId ){ var obj = {}, oldS = this.defNameSheets[oldSheetId], defNamNode, oldWS = this.wb.getWorksheetById(oldSheetId ), newWS = this.wb.getWorksheetById(newSheetId); for( var id in oldS ){ defNamNode = oldS[id].clone(); defNamNode.changeScope(newSheetId); defNamNode.changeRefToNewSheet(oldWS.getName(),newWS.getName()); obj[defNamNode.nodeId] = defNamNode; this.defNameList[defNamNode.nodeId] = defNamNode; } this.defNameSheets[newSheetId] = obj; }, relinkDefNameByWorksheet:function (oName, nName){ var oldS = this.defNameList, dN; for( var id in oldS ){ dN = oldS[id]; if(dN.isTable ){ if(dN.Ref) dN.Ref = dN.Ref.replace(oName,nName); } else{ if( dN.Ref ){ dN.relinkRef(oName, nName); } } } }, saveDefName:function () { var list = [], defN; for ( var id in this.defNameList ) { defN = this.defNameList[id]; if ( defN.isTable ) { continue; } if ( defN.Ref != null ) { list.push( defN.getAscCDefName() ); } } return list; }, unlockDefName:function(){ var nodesList = this.defNameList; for ( var id in nodesList ) { if ( nodesList[id].isLock ) { delete nodesList[id].isLock; } } }, checkDefNameLock:function(){ var nodesList = this.defNameList, countNodes = 0; for ( var id in nodesList ) { countNodes++; if ( nodesList[id].isLock ) { return true; } } return !countNodes; // return false; }, getNextTableName:function ( ws, Ref ) { this.nTableNameMaxIndex++; var sNewName = this.sTableNamePattern + this.nTableNameMaxIndex, name = getDefNameVertexId( null, sNewName ); while ( this.defNameList[name] ) { this.nTableNameMaxIndex++; sNewName = this.sTableNamePattern + this.nTableNameMaxIndex; name = getDefNameVertexId( null, sNewName ); } this.addTableName( sNewName, ws, Ref ); return sNewName; }, addTableName:function ( sName, ws, Ref ) { var refClone, defNameSheetsList, dfv, nSE, se; if(this.defNameSheets["WB"]){ dfv = this.defNameSheets["WB"][getDefNameVertexId( null, sName )] } refClone = Ref.clone(true ) refClone.r1++; if(!dfv){ dfv = new DefNameVertex( null, sName, parserHelp.get3DRef( ws.getName(), refClone.getAbsName() ), null, this.wb, true ); defNameSheetsList = this.defNameSheets[dfv.sheetId]; this.defNameList[dfv.nodeId] = dfv; if ( defNameSheetsList == null ) { defNameSheetsList = {}; this.defNameSheets[dfv.sheetId] = defNameSheetsList; } defNameSheetsList[dfv.nodeId] = dfv; } else{ dfv.Ref = parserHelp.get3DRef( ws.getName(), refClone.getAbsName() ); nSE = dfv.getSlaveEdges(); for ( var id in nSE ) { se = nSE[id]; addToArrRecalc(se.sheetId, se.cell); this.wb.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.wb.needRecalc.length++; } } addToArrDefNameRecalc(dfv); }, changeTableName:function(tableName, ws, newRef){ var table = this.getDefNameNodeByName( tableName, ws ), newRefClone = newRef.clone(true); newRefClone.r1++; table.Ref = table.Ref.split("!")[0]+"!"+newRefClone.getAbsName(); table.rebuild(); // table.Ref = parserHelp.getEscapeSheetName(ws.getName())+"!"+newRef.getAbsName(); }, changeTableRef:function(tableName, ws, newName){ var table = this.getDefNameNodeByName( tableName, ws ); var newTable = table.clone(); if(table) { //изменяем имя именнованного диапазона newTable.Name = newName; newTable.cellId = newName.toLowerCase(); newTable.nodeId = table.sheetId + table.cellId; this.changeDefName(table, newTable); //изменяем все ссылки на данную таблицу var nameRef = tableName + "[]"; for(var i in this.defNameList) { if(this.defNameList[i] && this.defNameList[i].Ref && this.defNameList[i].Ref === nameRef) { this.defNameList[i].Ref = newName + "[]"; } } } table.rebuild(); }, delTableName:function(name,ws){ var table = this.getDefNameNodeByName( name, ws ); table.Ref = null; var nSE, se; nSE = table.getSlaveEdges(); table.deleteAllMasterEdges(); for ( var id in nSE ) { se = nSE[id]; addToArrRecalc(se.sheetId, se.cell); this.wb.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.wb.needRecalc.length++; } addToArrDefNameRecalc(table); }, rebuildTable:function(tableName){ var table = this.getDefNameNodeByName( tableName, null ), nSE, se, nME, range; nME = table.getMasterEdges(); for ( var id in nME ) { range = this.getInRange( nME[id].sheetId, nME[id].bbox ); for ( var i = 0; i < range.length; i++ ) { nSE = range[i].getSlaveEdges(); for ( var id in nSE ) { se = nSE[id]; se = se.returnCell(); if ( se ) { se.setFormula( se.formulaParsed.assemble() ); } } } } } }; /** @constructor */ function Vertex(sheetId, cellId, wb){ this.sheetId = sheetId; this.cellId = cellId; this.bbox = AscCommonExcel.g_oRangeCache.getAscRange(this.cellId); this.isArea = !this.bbox.isOneCell(); this.valid = true; this.nodeId = getVertexId(this.sheetId, this.cellId); this.wb = wb; this.cell = null; //вершина которую мы прошли и поставили в очередь обхода this.isBlack = false; //вершина которую мы прошли, но не поставили в очередь обхода. нужно для определения петель в графе. this.isGray = false; //если вершина входит в цикличный путь, то она помечается плохой и запоминается в списке плохих вершин. this.isBad = false; //masterEdges содержит ячейки, от которых зависит текущая ячейка this.masterEdges = {}; //slaveEdges содержит ячейки, которые зависят от данной ячейки this.slaveEdges = {}; this.refCount = 0; this.isDefinedName = false; } Vertex.prototype = { constructor: Vertex, getBBox : function() { return this.bbox; }, setFormula : function(sFormula, bAddToHistory, bAddNeedRecalc) { this.wb.dependencyFormulas.deleteMasterNodes2(this.sheetId, this.cellId); var cell = this.returnCell(); if (null != sFormula) cell.setFormula(sFormula, bAddToHistory); addToArrRecalc(this.sheetId, cell); if(bAddNeedRecalc) { this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId ]; this.wb.needRecalc.length++; } }, setRefError : function(wsId, cellId) { var sRes = null; var cell = this.returnCell(); if( cell && cell.formulaParsed ) { cell.formulaParsed.setRefError(wsId, cellId); sRes = cell.formulaParsed.assemble(true); } return sRes; }, moveInner: function (bboxTo) { //удаляем старые ссылки slave и master var slave, master; for (var i in this.slaveEdges) { slave = this.slaveEdges[i]; slave.deleteMasterEdge(this); } for (var i in this.masterEdges) { master = this.masterEdges[i]; master.deleteSlaveEdge(this); } this.bbox = bboxTo; this.cellId = bboxTo.getName(); this.nodeId = getVertexId(this.sheetId, this.cellId); this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId]; this.wb.needRecalc.length++; //добавляем новые slave и master for (var i in this.slaveEdges) { slave = this.slaveEdges[i]; slave.addMasterEdge(this); } for (var i in this.masterEdges) { master = this.masterEdges[i]; master.addSlaveEdge(this); } }, moveOuter: function (from, to, oFormulas) { if ((from.r1 == to.r1 && from.c1 == to.c1) || (from.r2 == to.r2 && from.c2 == to.c2)) { /*вставляем/удаляем по вертикали/горизонтали внутри диапазона*/ var _sn = this.getSlaveEdges(), slave, cell; for (var _id in _sn) { slave = _sn[_id]; if( slave instanceof DefNameVertex ){ if ( false == this.wb.bUndoChanges && (false == this.wb.bRedoChanges || true == this.wb.bCollaborativeChanges )){ History.LocalChange = true; var oN = slave.getAscCDefName(), nN; slave.parsedRef.stretchArea(this, from, to); nN = slave.getAscCDefName(); nN.Ref = slave.parsedRef.assemble(); this.wb.editDefinesNames( oN, nN ); History.LocalChange = false; } continue; } cell = slave.returnCell(); if (cell && cell.formulaParsed) { cell.formulaParsed.stretchArea(this, from, to); var formula = cell.formulaParsed.assemble(); if (null != formula) { if (oFormulas) oFormulas[slave.nodeId] = { node: slave, formula: formula }; else slave.setFormula(formula, true, false); } } } } else { /*вставляем.удаляем левее/выше вне диапазона*/ if (oFormulas) { if (null == oFormulas[this.nodeId]) oFormulas[this.nodeId] = { node: this, formula: null }; } else { var cell = this.returnCell(); if (cell && cell.formulaParsed) { this.wb.dependencyFormulas.deleteMasterNodes2(this.sheetId, this.cellId); addToArrRecalc(this.sheetId, cell); } } var _sn = this.getSlaveEdges(), slave, cell; for (var _id in _sn) { slave = _sn[_id] if( slave instanceof DefNameVertex ){ /*slave.parsedRef.shiftCells(this, from, to); slave.relinkRef();*/ if ( false == this.wb.bUndoChanges && (false == this.wb.bRedoChanges || true == this.wb.bCollaborativeChanges )){ History.LocalChange = true; var oN = slave.getAscCDefName(), nN; slave.parsedRef.shiftCells(this, from, to); nN = slave.getAscCDefName(); nN.Ref = slave.parsedRef.assemble(); this.wb.editDefinesNames( oN, nN ); History.LocalChange = false; } continue; } cell = slave.returnCell(); if (cell && cell.formulaParsed) { cell.formulaParsed.shiftCells(this, from, to); var formula = cell.formulaParsed.assemble(); if (null != formula) { if (oFormulas) oFormulas[slave.nodeId] = { node: slave, formula: formula }; else slave.setFormula(formula, true, false); } } } } }, //добавляем ведущую ячейку. addMasterEdge : function(node){ if( !this.masterEdges ){ this.masterEdges = {}; } if( !this.masterEdges[node.nodeId] ){ this.masterEdges[node.nodeId] = node; this.refCount ++; } }, //добавляем зависимую(ведомую) ячейку. addSlaveEdge : function(node){ if( !this.slaveEdges ){ this.slaveEdges = {}; } if( !this.slaveEdges[node.nodeId] ){ this.slaveEdges[node.nodeId] = node; this.refCount ++; } }, getMasterEdges : function(){ return this.masterEdges; }, getSlaveEdges : function(){ return this.slaveEdges; }, getSlaveEdges2 : function(){ var ret = {}, count = 0; for(var id in this.slaveEdges){ ret[id] = this.slaveEdges[id]; count++; } if ( count > 0 ) return ret; else return null; }, //удаляем ребро между конкретной ведущей ячейки. deleteMasterEdge: function (node) { if (this.masterEdges) { delete this.masterEdges[node.nodeId]; this.refCount--; } }, //удаляем ребро между конкретной зависимой(ведомой) ячейки. deleteSlaveEdge: function (node) { if (this.slaveEdges) { delete this.slaveEdges[node.nodeId]; this.refCount--; } }, //очищаем все ребра по ведущим ячейкам. deleteAllMasterEdges : function(){ var ret = {}; for( var id in this.masterEdges ){ var masterEdge = this.masterEdges[id]; masterEdge.deleteSlaveEdge(this); delete this.masterEdges[id]; this.refCount--; ret[id] = masterEdge; } this.masterEdges = {}; return ret; }, //очищаем все ребра по ведомым ячейкам. deleteAllSlaveEdges : function(){ var ret = {}; for( var id in this.slaveEdges ){ var slaveEdge = this.slaveEdges[id]; slaveEdge.deleteMasterEdge(this); delete this.slaveEdges[id]; this.refCount--; ret[id] = slaveEdge; } this.slaveEdges = {}; return ret; }, returnCell : function(){ //todo if(null == this.cell && this.wb && !this.isArea) { var ws = this.wb.getWorksheetById(this.sheetId); if(ws) this.cell = ws._getCell(this.bbox.r1, this.bbox.c1); // this.cell = ws._getCellNoEmpty(this.bbox.r1, this.bbox.c1); } return this.cell; } }; function DefNameVertex( scope, defName, defRef, defHidden, wb, isTable ) { this.sheetId = scope === null || scope === undefined ? "WB" : scope; this.cellId = defName.toLowerCase(); this.Ref = defRef; this.Name = defName; this.Hidden = defHidden; this.isTable = isTable; this.nodeId = getDefNameVertexId( this.sheetId, defName ); this.wb = wb; //вершина которую мы прошли и поставили в очередь обхода this.isBlack = false; //вершина которую мы прошли, но не поставили в очередь обхода. нужно для определения петель в графе. this.isGray = false; //если вершина входит в цикличный путь, то она помечается плохой и запоминается в списке плохих вершин. this.isBad = false; //masterEdges содержит ячейки, от которых зависит текущая ячейка this.masterEdges = {}; //slaveEdges содержит ячейки, которые зависят от данной ячейки this.slaveEdges = {}; this.refCount = 0; this.isDefinedName = true; } DefNameVertex.prototype = { constructor:Vertex, clone:function(){ var dN = new DefNameVertex( this.sheetId, this.cellId, this.Ref, this.Hidden, this.wb, this.isTable ); dN.parsedRef = new parserFormula( dN.Ref, "", this.wb.getWorksheet(0) ); if( dN.Ref ){ dN.parsedRef.parse(); // dN.parsedRef.buildDependencies(); } return dN; }, changeScope:function( newScope ){ this.sheetId = newScope === null || newScope === undefined ? "WB" : newScope; this.nodeId = getDefNameVertexId( this.sheetId, this.Name ); }, changeRefToNewSheet:function( lastName, newName ){ if( !this.isTable && this.parsedRef.isParsed ){ this.parsedRef = this.parsedRef.changeSheet( lastName, newName ); this.Ref = this.parsedRef.assemble(); } }, moveInner:function ( bboxTo ) { //удаляем старые ссылки slave и master for ( var i in this.slaveEdges ) { var slave = this.slaveEdges[i]; slave.deleteMasterEdge( this ); } for ( var i in this.masterEdges ) { var master = this.masterEdges[i]; master.deleteSlaveEdge( this ); } var sOldNodeId = this.nodeId; this.bbox = bboxTo; this.cellId = bboxTo.getName(); this.nodeId = getVertexId( this.sheetId, this.cellId ); this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId ]; this.wb.needRecalc.length++; //добавляем новые slave и master for ( var i in this.slaveEdges ) { var slave = this.slaveEdges[i]; slave.addMasterEdge( this ); } for ( var i in this.masterEdges ) { var master = this.masterEdges[i]; master.addSlaveEdge( this ); } }, moveOuter:function ( from, to, oFormulas ) { if ( (from.r1 == to.r1 && from.c1 == to.c1) || (from.r2 == to.r2 && from.c2 == to.c2) ) { var _sn = this.getSlaveEdges(); for ( var _id in _sn ) { var slave = _sn[_id]; var cell = slave.returnCell(); if ( cell && cell.formulaParsed ) { cell.formulaParsed.stretchArea( this, from, to ); var formula = cell.formulaParsed.assemble(); if ( null != formula ) { if ( oFormulas ) oFormulas[slave.nodeId] = { node:slave, formula:formula }; else slave.setFormula( formula, true, false ); } } } } else { if ( oFormulas ) { if ( null == oFormulas[this.nodeId] ) oFormulas[this.nodeId] = { node:this, formula:null }; } else { var cell = this.returnCell(); if ( cell && cell.formulaParsed ) { this.wb.dependencyFormulas.deleteMasterNodes2( this.sheetId, this.cellId ); addToArrRecalc( this.sheetId, cell ); } } var _sn = this.getSlaveEdges(); for ( var _id in _sn ) { var slave = _sn[_id] var cell = slave.returnCell(); if ( cell && cell.formulaParsed ) { cell.formulaParsed.shiftCells( this, from, to ); var formula = cell.formulaParsed.assemble(); if ( null != formula ) { if ( oFormulas ) oFormulas[slave.nodeId] = { node:slave, formula:formula }; else slave.setFormula( formula, true, false ); } } } } }, //добавляем ведущую ячейку. addMasterEdge:function ( node ) { if ( !this.masterEdges ) { this.masterEdges = {}; } if ( !this.masterEdges[node.nodeId] ) { this.masterEdges[node.nodeId] = node; this.refCount++; } }, //добавляем зависимую(ведомую) ячейку. addSlaveEdge:function ( node ) { if ( !this.slaveEdges ) { this.slaveEdges = {}; } if ( !this.slaveEdges[node.nodeId] ) { this.slaveEdges[node.nodeId] = node; this.refCount++; } }, getMasterEdges:function () { return this.masterEdges; }, getSlaveEdges:function () { return this.slaveEdges; }, getSlaveEdges2:function () { var ret = {}, count = 0; for ( var id in this.slaveEdges ) { ret[id] = this.slaveEdges[id]; count++; } if ( count > 0 ) return ret; else return null; }, //удаляем ребро между конкретной ведущей ячейки. deleteMasterEdge:function ( node ) { if ( this.masterEdges ) { delete this.masterEdges[node.nodeId]; this.refCount--; } }, //удаляем ребро между конкретной зависимой(ведомой) ячейки. deleteSlaveEdge:function ( node ) { if ( this.slaveEdges ) { delete this.slaveEdges[node.nodeId]; this.refCount--; } }, //очищаем все ребра по ведущим ячейкам. deleteAllMasterEdges:function () { var ret = {}; for ( var id in this.masterEdges ) { var masterEdge = this.masterEdges[id]; masterEdge.deleteSlaveEdge( this ); this.masterEdges[id] = null; delete this.masterEdges[id]; this.refCount--; ret[id] = masterEdge; } this.masterEdges = {}; return ret; }, //очищаем все ребра по ведомым ячейкам. deleteAllSlaveEdges:function () { var ret = {}; for ( var id in this.slaveEdges ) { var slaveEdge = this.slaveEdges[id]; slaveEdge.deleteMasterEdge( this ); this.slaveEdges[id] = null; delete this.slaveEdges[id]; this.refCount--; ret[id] = slaveEdge; } this.slaveEdges = {}; return ret; }, returnCell:function () { //todo return false; // if ( null == this.cell && this.wb && !this.isArea && this.Ref !== null && this.Ref !== undefined ) { // var ws = this.wb.getWorksheetById( this.sheetId ); // if ( ws ) // this.cell = ws._getCellNoEmpty( this.bbox.r1, this.bbox.c1 ); // } // return this.cell; }, getAscCDefName:function () { var a = this.wb.getWorksheetById( this.sheetId ); return new Asc.asc_CDefName( this.Name, this.Ref, this.sheetId == "WB" ? null : a ? a.getIndex() : null, this.isTable, this.Hidden, this.isLock ); }, changeDefName:function ( newName ) { this.cellId = newName.Name.toLowerCase(); this.Ref = newName.Ref; this.Name = newName.Name; this.nodeId = getDefNameVertexId( this.sheetId, newName.Name ); }, relinkRef:function(oName, nName){ if( this.parsedRef && this.parsedRef.isParsed ){ this.Ref = this.parsedRef.assemble(); } }, renameDefNameToCollaborate:function(name){ var lastname = this.Name; //из-за особенностей реализации формул, сначала делаем parse со старым именем, потом преименовываем, потом assemble var aFormulas = []; //переименование для отправки изменений for(var i = 0, length = this.wb.aCollaborativeActions.length; i < length; ++i) { var aPointActions = this.wb.aCollaborativeActions[i]; for (var j = 0, length2 = aPointActions.length; j < length2; ++j) { var action = aPointActions[j]; if (AscCommonExcel.g_oUndoRedoWorkbook == action.oClass) { if (AscCH.historyitem_Workbook_DefinedNamesAdd == action.nActionType) { if (lastname == action.oData.newName.Name) action.oData.newName.Name = name; } } else if (AscCommonExcel.g_oUndoRedoCell == action.oClass) { if (action.oData instanceof UndoRedoData_CellSimpleData) { if (action.oData.oNewVal instanceof UndoRedoData_CellValueData) { var oNewVal = action.oData.oNewVal; if (null != oNewVal.formula && -1 != oNewVal.formula.indexOf(lastname)) { var oParser = new parserFormula(oNewVal.formula, "A1", this.wb.getWorksheet(0)); oParser.parse(); aFormulas.push({ formula: oParser, value: oNewVal }); } } } } } } var clone = this.clone(); clone.Name = name; this.wb.editDefinesNames( this.getAscCDefName(), clone.getAscCDefName() ); for(var i = 0, length = aFormulas.length; i < length; ++i) { var item = aFormulas[i]; item.value.formula = item.formula.assemble(); } }, rebuild:function(){ if(this.Ref){ this.deleteAllMasterEdges(); this.parsedRef = new parserFormula(this.Ref, "", this.wb.getWorksheet(0)); this.parsedRef.parse(); this.parsedRef.buildDependencies(null,this); } } }; function getVertexId(sheetId, cellId){ return sheetId + AscCommon.g_cCharDelimiter + cellId; } function getDefNameVertexId(scope, name){ return ( scope === null || scope === undefined ? "WB" : scope ) + AscCommon.g_cCharDelimiter + name.toLowerCase(); } function addToArrRecalc(sheetId, cell){ var temp = arrRecalc[sheetId]; if( !temp ) { temp = []; arrRecalc[sheetId] = temp; } temp.push(cell); } function addToArrDefNameRecalc(name){ arrDefNameRecalc[name.nodeId] = name; } function buildDefNameAfterRenameWorksheet() { var dN; for(var id in arrDefNameRecalc ){ dN = arrDefNameRecalc[id]; if( !dN.parsedRef && dN.Ref ){ dN.parsedRef = new parserFormula(dN.Ref, "", ws.workbook.getWorksheet(0)); dN.parsedRef.parse(); } } } function angleFormatToInterface(val) { var nRes = 0; if(0 <= val && val <= 180) nRes = val <= 90 ? val : 90 - val; return nRes; } function angleFormatToInterface2(val) { if(g_nVerticalTextAngle == val) return val; else return angleFormatToInterface(val); } function angleInterfaceToFormat(val) { var nRes = val; if(-90 <= val && val <= 90) { if(val < 0) nRes = 90 - val; } else if(g_nVerticalTextAngle != val) nRes = 0; return nRes; } function getUniqueKeys(array) { var i, o = {}; for (i = 0; i < array.length; ++i) { o[array[i]] = o.hasOwnProperty(array[i]); } return o; } //------------------------------------------------------------------------------------------------- /** * @constructor */ function Workbook(eventsHandlers, oApi){ this.oApi = oApi; this.handlers = eventsHandlers; this.needRecalc = {nodes: {}, length:0}; this.dependencyFormulas = new DependencyGraph(this); this.nActive = 0; this.theme = null; this.clrSchemeMap = null; this.DefinedNames = {}; this.oRealDefinedNames = {}; // this.oNameGenerator = new NameGenerator(this); this.CellStyles = new AscCommonExcel.CCellStyles(); this.TableStyles = new Asc.CTableStyles(); this.oStyleManager = new AscCommonExcel.StyleManager(); this.calcChain = []; this.aComments = []; // Комментарии к документу this.aCommentsCoords = []; this.aWorksheets = []; this.aWorksheetsById = {}; this.cwf = {}; this.aCollaborativeActions = []; this.bCollaborativeChanges = false; this.bUndoChanges = false; this.bRedoChanges = false; this.aCollaborativeChangeElements = []; this.wsHandlers = null; this.openErrors = []; this.lockCounter = 0; } Workbook.prototype.init=function(bNoBuildDep){ if(this.nActive < 0) this.nActive = 0; if(this.nActive >= this.aWorksheets.length) this.nActive = this.aWorksheets.length - 1; var self = this; this.wsHandlers = new AscCommonExcel.asc_CHandlersList( /*handlers*/{ "changeRefTablePart" : function ( displayName, ref ) { self.dependencyFormulas.changeTableName( displayName, null, ref ); }, "changeColumnTablePart": function ( tableName ) { self.dependencyFormulas.rebuildTable( tableName ); }, "delTable" : function ( name, ws ) { self.dependencyFormulas.delTableName( name, ws ); } } ); //charts for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var ws = this.aWorksheets[i]; ws.initPostOpen(this.wsHandlers); } if(!bNoBuildDep){ /* buildDependency необходимо запускать для построения графа зависимостей между ячейками. Сортировка графа производится при необходимости пересчета формул: при открытии документа если есть ячейки помеченные как пересчитываемые или есть ячейки без значения. */ this.buildDependency(); this.sortDependency(); } }; Workbook.prototype.rebuildColors=function(){ AscCommonExcel.g_oColorManager.rebuildColors(); for(var i = 0 , length = this.aWorksheets.length; i < length; ++i) this.aWorksheets[i].rebuildColors(); }; Workbook.prototype.getDefaultFont=function(){ return g_oDefaultFormat.Font.fn; }; Workbook.prototype.getDefaultSize=function(){ return g_oDefaultFormat.Font.fs; }; Workbook.prototype.getActive=function(){ return this.nActive; }; Workbook.prototype.getActiveWs = function () { return this.getWorksheet(this.nActive); }; Workbook.prototype.setActive=function(index){ if(index >= 0 && index < this.aWorksheets.length){ this.nActive = index; return true; } return false; }; Workbook.prototype.getWorksheet=function(index){ //index 0-based if(index >= 0 && index < this.aWorksheets.length){ return this.aWorksheets[index]; } return null; }; Workbook.prototype.getWorksheetById=function(id){ return this.aWorksheetsById[id]; }; Workbook.prototype.getWorksheetByName=function(name){ for(var i = 0; i < this.aWorksheets.length; i++) if(this.aWorksheets[i].getName() == name){ return this.aWorksheets[i]; } return null; }; Workbook.prototype.getWorksheetIndexByName=function(name){ for(var i = 0; i < this.aWorksheets.length; i++) if(this.aWorksheets[i].getName() == name){ return i; } return null; }; Workbook.prototype.getWorksheetCount=function(){ return this.aWorksheets.length; }; Workbook.prototype.createWorksheet=function(indexBefore, sName, sId){ History.Create_NewPoint(); History.TurnOff(); var wsActive = this.getActiveWs(); var oNewWorksheet = new Woorksheet(this, this.aWorksheets.length, sId); if (this.checkValidSheetName(sName)) oNewWorksheet.sName = sName; oNewWorksheet.initPostOpen(this.wsHandlers); if(null != indexBefore && indexBefore >= 0 && indexBefore < this.aWorksheets.length) this.aWorksheets.splice(indexBefore, 0, oNewWorksheet); else { indexBefore = this.aWorksheets.length; this.aWorksheets.push(oNewWorksheet); } this.aWorksheetsById[oNewWorksheet.getId()] = oNewWorksheet; this._updateWorksheetIndexes(wsActive); History.TurnOn(); this._insertWorksheetFormula(oNewWorksheet.index); History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(indexBefore, oNewWorksheet.getName(), null, oNewWorksheet.getId())); History.SetSheetUndo(wsActive.getId()); History.SetSheetRedo(oNewWorksheet.getId()); return oNewWorksheet.index; }; Workbook.prototype.copyWorksheet=function(index, insertBefore, sName, sId, bFromRedo){ //insertBefore - optional if(index >= 0 && index < this.aWorksheets.length){ History.TurnOff(); var wsActive = this.getActiveWs(); var wsFrom = this.aWorksheets[index]; var newSheet = wsFrom.clone(sId, sName); newSheet.initPostOpen(this.wsHandlers); if(null != insertBefore && insertBefore >= 0 && insertBefore < this.aWorksheets.length){ //помещаем новый sheet перед insertBefore this.aWorksheets.splice(insertBefore, 0, newSheet); } else{ //помещаем новый sheet в конец this.aWorksheets.push(newSheet); } this.aWorksheetsById[newSheet.getId()] = newSheet; this._updateWorksheetIndexes(wsActive); History.TurnOn(); this._insertWorksheetFormula(insertBefore); this.dependencyFormulas.copyDefNameByWorksheet( wsFrom.getId(), newSheet.getId() ); //для формул. создаем копию this.cwf[this.Id] для нового листа. if ( this.cwf[wsFrom.getId()] ){ var cwf = { cells:{} }; var newSheetId = newSheet.getId(); var cwfFrom = this.cwf[wsFrom.getId()]; this.cwf[newSheetId] = cwf; for( var id in cwfFrom.cells ){ cwf.cells[id] = cwfFrom.cells[id]; this.needRecalc.nodes[getVertexId(newSheetId, id)] = [newSheetId, id]; this.needRecalc.length++; } newSheet._BuildDependencies(cwf.cells); } History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(insertBefore, newSheet.getName(), wsFrom.getId(), newSheet.getId())); History.SetSheetUndo(wsActive.getId()); History.SetSheetRedo(newSheet.getId()); if(!(bFromRedo === true)) { wsFrom.copyDrawingObjects(newSheet, wsFrom); } this.sortDependency(); } }; Workbook.prototype.insertWorksheet = function (index, sheet, cwf) { var wsActive = this.getActiveWs(); if(null != index && index >= 0 && index < this.aWorksheets.length){ //помещаем новый sheet перед insertBefore this.aWorksheets.splice(index, 0, sheet); } else{ //помещаем новый sheet в конец this.aWorksheets.push(sheet); } this.aWorksheetsById[sheet.getId()] = sheet; this._updateWorksheetIndexes(wsActive); this._insertWorksheetFormula(index); this._insertTablePartsName(sheet); //восстанавливаем список ячеек с формулами для sheet this.cwf[sheet.getId()] = cwf; sheet._BuildDependencies(cwf.cells); this.sortDependency(); }; Workbook.prototype._insertTablePartsName = function (sheet) { if(sheet && sheet.TableParts && sheet.TableParts.length) { for(var i = 0; i < sheet.TableParts.length; i++) { var oNewTable = sheet.TableParts[i]; this.dependencyFormulas.addTableName(oNewTable.DisplayName, sheet, oNewTable.Ref); } } }; Workbook.prototype._insertWorksheetFormula=function(index){ if( index > 0 && index < this.aWorksheets.length - 1 ){ var oWsTo = this.aWorksheets[index - 1]; var nodesSheetTo = this.dependencyFormulas.getNodeBySheetId(oWsTo.getId()); for( var i = 0; i < nodesSheetTo.length; i++ ){ var se = nodesSheetTo[i].getSlaveEdges(); if(se) { for( var id in se ){ var slave = se[id]; if(slave.isDefinedName){ continue; } var cell = slave.returnCell(); if( cell && cell.formulaParsed && cell.formulaParsed.is3D ) { if(cell.formulaParsed.insertSheet(index)) slave.setFormula(null, false, true); } } } } } }; Workbook.prototype.replaceWorksheet=function(indexFrom, indexTo){ if(indexFrom >= 0 && indexFrom < this.aWorksheets.length && indexTo >= 0 && indexTo < this.aWorksheets.length){ History.Create_NewPoint(); History.TurnOff(); var wsActive = this.getActiveWs(); var oWsFrom = this.aWorksheets[indexFrom]; var oWsTo = this.aWorksheets[indexTo]; var tempW = { wFN: oWsFrom.getName(), wFI: indexFrom, wFId: oWsFrom.getId(), wTN: oWsTo.getName(), wTI: indexTo, wTId: oWsTo.getId() }; //переводим обратно в индекс sheet перед которым надо вставить if(tempW.wFI < tempW.wTI) tempW.wTI++; /* Формулы: перестройка графа для трехмерных формул вида Sheet1:Sheet3!A1:A3, Sheet1:Sheet3!A1. пересчет трехмерных формул, перестройка формул при изменении положения листа: Sheet1, Sheet2, Sheet3, Sheet4 - Sheet1:Sheet4!A1 -> Sheet4, Sheet1, Sheet2, Sheet3 - Sheet1:Sheet3!A1; */ this.lockDraw(); var a = this.dependencyFormulas.getNodeBySheetId(tempW.wFId); for(var i=0;i<a.length;i++){ var se = a[i].getSlaveEdges(); if(se){ for(var id in se){ var slave = se[id]; if( slave.isDefinedName ) continue; var cell = slave.returnCell(); if( cell && cell.formulaParsed && cell.formulaParsed.is3D ) { var nMoveRes = cell.formulaParsed.moveSheet(tempW, true); if(2 == nMoveRes) slave.setFormula(cell.formulaParsed.assemble(), true, true); else if(1 == nMoveRes) slave.setFormula(null, false, true); } } } } History.TurnOn(); var movedSheet = this.aWorksheets.splice(indexFrom, 1); this.aWorksheets.splice(indexTo, 0, movedSheet[0]); this._updateWorksheetIndexes(wsActive); this._insertWorksheetFormula(tempW.wTI); History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetMove, null, null, new UndoRedoData_FromTo(indexFrom, indexTo), true); this.unLockDraw(); this.buildRecalc(); } }; Workbook.prototype.findSheetNoHidden = function (nIndex) { var i, ws, oRes = null, bFound = false, countWorksheets = this.getWorksheetCount(); for (i = nIndex; i < countWorksheets; ++i) { ws = this.getWorksheet(i); if (false === ws.getHidden()) { oRes = ws; bFound = true; break; } } // Не нашли справа, ищем слева от текущего if (!bFound) { for (i = nIndex - 1; i >= 0; --i) { ws = this.getWorksheet(i); if (false === ws.getHidden()) { oRes = ws; break; } } } return oRes; }; Workbook.prototype.removeWorksheet=function(nIndex, outputParams){ //проверяем останется ли хоть один нескрытый sheet var bEmpty = true; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var worksheet = this.aWorksheets[i]; if(false == worksheet.getHidden() && i != nIndex) { bEmpty = false; break; } } if(bEmpty) return -1; var removedSheet = this.getWorksheet(nIndex); if(removedSheet) { History.Create_NewPoint(); var removedSheetId = removedSheet.getId(); this.lockDraw(); var retRes = this.dependencyFormulas.removeDefNameBySheet( removedSheetId ), nSE, se, seUndoRedo = []; var a = this.dependencyFormulas.getNodeBySheetId(removedSheetId); for(var i = 0; i < a.length; i++) { var node = a[i]; var se = node.getSlaveEdges(); if(se){ for(var id in se){ var slave = se[id]; var cell = slave.returnCell(); if( cell && cell.formulaParsed && cell.formulaParsed.is3D ) { if(cell.formulaParsed.removeSheet(removedSheetId)) slave.setFormula(cell.formulaParsed.assemble(true), true, true); } } } } //по всем удаленным листам пробегаемся и удаляем из workbook.cwf (cwf - cells with forluma) элементы с названием соответствующего листа. this.dependencyFormulas.removeNodeBySheetId(removedSheetId); var _cwf = this.cwf[removedSheetId]; delete this.cwf[removedSheetId]; if ( retRes ) { /* * #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка. * для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон. * #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку; * удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу. * */ for( var defNameID in retRes ){ nSE = retRes[defNameID].getSlaveEdges(); retRes[defNameID].deleteAllMasterEdges(); for ( var id in nSE ) { // seUndoRedo.push( id ); se = nSE[id]; se.deleteMasterEdge( retRes[defNameID] ); this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.needRecalc.length++; se = se.returnCell(); se ? function () { se.setFormula( se.formulaParsed.assemble() ); se.formulaParsed.isParsed = false; se.formulaParsed.parse(); se.formulaParsed.buildDependencies(); }() : null; } } } var wsActive = this.getActiveWs(); var oVisibleWs = null; this.aWorksheets.splice(nIndex, 1); delete this.aWorksheetsById[removedSheetId]; if (nIndex == this.getActive()) { oVisibleWs = this.findSheetNoHidden(nIndex); if (null != oVisibleWs) wsActive = oVisibleWs; } History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetRemove, null, null, new AscCommonExcel.UndoRedoData_SheetRemove(nIndex, removedSheetId, removedSheet, _cwf)); if (null != oVisibleWs) { History.SetSheetUndo(removedSheetId); History.SetSheetRedo(wsActive.getId()); } if(null != outputParams) { outputParams.sheet = removedSheet; outputParams.cwf = _cwf; } this._updateWorksheetIndexes(wsActive); this.unLockDraw(); this.buildRecalc(); return wsActive.getIndex(); } return -1; }; Workbook.prototype._updateWorksheetIndexes = function (wsActive) { for(var i = 0, length = this.aWorksheets.length; i < length; ++i) this.aWorksheets[i]._setIndex(i); if (null != wsActive) this.setActive(wsActive.getIndex()); }; Workbook.prototype.checkUniqueSheetName=function(name){ var workbookSheetCount = this.getWorksheetCount(); for (var i = 0; i < workbookSheetCount; i++){ if (this.getWorksheet(i).getName() == name) return i; } return -1; }; Workbook.prototype.checkValidSheetName=function(name){ return (name && name.length < g_nSheetNameMaxLength); }; Workbook.prototype.getUniqueSheetNameFrom=function(name, bCopy){ var nIndex = 1; var sNewName = ""; var fGetPostfix = null; if(bCopy) { var result = /^(.*)\((\d)\)$/.exec(name); if(result) { fGetPostfix = function(nIndex){return "(" + nIndex +")";}; name = result[1]; } else { fGetPostfix = function(nIndex){return " (" + nIndex +")";}; name = name; } } else { fGetPostfix = function(nIndex){return nIndex.toString();}; } var workbookSheetCount = this.getWorksheetCount(); while(nIndex < 10000) { var sPosfix = fGetPostfix(nIndex); sNewName = name + sPosfix; if(sNewName.length > g_nSheetNameMaxLength) { name = name.substring(0, g_nSheetNameMaxLength - sPosfix.length); sNewName = name + sPosfix; } var bUniqueName = true; for (var i = 0; i < workbookSheetCount; i++){ if (this.getWorksheet(i).getName() == sNewName) { bUniqueName = false; break; } } if(bUniqueName) break; nIndex++; } return sNewName; }; Workbook.prototype._generateFontMap=function(){ var oFontMap = { "Arial" : 1 }; if(null != g_oDefaultFormat.Font.fn) oFontMap[g_oDefaultFormat.Font.fn] = 1; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) this.aWorksheets[i].generateFontMap(oFontMap); this.CellStyles.generateFontMap(oFontMap); return oFontMap; }; Workbook.prototype.generateFontMap=function(){ var oFontMap = this._generateFontMap(); var aRes = []; for(var i in oFontMap) aRes.push(i); return aRes; }; Workbook.prototype.generateFontMap2=function(){ var oFontMap = this._generateFontMap(); var aRes = []; for(var i in oFontMap) aRes.push(new AscFonts.CFont(i, 0, "", 0)); return aRes; }; Workbook.prototype.recalcWB = function(isRecalcWB){ //todo if ( this.dependencyFormulas.getNodesLength() > 0 ) { var aNodes = isRecalcWB ? this.dependencyFormulas.getAll() : this.dependencyFormulas.getNodeBySheetIdAll(this.getWorksheet(this.getActive()).getId()); var nR = this.needRecalc; for ( var i in aNodes ) { var node = aNodes[i]; if ( !node.isArea ) { nR.nodes[node.nodeId] = [node.sheetId, node.cellId]; nR.length++; } } this.sortDependency(); } }; Workbook.prototype.checkDefName = function ( checkName, scope ) { var rxTest = AscCommon.rx_defName.test( checkName ), res = new Asc.asc_CCheckDefName(); if ( !rxTest ) { res.status = false; res.reason = c_oAscDefinedNameReason.WrongName; return res; } if( scope !== null ){ scope = this.getWorksheet(scope).getId(); } var defName = this.dependencyFormulas.getDefNameNode(getDefNameVertexId(scope, checkName)); if(defName){ defName = defName.getAscCDefName(); res.status = false; if(defName.isLock){ res.reason = c_oAscDefinedNameReason.IsLocked; } else if( defName.Ref == null ){ res.reason = c_oAscDefinedNameReason.NameReserved; } else{ res.reason = c_oAscDefinedNameReason.Existed; } } else{ res.status = true; res.reason = c_oAscDefinedNameReason.OK; } return res; }; Workbook.prototype.isDefinedNamesExists = function ( name, sheetId ) { var n = name.toLowerCase(); return !!this.dependencyFormulas.defNameList[getDefNameVertexId(sheetId, n)]; }; Workbook.prototype.getDefinedNamesWB = function (defNameListId) { var names = [], name, thas = this, activeWS; /*c_oAscGetDefinedNamesList. Worksheet : 0, WorksheetWorkbook : 1, All*/ function getNames(id,arr){ var listDN = thas.dependencyFormulas.defNameSheets[id], name; for ( var id in listDN ) { name = listDN[id] if ( name.Ref && !name.Hidden && name.Name.indexOf("_xlnm") < 0 ) { if( name.isTable || name.parsedRef && name.parsedRef.isParsed && name.parsedRef.countRef == 1 && name.parsedRef.outStack.length == 1 && name.parsedRef.calculate().errorType !== AscCommonExcel.cErrorType.bad_reference ){ arr.push( name.getAscCDefName() ); } } } } function sort(a,b){ if (a.Name > b.Name) return 1; if (a.Name < b.Name) return -1; } switch(defNameListId){ case c_oAscGetDefinedNamesList.Worksheet: case c_oAscGetDefinedNamesList.WorksheetWorkbook: activeWS = this.getActiveWs(); getNames(activeWS.getId(),names); if( c_oAscGetDefinedNamesList.WorksheetWorkbook ){ getNames("WB",names); } break; case c_oAscGetDefinedNamesList.All: default: for ( var id in this.dependencyFormulas.defNameList ) { name = this.dependencyFormulas.defNameList[id].getAscCDefName() if ( name.Ref && !name.Hidden && name.Name.indexOf("_xlnm") < 0 ) { names.push( name ); } } break; } return names.sort(sort); }; Workbook.prototype.getDefinesNames = function ( name, sheetId ) { return this.dependencyFormulas.getDefNameNodeByName( name, sheetId ); }; Workbook.prototype.getDefinedName = function ( name ) { var ws = this.getWorksheet( name.LocalSheetId ), sheetId = null; ws ? sheetId = ws.getId() : null; return this.dependencyFormulas.getDefNameNodeByName( name.Name, sheetId ); }; Workbook.prototype.delDefinesNames = function ( defName, bUndo ) { History.Create_NewPoint(); var retRes = false; retRes = this.dependencyFormulas.removeDefName( defName.LocalSheetId, defName.Name ); if ( retRes ) { /* * #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка. * для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон. * #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку; * удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу. * */ var nSE, se, seUndoRedo = []; nSE = retRes.getSlaveEdges(); retRes.deleteAllMasterEdges(); for ( var id in nSE ) { seUndoRedo.push( id ); se = nSE[id]; addToArrRecalc(se.sheetId, se.cell); this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.needRecalc.length++; } if(!bUndo) this.buildRecalc(); History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesDelete, null, null, new UndoRedoData_DefinedNames( defName.Name, defName.Ref, defName.LocalSheetId, defName.isTable, seUndoRedo ) ); } return retRes; }; Workbook.prototype.editDefinesNames = function ( oldName, newName, bUndo ) { var newN = newName.Name.toLowerCase(), retRes = null, rename = false, nSE, se; if ( !AscCommon.rx_defName.test( newN ) || !newName.Ref || newName.Ref.length == 0 ) { return retRes; } if ( oldName ) { this.buildRecalc(true, true); retRes = this.dependencyFormulas.changeDefName( oldName, newName ); rename = true; } else { retRes = this.dependencyFormulas.addDefinedNameNode( newName.Name, newName.LocalSheetId, newName.Ref, newName.Hidden, bUndo ); } if ( retRes ) { History.Create_NewPoint(); /* #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка. для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон. #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку; удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу.*/ if( !rename ){ retRes = this.dependencyFormulas.getDefNameNodeByName(newName.Name) } if(retRes){ nSE = retRes.getSlaveEdges(); } for ( var id in nSE ) { se = nSE[id]; se.deleteMasterEdge( retRes ); this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.needRecalc.length++; addToArrRecalc(se.sheetId, se.cell); se = se.returnCell(); if ( se ) { se.setFormula( se.formulaParsed.assemble() ); if ( !rename ) { se.formulaParsed.setFormula(se.sFormula); } } } if ( rename ) { History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesChange, null, null, new UndoRedoData_DefinedNamesChange( oldName, newName ) ); } else { History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesAdd, null, null, new UndoRedoData_DefinedNamesChange( oldName, newName ) ); } /*if(retRes){ retRes = retRes.getAscCDefName(); }*/ } if(!bUndo) this.buildRecalc(); return retRes; }; Workbook.prototype.findDefinesNames = function ( ref, sheetId ) { return this.dependencyFormulas.getDefNameNodeByRef( ref, sheetId ); }; Workbook.prototype.unlockDefName = function(){ this.dependencyFormulas.unlockDefName(); }; Workbook.prototype.checkDefNameLock = function(){ return this.dependencyFormulas.checkDefNameLock(); }; Workbook.prototype.getUniqueDefinedNameFrom=function(name, bCopy){ var nIndex = 1, dnNewName = "", fGetPostfix = null, name = name.Name, sheetId = name.sheetId; if(bCopy) { var result = /^(.*)(\d)$/.exec(name); if(result) { fGetPostfix = function(nIndex){return "" + nIndex;}; name = result[1]; } else { fGetPostfix = function(nIndex){return "_" + nIndex;}; name = name; } } else { fGetPostfix = function(nIndex){return nIndex.toString();}; } while(nIndex < 10000) { var sPosfix = fGetPostfix(nIndex); dnNewName = name + sPosfix; var bUniqueName = false; if(!this.isDefinedNamesExists( dnNewName, sheetId )){ bUniqueName = true; break; } if(bUniqueName) break; nIndex++; } return dnNewName; }; Workbook.prototype.buildDependency = function(){ this.dependencyFormulas.clear(); // this.dependencyFormulas = null; // this.dependencyFormulas = new DependencyGraph(this); for(var i in this.cwf){ this.getWorksheetById(i)._BuildDependencies(this.cwf[i].cells); } }; Workbook.prototype.recalcDependency = function(f,bad,notRecalc){ if(f.length > 0){ var sr = {}; for(var i = 0; i < f.length; i++){ var sheetID = f[i].sheetId, cellID = f[i].cellId, selectedSheet; if( cellID.indexOf(":") > -1 ) continue; var l = new CellAddress(cellID); var lRow = l.getRow(), lCol = l.getCol(); if( !(sheetID in sr) ){ sr[sheetID] = {max:new CellAddress(cellID),min:new CellAddress(cellID)} } selectedSheet = sr[sheetID]; if ( selectedSheet.min.getRow() > lRow ) selectedSheet.min = new CellAddress( lRow, selectedSheet.min.getCol() ); if ( selectedSheet.min.getCol() > lCol ) selectedSheet.min = new CellAddress( selectedSheet.min.getRow(), lCol ); if ( selectedSheet.max.getRow() < lRow ) selectedSheet.max = new CellAddress( lRow, selectedSheet.max.getCol() ); if ( selectedSheet.max.getCol() < lCol ) selectedSheet.max = new CellAddress( selectedSheet.max.getRow(), lCol ); if( !notRecalc ) this.getWorksheetById( sheetID )._RecalculatedFunctions( cellID, bad ); } return sr; } }; Workbook.prototype._SerializeHistoryBase64 = function (oMemory, item, aPointChangesBase64) { if (!item.LocalChange) { var nPosStart = oMemory.GetCurPosition(); item.Serialize(oMemory, this.oApi.collaborativeEditing); var nPosEnd = oMemory.GetCurPosition(); var nLen = nPosEnd - nPosStart; if (nLen > 0) aPointChangesBase64.push(nLen + ";" + oMemory.GetBase64Memory2(nPosStart, nLen)); } }; Workbook.prototype.SerializeHistory = function(){ var aRes = []; //соединяем изменения, которые были до приема данных с теми, что получились после. var worksheets = this.aWorksheets, t, j, length2; for(t = 0; t < worksheets.length; ++t) { worksheets[t] && worksheets[t].refreshContentChanges(); } var aActions = this.aCollaborativeActions.concat(History.GetSerializeArray()); if(aActions.length > 0) { var oMemory = new AscCommon.CMemory(); var bChangeSheetPlace = false; for(var i = 0, length = aActions.length; i < length; ++i) { var aPointChanges = aActions[i]; bChangeSheetPlace = false; for (j = 0, length2 = aPointChanges.length; j < length2; ++j) { var item = aPointChanges[j]; if (AscCommonExcel.g_oUndoRedoWorkbook == item.oClass) { if (AscCH.historyitem_Workbook_SheetAdd == item.nActionType || AscCH.historyitem_Workbook_SheetRemove == item.nActionType || AscCH.historyitem_Workbook_SheetMove == item.nActionType) bChangeSheetPlace = true; } else if (AscCommonExcel.g_oUndoRedoWorksheet === item.oClass && AscCH.historyitem_Worksheet_Hide === item.nActionType) { bChangeSheetPlace = true; } this._SerializeHistoryBase64(oMemory, item, aRes); } var oUndoRedoData_SheetPositions; if (bChangeSheetPlace) { //создаем еще один элемент в undo/redo - взаимное расположение Sheet, чтобы не запутываться в add, move событиях //добавляем не после конца aActions, чтобы можно было делать undo/redo и просто удалять хвост изменений. var oSheetPlaceData = []; for (j = 0, length2 = this.aWorksheets.length; j < length2; ++j) oSheetPlaceData.push(this.aWorksheets[j].getId()); oUndoRedoData_SheetPositions = new UndoRedoData_SheetPositions(oSheetPlaceData); } else oUndoRedoData_SheetPositions = new UndoRedoData_SheetPositions(); this._SerializeHistoryBase64(oMemory, new UndoRedoItemSerializable(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetPositions, null, null, oUndoRedoData_SheetPositions), aRes); } this.aCollaborativeActions = []; } return aRes; }; Workbook.prototype.DeserializeHistory = function(aChanges, fCallback){ var oThis = this; //сохраняем те изменения, которые были до приема данных, потому что дальше undo/redo будет очищено this.aCollaborativeActions = this.aCollaborativeActions.concat(History.GetSerializeArray()); if(aChanges.length > 0) { this.bCollaborativeChanges = true; //собираем общую длину var dstLen = 0; var aIndexes = [], i, length = aChanges.length, sChange; for(i = 0; i < length; ++i) { sChange = aChanges[i]; var nIndex = sChange.indexOf(";"); if (-1 != nIndex) { dstLen += parseInt(sChange.substring(0, nIndex)); nIndex++; } aIndexes.push(nIndex); } var pointer = g_memory.Alloc(dstLen); var stream = new AscCommon.FT_Stream2(pointer.data, dstLen); stream.obj = pointer.obj; var nCurOffset = 0; //пробегаемся первый раз чтобы заполнить oFontMap var oFontMap = {};//собираем все шрифтры со всех изменений var aUndoRedoElems = []; for (i = 0; i < length; ++i) { sChange = aChanges[i]; var oBinaryFileReader = new AscCommonExcel.BinaryFileReader(); nCurOffset = oBinaryFileReader.getbase64DecodedData2(sChange, aIndexes[i], stream, nCurOffset); var item = new UndoRedoItemSerializable(); item.Deserialize(stream); if (AscCommonExcel.g_oUndoRedoWorkbook == item.oClass && AscCH.historyitem_Workbook_AddFont == item.nActionType) { for (var k = 0, length3 = item.oData.elem.length; k < length3; ++k) oFontMap[item.oData.elem[k]] = 1; } aUndoRedoElems.push(item); } window["Asc"]["editor"]._loadFonts(oFontMap, function(){ var wsViews = window["Asc"]["editor"].wb.wsViews; if(oThis.oApi.collaborativeEditing.getFast()){ AscCommon.CollaborativeEditing.Clear_DocumentPositions(); } for(var i in wsViews) { if(isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) && isRealObject(wsViews[i].objectRender.controller)) { if ( wsViews[i].isChartAreaEditMode ) { wsViews[i].isChartAreaEditMode = false; wsViews[i].arrActiveChartsRanges = []; } if(oThis.oApi.collaborativeEditing.getFast()){ var oState = wsViews[i].objectRender.saveStateBeforeLoadChanges(); if(oState){ if (oState.Pos) AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.Pos); if (oState.StartPos) AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.StartPos); if (oState.EndPos) AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.EndPos); } } wsViews[i].objectRender.controller.resetSelection(); } } oFormulaLocaleInfo.Parse = false; oFormulaLocaleInfo.DigitSep = false; History.Clear(); History.Create_NewPoint(); History.SetSelection(null); History.SetSelectionRedo(null); var oRedoObjectParam = new AscCommonExcel.RedoObjectParam(); History.UndoRedoPrepare(oRedoObjectParam, false); for (var i = 0, length = aUndoRedoElems.length; i < length; ++i) { var item = aUndoRedoElems[i]; if ((null != item.oClass || (item.oData && typeof item.oData.sChangedObjectId === "string")) && null != item.nActionType) { if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"]) { if (!window["native"]["CheckNextChange"]()) break; } // TODO if(g_oUndoRedoGraphicObjects == item.oClass && item.oData.drawingData) // item.oData.drawingData.bCollaborativeChanges = true; History.RedoAdd(oRedoObjectParam, item.oClass, item.nActionType, item.nSheetId, item.oRange, item.oData); } } if(oThis.oApi.collaborativeEditing.getFast()){ for(var i in wsViews){ if(isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) && isRealObject(wsViews[i].objectRender.controller)){ var oState = wsViews[i].objectRender.getStateBeforeLoadChanges(); if(oState){ if (oState.Pos) AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.Pos); if (oState.StartPos) AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.StartPos); if (oState.EndPos) AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.EndPos); } wsViews[i].objectRender.loadStateAfterLoadChanges(); } } } oFormulaLocaleInfo.Parse = true; oFormulaLocaleInfo.DigitSep = true; History.UndoRedoEnd(null, oRedoObjectParam, false); oThis.bCollaborativeChanges = false; History.Clear(); if(null != fCallback) fCallback(); }); } }; Workbook.prototype.DeserializeHistoryNative = function(oRedoObjectParam, data, isFull){ if(null != data) { this.bCollaborativeChanges = true; if(null == oRedoObjectParam) { var wsViews = window["Asc"]["editor"].wb.wsViews; for(var i in wsViews) { if(isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) && isRealObject(wsViews[i].objectRender.controller)) { if ( wsViews[i].isChartAreaEditMode ) { wsViews[i].isChartAreaEditMode = false; wsViews[i].arrActiveChartsRanges = []; } wsViews[i].objectRender.controller.resetSelection(); } } History.Clear(); History.Create_NewPoint(); History.SetSelection(null); History.SetSelectionRedo(null); oRedoObjectParam = new AscCommonExcel.RedoObjectParam(); History.UndoRedoPrepare(oRedoObjectParam, false); } var stream = new AscCommon.FT_Stream2(data, data.length); stream.obj = null; // Применяем изменения, пока они есть var _count = stream.GetLong(); var _pos = 4; for (var i = 0; i < _count; i++) { if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"]) { if (!window["native"]["CheckNextChange"]()) break; } var _len = stream.GetLong(); _pos += 4; stream.size = _pos + _len; stream.Seek(_pos); stream.Seek2(_pos); var item = new UndoRedoItemSerializable(); item.Deserialize(stream); if ((null != item.oClass || (item.oData && typeof item.oData.sChangedObjectId === "string")) && null != item.nActionType) History.RedoAdd(oRedoObjectParam, item.oClass, item.nActionType, item.nSheetId, item.oRange, item.oData); _pos += _len; stream.Seek2(_pos); stream.size = data.length; } if(isFull){ History.UndoRedoEnd(null, oRedoObjectParam, false); History.Clear(); oRedoObjectParam = null; } this.bCollaborativeChanges = false; } return oRedoObjectParam; }; Workbook.prototype.getTableRangeForFormula = function(name, objectParam){ var res = null; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var ws = this.aWorksheets[i]; res = ws.getTableRangeForFormula(name, objectParam); if(res !== null){ res = {wsID:ws.getId(),range:res}; break; } } return res; }; Workbook.prototype.getTableIndexColumnByName = function(tableName, columnName){ var res = null; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var ws = this.aWorksheets[i]; res = ws.getTableIndexColumnByName(tableName, columnName); if(res !== null){ res = {wsID:ws.getId(), index: res}; break; } } return res; }; Workbook.prototype.getTableNameColumnByIndex = function(tableName, columnIndex){ var res = null; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var ws = this.aWorksheets[i]; res = ws.getTableNameColumnByIndex(tableName, columnIndex); if(res !== null){ res = {wsID:ws.getId(), columnName: res}; break; } } return res; }; Workbook.prototype.updateSparklineCache = function(sheet, ranges) { for (var i = 0; i < this.aWorksheets.length; ++i) { this.aWorksheets[i].updateSparklineCache(sheet, ranges); } }; Workbook.prototype.lockDraw = function() { ++this.lockCounter; }; Workbook.prototype.unLockDraw = function() { if (0 < this.lockCounter) { --this.lockCounter; } }; Workbook.prototype.buildRecalc = function(notrec, bForce) { var ws; if (this.lockCounter > 0 && !bForce) { return; } if (!bForce) { for (var id in arrDefNameRecalc) { arrDefNameRecalc[id].rebuild(); } arrDefNameRecalc = {}; } for (var id in arrRecalc) { ws = this.getWorksheetById(id); if (ws) { var temp = arrRecalc[id]; var _rec = {}; for (var i = 0, length = temp.length; i < length; ++i) { var cell = temp[i]; var cellId = g_oCellAddressUtils.getCellId(cell.nRow, cell.nCol); _rec[cellId] = cellId; this.needRecalc.nodes[getVertexId(id, cellId)] = [id, cellId]; this.needRecalc.length++; } ws._BuildDependencies(_rec); } } arrRecalc = {}; if (!notrec) { this.sortDependency(); } }; Workbook.prototype.sortDependency = function(setCellFormat) { this.buildRecalc(true); var i; var nR = this.needRecalc; if (nR && (nR.length > 0)) { var oCleanCellCacheArea = {}; var oNodeDependence = this.dependencyFormulas.getNodeDependence(nR.nodes); for (i in oNodeDependence.oMasterNodes) this._sortDependency(oNodeDependence.oMasterNodes[i], oNodeDependence, oNodeDependence.oMasterAreaNodes, false, oCleanCellCacheArea, setCellFormat); //те AreaNodes var oCurMasterAreaNodes = oNodeDependence.oMasterAreaNodes; while (true) { var bEmpty = true; var oNewMasterAreaNodes = {}; for (i in oCurMasterAreaNodes) { bEmpty = false; this._sortDependency(oCurMasterAreaNodes[i], oNodeDependence, oNewMasterAreaNodes, false, oCleanCellCacheArea, setCellFormat); } oCurMasterAreaNodes = oNewMasterAreaNodes; if (bEmpty) { //все оставшиеся считаем как bad //todo сделать как в Excel, которой определяет циклические ссылки на момент подсчета(пример A1=VLOOKUP(1,B1:D2,2),B2 = 1, D1=A1 - это не циклическая ссылка) for (i in oNodeDependence.oMasterAreaNodesRestricted) { this._sortDependency(oNodeDependence.oMasterAreaNodesRestricted[i].node, oNodeDependence, null, true, oCleanCellCacheArea, setCellFormat); } break; } } for (i in oCleanCellCacheArea) this.handlers.trigger("cleanCellCache", i, oCleanCellCacheArea[i], AscCommonExcel.c_oAscCanChangeColWidth.numbers); AscCommonExcel.g_oVLOOKUPCache.clean(); AscCommonExcel.g_oHLOOKUPCache.clean(); } this.needRecalc = {nodes: {}, length: 0}; }; Workbook.prototype._sortDependency = function(node, oNodeDependence, oNewMasterAreaNodes, bBad, oCleanCellCacheArea, setCellFormat) { if (node) { var oWeightMapElem = oNodeDependence.oWeightMap[node.nodeId]; if (oWeightMapElem) { oWeightMapElem.cur++; if (oWeightMapElem.cur == oWeightMapElem.max && !oWeightMapElem.gray) { if (null != oNewMasterAreaNodes) { var oNodeToAreaElement = oNodeDependence.oNodeToArea[node.nodeId]; if (oNodeToAreaElement) { for (var i = 0, length = oNodeToAreaElement.length; i < length; ++i) { var elem = oNodeToAreaElement[i]; elem.cur++; if (elem.cur == elem.max) { oNewMasterAreaNodes[elem.node.nodeId] = elem.node; delete oNodeDependence.oMasterAreaNodesRestricted[elem.node.nodeId]; } } } } var bCurBad = oWeightMapElem.bad || bBad; if (node.isDefinedName) { //todo //Обрабатываем тут все, что было сделано с именованной ссылкой: переименована; //перемещен диапазон; сдвиг/удаление ячеек, приведшие к сдвигу ячеек; удаление именованного диапазона. // // var ws = this.getWorksheetById( node.sheetId ); // ws._ReBuildFormulas // ws._RecalculatedFunctions(node.cellId, bCurBad, setCellFormat); } else { //пересчитываем функцию var ws = this.getWorksheetById(node.sheetId); ws._RecalculatedFunctions(node.cellId, bCurBad, setCellFormat); //запоминаем области для удаления cache var sheetArea = oCleanCellCacheArea[node.sheetId]; if (null == sheetArea) { sheetArea = {}; oCleanCellCacheArea[node.sheetId] = sheetArea; } if (!node.isArea) { sheetArea[node.cellId] = node.getBBox(); } } //обрабатываем child oWeightMapElem.gray = true; var oSlaveNodes = node.getSlaveEdges(); if (oSlaveNodes) { for (var i in oSlaveNodes) this._sortDependency(oSlaveNodes[i], oNodeDependence, oNewMasterAreaNodes, bBad, oCleanCellCacheArea); } oWeightMapElem.gray = false; } } } }; //------------------------------------------------------------------------------------------------- /** * @constructor */ function Woorksheet(wb, _index, sId){ this.workbook = wb; this.DefinedNames = {}; this.sName = this.workbook.getUniqueSheetNameFrom(g_sNewSheetNamePattern, false); this.bHidden = false; this.oSheetFormatPr = new AscCommonExcel.SheetFormatPr(); this.index = _index; this.Id = null != sId ? sId : AscCommon.g_oIdCounter.Get_NewId(); this.nRowsCount = 0; this.nColsCount = 0; this.aGCells = {};// 0 based this.aCols = [];// 0 based this.Drawings = []; this.TableParts = []; this.AutoFilter = null; this.oAllCol = null; this.aComments = []; this.aCommentsCoords = []; var oThis = this; this.mergeManager = new RangeDataManager(function(data, from, to) { if (History.Is_On() && (null != from || null != to)) { if (null != from) { from = from.clone(); } if (null != to) to = to.clone(); var oHistoryRange = from; if (null == oHistoryRange) oHistoryRange = to; History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ChangeMerge, oThis.getId(), oHistoryRange, new UndoRedoData_FromTo(new UndoRedoData_BBox(from), new UndoRedoData_BBox(to))); } //расширяем границы if (null != to) { if (to.r2 >= oThis.nRowsCount) oThis.nRowsCount = to.r2 + 1; if (to.c2 >= oThis.nColsCount) oThis.nColsCount = to.c2 + 1; } }); this.hyperlinkManager = new RangeDataManager(function(data, from, to, oChangeParam) { if (History.Is_On() && (null != from || null != to)) { if (null != from) from = from.clone(); if (null != to) to = to.clone(); var oHistoryRange = from; if (null == oHistoryRange) oHistoryRange = to; var oHistoryData = null; if (null == from || null == to) oHistoryData = data.clone(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ChangeHyperlink, oThis.getId(), oHistoryRange, new AscCommonExcel.UndoRedoData_FromToHyperlink(from, to, oHistoryData)); } if (null != to) data.Ref = oThis.getRange3(to.r1, to.c1, to.r2, to.c2); else if (oChangeParam && oChangeParam.removeStyle && null != data.Ref) data.Ref.cleanFormat(); //расширяем границы if (null != to) { if (to.r2 >= oThis.nRowsCount) oThis.nRowsCount = to.r2 + 1; if (to.c2 >= oThis.nColsCount) oThis.nColsCount = to.c2 + 1; } }); this.hyperlinkManager.setDependenceManager(this.mergeManager); this.DrawingDocument = new AscCommon.CDrawingDocument(); this.sheetViews = []; this.aConditionalFormatting = []; this.sheetPr = null; this.aFormulaExt = null; this.autoFilters = AscCommonExcel.AutoFilters !== undefined ? new AscCommonExcel.AutoFilters(this) : null; this.sparklineGroups = new sparklineGroups(); this.oDrawingOjectsManager = new DrawingObjectsManager(this); this.contentChanges = new AscCommon.CContentChanges(); this.sparklineGroups = new AscCommonExcel.sparklineGroups(); /*handlers*/ this.handlers = null; } Woorksheet.prototype.addContentChanges = function(changes) { this.contentChanges.Add(changes); }; Woorksheet.prototype.refreshContentChanges = function() { this.contentChanges.Refresh(); this.contentChanges.Clear(); }; Woorksheet.prototype.rebuildColors=function(){ this._forEachCell(function(cell){ cell.cleanCache(); }); this.rebuildTabColor(); }; Woorksheet.prototype.generateFontMap=function(oFontMap){ //пробегаемся по Drawing for(var i = 0, length = this.Drawings.length; i < length; ++i) { var drawing = this.Drawings[i]; if(drawing) drawing.getAllFonts(oFontMap); } if(null != this.workbook.theme) AscFormat.checkThemeFonts(oFontMap, this.workbook.theme.themeElements.fontScheme); //пробегаемся по колонкам for(var i in this.aCols) { var col = this.aCols[i]; if(null != col && null != col.xfs && null != col.xfs.font && null != col.xfs.font.fn) oFontMap[col.xfs.font.fn] = 1; } if(null != this.oAllCol && null != this.oAllCol.xfs && null != this.oAllCol.xfs.font && null != this.oAllCol.xfs.font.fn) oFontMap[this.oAllCol.xfs.font.fn] = 1; //пробегаемся строкам for(var i in this.aGCells) { var row = this.aGCells[i]; if(null != row && null != row.xfs && null != row.xfs.font && null != row.xfs.font.fn) oFontMap[row.xfs.font.fn] = 1; //пробегаемся по ячейкам for(var j in row.c) { var cell = row.c[j]; if(null != cell) { if(null != cell.xfs && null != cell.xfs.font && null != cell.xfs.font.fn) oFontMap[cell.xfs.font.fn] = 1; //смотрим в комплексных строках if(null != cell.oValue && null != cell.oValue.multiText) { for(var k = 0, length3 = cell.oValue.multiText.length; k < length3; ++k) { var part = cell.oValue.multiText[k]; if(null != part.format && null != part.format.fn) oFontMap[part.format.fn] = 1; } } } } } }; Woorksheet.prototype.clone=function(sNewId, sName){ var i, elem, range; var oNewWs = new Woorksheet(this.workbook, this.workbook.aWorksheets.length, sNewId); oNewWs.sName = this.workbook.checkValidSheetName(sName) ? sName : this.workbook.getUniqueSheetNameFrom(this.sName, true); oNewWs.bHidden = this.bHidden; oNewWs.oSheetFormatPr = this.oSheetFormatPr.clone(); oNewWs.index = this.index; oNewWs.nRowsCount = this.nRowsCount; oNewWs.nColsCount = this.nColsCount; for (i = 0; i < this.TableParts.length; ++i) oNewWs.TableParts.push(this.TableParts[i].clone(oNewWs)); if(this.AutoFilter) oNewWs.AutoFilter = this.AutoFilter.clone(); for (i in this.aCols) { var col = this.aCols[i]; if(null != col) oNewWs.aCols[i] = col.clone(oNewWs); } if(null != this.oAllCol) oNewWs.oAllCol = this.oAllCol.clone(oNewWs); for(i in this.aGCells) oNewWs.aGCells[i] = this.aGCells[i].clone(oNewWs); var aMerged = this.mergeManager.getAll(); for(i in aMerged) { elem = aMerged[i]; range = oNewWs.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2); range.mergeOpen(); } var aHyperlinks = this.hyperlinkManager.getAll(); for(i in aHyperlinks) { elem = aHyperlinks[i]; range = oNewWs.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2); range.setHyperlinkOpen(elem.data); } if(null != this.aComments) { for (i = 0; i < this.aComments.length; i++) { var comment = new Asc.asc_CCommentData(this.aComments[i]); comment.wsId = oNewWs.getId(); comment.nId = "sheet" + comment.wsId + "_" + (i + 1); oNewWs.aComments.push(comment); } } for (i = 0; i < this.sheetViews.length; ++i) { oNewWs.sheetViews.push(this.sheetViews[i].clone()); } for (i = 0; i < this.aConditionalFormatting.length; ++i) { oNewWs.aConditionalFormatting.push(this.aConditionalFormatting[i].clone()); } if (this.sheetPr) oNewWs.sheetPr = this.sheetPr.clone(); return oNewWs; }; Woorksheet.prototype.copyDrawingObjects=function(oNewWs, wsFrom) { if(null != this.Drawings && this.Drawings.length > 0) { var drawingObjects = new AscFormat.DrawingObjects(); oNewWs.Drawings = []; AscFormat.NEW_WORKSHEET_DRAWING_DOCUMENT = oNewWs.DrawingDocument; for(var i = 0; i < this.Drawings.length; ++i) { var drawingObject = drawingObjects.cloneDrawingObject(this.Drawings[i]); drawingObject.graphicObject = this.Drawings[i].graphicObject.copy(); drawingObject.graphicObject.setWorksheet(oNewWs); drawingObject.graphicObject.addToDrawingObjects(); var drawingBase = this.Drawings[i]; drawingObject.graphicObject.setDrawingBaseCoords(drawingBase.from.col, drawingBase.from.colOff, drawingBase.from.row, drawingBase.from.rowOff, drawingBase.to.col, drawingBase.to.colOff, drawingBase.to.row, drawingBase.to.rowOff, drawingBase.Pos.X, drawingBase.Pos.Y, drawingBase.ext.cx, drawingBase.ext.cy); oNewWs.Drawings[oNewWs.Drawings.length - 1] = drawingObject; } AscFormat.NEW_WORKSHEET_DRAWING_DOCUMENT = null; drawingObjects.pushToAObjects(oNewWs.Drawings); drawingObjects.updateChartReferences2(parserHelp.getEscapeSheetName(wsFrom.sName), parserHelp.getEscapeSheetName(oNewWs.sName)); } }; Woorksheet.prototype.initPostOpen = function(handlers){ this.workbook.cwf[this.Id]={ cells:{} }; if(this.aFormulaExt){ var formulaShared = {}; for(var i = 0; i < this.aFormulaExt.length; ++i){ var elem = this.aFormulaExt[i]; var oCell = elem.cell; var sCellId = g_oCellAddressUtils.getCellId(oCell.nRow, oCell.nCol); var oFormulaExt = elem.ext; if (oFormulaExt.t == Asc.ECellFormulaType.cellformulatypeShared) { if(null != oFormulaExt.si){ if(null != oFormulaExt.ref){ if (oFormulaExt.v.length <= AscCommon.c_oAscMaxFormulaLength) { formulaShared[oFormulaExt.si] = { fVal: new parserFormula(oFormulaExt.v, "", this), fRef: function(t) { var r = t.getRange2(oFormulaExt.ref); return { c: r, first: r.first }; }(this) }; formulaShared[oFormulaExt.si].fVal.parse(); } } else{ if( formulaShared[oFormulaExt.si] ){ var fr = formulaShared[oFormulaExt.si].fRef; if( fr.c.containCell2(oCell) ){ if( formulaShared[oFormulaExt.si].fVal.isParsed ){ var off = oCell.getOffset3(fr.first); formulaShared[oFormulaExt.si].fVal.changeOffset(off); oFormulaExt.v = formulaShared[oFormulaExt.si].fVal.assemble(); off.offsetCol *=-1; off.offsetRow *=-1; formulaShared[oFormulaExt.si].fVal.changeOffset(off); } this.workbook.cwf[this.Id].cells[sCellId] = sCellId; } } } } } if(oFormulaExt.v) { if (oFormulaExt.v.length <= AscCommon.c_oAscMaxFormulaLength) { oCell.setFormula(oFormulaExt.v); if(oFormulaExt.ca) { oCell.sFormulaCA = true; } } else { this.workbook.openErrors.push(oCell.getName()); } } /* Если ячейка содержит в себе формулу, то добавляем ее в список ячеек с формулами. */ if(oCell.sFormula){ this.workbook.cwf[this.Id].cells[sCellId] = sCellId; } /* Строится список ячеек, которые необходимо пересчитать при открытии. Это ячейки имеющие атрибут f.ca или значение в которых неопределено. */ if(oCell.sFormula && (oFormulaExt.ca || !oCell.oValue.getValueWithoutFormat()) ){ this.workbook.needRecalc.nodes[ getVertexId( this.Id, sCellId ) ] = [this.Id, sCellId]; this.workbook.needRecalc.length++; } } this.aFormulaExt = null; } if (!this.PagePrintOptions) { // Даже если не было, создадим this.PagePrintOptions = new Asc.asc_CPageOptions(); } this.PagePrintOptions.init(); // Sheet Views if (0 === this.sheetViews.length) { // Даже если не было, создадим this.sheetViews.push(new AscCommonExcel.asc_CSheetViewSettings()); } if (window['IS_NATIVE_EDITOR']) { for (var j = this.sheetViews.length - 1; j >= 0; --j) { this.sheetViews[j].pane = null; } } this._updateConditionalFormatting(null); this.handlers = handlers; this._setHandlersTablePart(); }; Woorksheet.prototype._getValuesForConditionalFormatting = function(sqref) { var aValues = [], aCells = []; var tmp; this.getRange3(sqref.r1, sqref.c1, sqref.r2, sqref.c2)._setPropertyNoEmpty(null, null, function(c) { if (!c.isEmptyTextString()) { aCells.push(c); aValues.push(c.getValueWithoutFormat()); } }); return {c: aCells, v: aValues}; }; Woorksheet.prototype._updateConditionalFormatting = function(range) { var oGradient = null; var aCFs = this.aConditionalFormatting; var aRules, oRule; var oRuleElement = null; var o; var i, j, cell, sqref, values, tmp, min, max, dxf, condition; for (i = 0; i < aCFs.length; ++i) { sqref = aCFs[i].sqref; // ToDo убрать null === sqref когда научимся мультиселект обрабатывать (\\192.168.5.2\source\DOCUMENTS\XLSX\Matematika Quantum Sedekah.xlsx) if (null === sqref) { continue; } if (!range || range.isIntersect(sqref)) { aRules = aCFs[i].aRules; for (j = 0; j < aRules.length; ++j) { oRule = aRules[j]; // ToDo aboveAverage, beginsWith, cellIs, containsBlanks, containsErrors, // ToDo containsText, dataBar, duplicateValues, endsWith, expression, iconSet, notContainsBlanks, // ToDo notContainsErrors, notContainsText, timePeriod, top10, uniqueValues (page 2679) switch (oRule.type) { case Asc.ECfType.colorScale: if (1 !== oRule.aRuleElements.length) { break; } oRuleElement = oRule.aRuleElements[0]; if (!(oRuleElement instanceof AscCommonExcel.CColorScale)) { break; } min = Number.MAX_VALUE; max = -Number.MAX_VALUE; values = this._getValuesForConditionalFormatting(sqref); for (cell = 0; cell < values.v.length; ++cell) { if (CellValueType.Number === values.c[cell].getType() && !isNaN(tmp = parseFloat(values.v[cell]))) { values.v[cell] = tmp; min = Math.min(min, tmp); max = Math.max(max, tmp); } else { values.v[cell] = null; } } // ToDo CFVO Type (formula, max, min, num, percent, percentile) (page 2681) // ToDo support 3 colors in rule if (0 < values.c.length && 2 === oRuleElement.aColors.length) { oGradient = new AscCommonExcel.CGradient(oRuleElement.aColors[0], oRuleElement.aColors[1]); oGradient.init(min, max); for (cell = 0; cell < values.c.length; ++cell) { dxf = null; if (null !== values.v[cell]) { dxf = new AscCommonExcel.CellXfs(); dxf.fill = new AscCommonExcel.Fill({bg: oGradient.calculateColor(values.v[cell])}); } values.c[cell].setConditionalFormattingStyle(dxf); } } break; case Asc.ECfType.duplicateValues: case Asc.ECfType.uniqueValues: if (oRule.dxf) { condition = oRule.type === Asc.ECfType.uniqueValues; values = this._getValuesForConditionalFormatting(sqref); o = getUniqueKeys(values.v); for (cell = 0; cell < values.c.length; ++cell) { values.c[cell].setConditionalFormattingStyle((condition === o[values.v[cell]]) ? null : oRule.dxf); } } break; } } } } }; Woorksheet.prototype._forEachCell=function(fAction){ for(var rowInd in this.aGCells){ var row = this.aGCells[rowInd]; if(row){ for(var cellInd in row.c){ var cell = row.c[cellInd]; if(cell){ fAction(cell); } } } } }; Woorksheet.prototype.getId=function(){ return this.Id; }; Woorksheet.prototype.getIndex=function(){ return this.index; }; Woorksheet.prototype.getName=function(){ return this.sName !== undefined && this.sName.length > 0 ? this.sName : ""; }; Woorksheet.prototype.setName=function(name, bFromUndoRedo){ if(name.length <= g_nSheetNameMaxLength) { var lastName = this.sName; this.sName = name; History.Create_NewPoint(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Rename, this.getId(), null, new UndoRedoData_FromTo(lastName, name)); //перестраиваем формулы, если у них были ссылки на лист со старым именем. for(var id in this.workbook.cwf) { this.workbook.getWorksheetById(id)._ReBuildFormulas(this.workbook.cwf[id].cells,lastName,this.sName); } this.workbook.dependencyFormulas.relinkDefNameByWorksheet(lastName, name); if(!bFromUndoRedo) { var _lastName = parserHelp.getEscapeSheetName(lastName); var _newName = parserHelp.getEscapeSheetName(this.sName); for (var key in this.workbook.aWorksheets) { var wsModel = this.workbook.aWorksheets[key]; if ( wsModel ) wsModel.oDrawingOjectsManager.updateChartReferencesWidthHistory(_lastName, _newName, true); } } } }; Woorksheet.prototype.getTabColor=function(){ return this.sheetPr && this.sheetPr.TabColor ? Asc.colorObjToAscColor(this.sheetPr.TabColor) : null; }; Woorksheet.prototype.setTabColor=function(color){ if (!this.sheetPr) this.sheetPr = new AscCommonExcel.asc_CSheetPr(); History.Create_NewPoint(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_SetTabColor, this.getId(), null, new UndoRedoData_FromTo(this.sheetPr.TabColor ? this.sheetPr.TabColor.clone() : null, color ? color.clone() : null)); this.sheetPr.TabColor = color; if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges) this.workbook.handlers.trigger("asc_onUpdateTabColor", this.getIndex()); }; Woorksheet.prototype.rebuildTabColor = function() { if (this.sheetPr && this.sheetPr.TabColor) { this.workbook.handlers.trigger("asc_onUpdateTabColor", this.getIndex()); } }; Woorksheet.prototype.renameWsToCollaborate=function(name){ var lastname = this.getName(); //из-за особенностей реализации формул, сначала делаем parse со старым именем, потом преименовываем, потом assemble var aFormulas = []; //переименование для отправки изменений for(var i = 0, length = this.workbook.aCollaborativeActions.length; i < length; ++i) { var aPointActions = this.workbook.aCollaborativeActions[i]; for (var j = 0, length2 = aPointActions.length; j < length2; ++j) { var action = aPointActions[j]; if (AscCommonExcel.g_oUndoRedoWorkbook == action.oClass) { if (AscCH.historyitem_Workbook_SheetAdd == action.nActionType) { if (lastname == action.oData.name) action.oData.name = name; } } else if (AscCommonExcel.g_oUndoRedoWorksheet == action.oClass) { if (AscCH.historyitem_Worksheet_Rename == action.nActionType) { if (lastname == action.oData.to) action.oData.to = name; } } else if (AscCommonExcel.g_oUndoRedoCell == action.oClass) { if (action.oData instanceof UndoRedoData_CellSimpleData) { if (action.oData.oNewVal instanceof UndoRedoData_CellValueData) { var oNewVal = action.oData.oNewVal; if (null != oNewVal.formula && -1 != oNewVal.formula.indexOf(lastname)) { var oParser = new parserFormula(oNewVal.formula, "A1", this); oParser.parse(); aFormulas.push({ formula: oParser, value: oNewVal }); } } } } } } //переименование для локальной версии this.setName(name); for(var i = 0, length = aFormulas.length; i < length; ++i) { var item = aFormulas[i]; item.value.formula = item.formula.assemble(); } }; Woorksheet.prototype.getHidden=function(){ if(null != this.bHidden) return false != this.bHidden; return false; }; Woorksheet.prototype.setHidden = function (hidden) { var bOldHidden = this.bHidden, wb = this.workbook, wsActive = wb.getActiveWs(), oVisibleWs = null; this.bHidden = hidden; if (true == this.bHidden && this.getIndex() == wsActive.getIndex()) { oVisibleWs = wb.findSheetNoHidden(this.getIndex()); if (null != oVisibleWs) { var nNewIndex = oVisibleWs.getIndex(); wb.setActive(nNewIndex); if (!wb.bUndoChanges && !wb.bRedoChanges) wb.handlers.trigger("undoRedoHideSheet", nNewIndex); } } if (bOldHidden != hidden) { History.Create_NewPoint(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Hide, this.getId(), null, new UndoRedoData_FromTo(bOldHidden, hidden)); if (null != oVisibleWs) { History.SetSheetUndo(wsActive.getId()); History.SetSheetRedo(oVisibleWs.getId()); } } }; Woorksheet.prototype.getSheetViewSettings = function () { return this.sheetViews[0].clone(); }; Woorksheet.prototype.setSheetViewSettings = function (options) { var current = this.getSheetViewSettings(); if (current.isEqual(options)) return; History.Create_NewPoint(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_SetViewSettings, this.getId(), null, new UndoRedoData_FromTo(current, options.clone())); this.sheetViews[0].setSettings(options); if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges) this.workbook.handlers.trigger("asc_onUpdateSheetViewSettings"); }; Woorksheet.prototype.getRowsCount=function(){ var result = this.nRowsCount; var pane = this.sheetViews[0].pane; if (null !== pane && null !== pane.topLeftFrozenCell) result = Math.max(result, pane.topLeftFrozenCell.getRow0()); return result; }; Woorksheet.prototype.removeRows=function(start, stop){ var oRange = this.getRange(new CellAddress(start, 0, 0), new CellAddress(stop, gc_nMaxCol0, 0)); oRange.deleteCellsShiftUp(); }; Woorksheet.prototype._removeRows=function(start, stop){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.lockDraw(); History.Create_NewPoint(); //start, stop 0 based var nDif = -(stop - start + 1); var oActualRange = {r1: start, c1: 0, r2: stop, c2: gc_nMaxCol0}; this.renameDependencyNodes({offsetRow:nDif,offsetCol:0}, oActualRange); var i, j, length, nIndex, aIndexes = []; for(i in this.aGCells) { nIndex = i - 0; if(nIndex >= start) aIndexes.push(nIndex); } //По возрастанию aIndexes.sort(fSortAscending); var oDefRowPr = new AscCommonExcel.UndoRedoData_RowProp(); for(i = 0, length = aIndexes.length; i < length; ++i) { nIndex = aIndexes[i]; var row = this.aGCells[nIndex]; if(nIndex > stop) { if(false == row.isEmpty()) { var oTargetRow = this._getRow(nIndex + nDif); oTargetRow.copyProperty(row); } for(j in row.c) this._moveCellVer(nIndex, j - 0, nDif); } else { var oOldProps = row.getHeightProp(); if (false === oOldProps.isEqual(oDefRowPr)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, this.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(nIndex, true, oOldProps, oDefRowPr)); row.setStyle(null); for(j in row.c) { var nColIndex = j - 0; //удаляем ячейку this._removeCell(nIndex, nColIndex); } } delete this.aGCells[nIndex]; } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveRows, this.getId(), new Asc.Range(0, start, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, start, stop)); this.autoFilters.insertRows( "delCell", new Asc.Range(0, start, gc_nMaxCol0, stop), c_oAscDeleteOptions.DeleteRows ); this.workbook.unLockDraw(); this.workbook.buildRecalc(); return true; }; Woorksheet.prototype.insertRowsBefore=function(index, count){ var oRange = this.getRange(new CellAddress(index, 0, 0), new CellAddress(index + count - 1, gc_nMaxCol0, 0)); oRange.addCellsShiftBottom(); }; Woorksheet.prototype._insertRowsBefore=function(index, count){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.lockDraw(); var oActualRange = {r1: index, c1: 0, r2: index + count - 1, c2: gc_nMaxCol0}; History.Create_NewPoint(); this.renameDependencyNodes({offsetRow:count,offsetCol:0},oActualRange); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_AddRows, this.getId(), new Asc.Range(0, index, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, index, index + count - 1)); //index 0 based var aIndexes = []; for(var i in this.aGCells) { var nIndex = i - 0; if(nIndex >= index) aIndexes.push(nIndex); } var oPrevRow = null; if(index > 0) oPrevRow = this.aGCells[index - 1]; //По убыванию aIndexes.sort(fSortDescending); for(var i = 0, length = aIndexes.length; i < length; ++i) { var nIndex = aIndexes[i]; var row = this.aGCells[nIndex]; if(false == row.isEmpty()) { var oTargetRow = this._getRow(nIndex + count); oTargetRow.copyProperty(row); } for(var j in row.c) this._moveCellVer(nIndex, j - 0, count); delete this.aGCells[nIndex]; } if (null != oPrevRow && false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges)) { History.LocalChange = true; for(var i = 0; i < count; ++i) { var row = this._getRow(index + i); row.copyProperty(oPrevRow); row.flags &= ~AscCommonExcel.g_nRowFlag_hd; } History.LocalChange = false; } this.autoFilters.insertRows( "insCell", new Asc.Range(0, index, gc_nMaxCol0, index + count - 1), c_oAscInsertOptions.InsertColumns ); this.workbook.unLockDraw(); this.workbook.buildRecalc(); this.nRowsCount += count; return true; }; Woorksheet.prototype.insertRowsAfter=function(index, count){ //index 0 based return this.insertRowsBefore(index + 1, count); }; Woorksheet.prototype.getColsCount=function(){ var result = this.nColsCount; var pane = this.sheetViews[0].pane; if (null !== pane && null !== pane.topLeftFrozenCell) result = Math.max(result, pane.topLeftFrozenCell.getCol0()); return result; }; Woorksheet.prototype.removeCols=function(start, stop){ var oRange = this.getRange(new CellAddress(0, start, 0), new CellAddress(gc_nMaxRow0, stop, 0)); oRange.deleteCellsShiftLeft(); }; Woorksheet.prototype._removeCols=function(start, stop){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.lockDraw(); History.Create_NewPoint(); //start, stop 0 based var nDif = -(stop - start + 1), i, j, length, nIndex; var oActualRange = { r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop }; this.renameDependencyNodes({ offsetRow: 0, offsetCol: nDif }, oActualRange); for(i in this.aGCells) { var nRowIndex = i - 0; var row = this.aGCells[i]; var aIndexes = []; for(j in row.c) { nIndex = j - 0; if(nIndex >= start) aIndexes.push(nIndex); } //сортируем по возрастанию aIndexes.sort(fSortAscending); for(j = 0, length = aIndexes.length; j < length; ++j) { nIndex = aIndexes[j]; if(nIndex > stop) { this._moveCellHor(nRowIndex, nIndex, nDif, {r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop}); } else { //удаляем ячейку this._removeCell(nRowIndex, nIndex); } } } var oDefColPr = new AscCommonExcel.UndoRedoData_ColProp(); for(i = start; i <= stop; ++i) { var col = this.aCols[i]; if(null != col) { var oOldProps = col.getWidthProp(); if(false === oOldProps.isEqual(oDefColPr)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, this.getId(), new Asc.Range(i, 0, i, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(i, false, oOldProps, oDefColPr)); col.setStyle(null); } } this.aCols.splice(start, stop - start + 1); for(i = start, length = this.aCols.length; i < length; ++i) { var elem = this.aCols[i]; if(null != elem) elem.moveHor(nDif); } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveCols, this.getId(), new Asc.Range(start, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, start, stop)); this.autoFilters.insertColumn( "delCell", new Asc.Range(start, 0, stop, gc_nMaxRow0), c_oAscInsertOptions.InsertColumns ); this.workbook.unLockDraw(); this.workbook.buildRecalc(); return true; }; Woorksheet.prototype.insertColsBefore=function(index, count){ var oRange = this.getRange3(0, index, gc_nMaxRow0, index + count - 1); oRange.addCellsShiftRight(); }; Woorksheet.prototype._insertColsBefore=function(index, count){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.lockDraw(); var oActualRange = {r1: 0, c1: index, r2: gc_nMaxRow0, c2: index + count - 1}; History.Create_NewPoint(); this.renameDependencyNodes({offsetRow:0,offsetCol:count},oActualRange); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_AddCols, this.getId(), new Asc.Range(index, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, index, index + count - 1)); //index 0 based for(var i in this.aGCells) { var nRowIndex = i - 0; var row = this.aGCells[i]; var aIndexes = []; for(var j in row.c) { var nIndex = j - 0; if(nIndex >= index) aIndexes.push(nIndex); } //сортируем по убыванию aIndexes.sort(fSortDescending); for(var j = 0, length2 = aIndexes.length; j < length2; ++j) { var nIndex = aIndexes[j]; this._moveCellHor(nRowIndex, nIndex, count, oActualRange); } } this.autoFilters.insertColumn( "insCells", new Asc.Range(index, 0, index + count - 1, gc_nMaxRow0), c_oAscInsertOptions.InsertColumns ); this.workbook.unLockDraw(); this.workbook.buildRecalc(); var oPrevCol = null; if(index > 0) oPrevCol = this.aCols[index - 1]; if(null == oPrevCol && null != this.oAllCol) oPrevCol = this.oAllCol; for(var i = 0; i < count; ++i) { var oNewCol = null; if (null != oPrevCol && false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges)) { History.LocalChange = true; oNewCol = oPrevCol.clone(); oNewCol.hd = null; oNewCol.BestFit = null; oNewCol.index = index + i; History.LocalChange = false; } this.aCols.splice(index, 0, oNewCol); } for(var i = index + count, length = this.aCols.length; i < length; ++i) { var elem = this.aCols[i]; if(null != elem) elem.moveHor(count); } this.nColsCount += count; return true; }; Woorksheet.prototype.insertColsAfter=function(index, count){ //index 0 based return this.insertColsBefore(index + 1, count); }; Woorksheet.prototype.getDefaultWidth=function(){ return this.oSheetFormatPr.dDefaultColWidth; }; Woorksheet.prototype.getDefaultFontName=function(){ return this.workbook.getDefaultFont(); }; Woorksheet.prototype.getDefaultFontSize=function(){ return this.workbook.getDefaultSize(); }; Woorksheet.prototype.getColWidth=function(index){ //index 0 based //Результат в пунктах var col = this._getColNoEmptyWithAll(index); if(null != col && null != col.width) return col.width; var dResult = this.oSheetFormatPr.dDefaultColWidth; if(dResult === undefined || dResult === null || dResult == 0) //dResult = (8) + 5;//(EMCA-376.page 1857.)defaultColWidth = baseColumnWidth + {margin padding (2 pixels on each side, totalling 4 pixels)} + {gridline (1pixel)} dResult = -1; // calc default width at presentation level return dResult; }; Woorksheet.prototype.setColWidth=function(width, start, stop){ if(0 == width) return this.setColHidden(true, start, stop); //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(start, 0, stop, gc_nMaxRow0); oSelection.type = Asc.c_oAscSelectionType.RangeCol; History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } var oThis = this; var fProcessCol = function(col){ if(col.width != width) { var oOldProps = col.getWidthProp(); col.width = width; col.CustomWidth = true; col.BestFit = null; col.hd = null; var oNewProps = col.getWidthProp(); if(false == oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(), col._getUpdateRange(), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps)); } }; if(0 == start && gc_nMaxCol0 == stop) { var col = this.getAllCol(); fProcessCol(col); for(var i in this.aCols){ var col = this.aCols[i]; if (null != col) fProcessCol(col); } } else { for(var i = start; i <= stop; i++){ var col = this._getCol(i); fProcessCol(col); } } }; Woorksheet.prototype.getColHidden=function(index){ var col = this._getColNoEmptyWithAll(index); return col ? col.hd : false; }; Woorksheet.prototype.setColHidden=function(bHidden, start, stop){ //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this; var fProcessCol = function(col){ if(col.hd != bHidden) { var oOldProps = col.getWidthProp(); if(bHidden) { col.hd = bHidden; if(null == col.width || true != col.CustomWidth) col.width = 0; col.CustomWidth = true; col.BestFit = null; } else { col.hd = null; if(0 == col.width) col.width = null; } var oNewProps = col.getWidthProp(); if(false == oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(), col._getUpdateRange(), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps)); } }; if(0 != start && gc_nMaxCol0 == stop) { var col = null; if(false == bHidden) col = this.oAllCol; else col = this.getAllCol(); if(null != col) fProcessCol(col); for(var i in this.aCols){ var col = this.aCols[i]; if (null != col) fProcessCol(col); } } else { for(var i = start; i <= stop; i++){ var col = null; if(false == bHidden) col = this._getColNoEmpty(i); else col = this._getCol(i); if(null != col) fProcessCol(col); } } }; Woorksheet.prototype.setColBestFit=function(bBestFit, width, start, stop){ //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this; var fProcessCol = function(col){ var oOldProps = col.getWidthProp(); if(bBestFit) { col.BestFit = bBestFit; col.hd = null; } else col.BestFit = null; col.width = width; var oNewProps = col.getWidthProp(); if(false == oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(), col._getUpdateRange(), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps)); }; if(0 != start && gc_nMaxCol0 == stop) { var col = null; if(bBestFit && oDefaultMetrics.ColWidthChars == width) col = this.oAllCol; else col = this.getAllCol(); if(null != col) fProcessCol(col); for(var i in this.aCols){ var col = this.aCols[i]; if (null != col) fProcessCol(col); } } else { for(var i = start; i <= stop; i++){ var col = null; if(bBestFit && oDefaultMetrics.ColWidthChars == width) col = this._getColNoEmpty(i); else col = this._getCol(i); if(null != col) fProcessCol(col); } } }; Woorksheet.prototype.isDefaultHeightHidden=function(){ return null != this.oSheetFormatPr.oAllRow && 0 != (AscCommonExcel.g_nRowFlag_hd & this.oSheetFormatPr.oAllRow.flags); }; Woorksheet.prototype.isDefaultWidthHidden=function(){ return null != this.oAllCol && this.oAllCol.hd; }; Woorksheet.prototype.getDefaultHeight=function(){ // ToDo http://bugzserver/show_bug.cgi?id=19666 (флага CustomHeight нет) var dRes = null; // Нужно возвращать выставленную, только если флаг CustomHeight = true if(null != this.oSheetFormatPr.oAllRow && 0 != (AscCommonExcel.g_nRowFlag_CustomHeight & this.oSheetFormatPr.oAllRow.flags)) dRes = this.oSheetFormatPr.oAllRow.h; return dRes; }; Woorksheet.prototype.getRowHeight=function(index){ //index 0 based var row = this.aGCells[index]; if(null != row && null != row.h) return row.h; else return -1; }; Woorksheet.prototype.setRowHeight=function(height, start, stop, isCustom){ if(0 == height) return this.setRowHidden(true, start, stop); //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this, i; var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(0, start, gc_nMaxCol0, stop); oSelection.type = Asc.c_oAscSelectionType.RangeRow; History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } var fProcessRow = function(row){ if(row) { var oOldProps = row.getHeightProp(); row.h = height; if (isCustom) { row.flags |= AscCommonExcel.g_nRowFlag_CustomHeight; } row.flags &= ~AscCommonExcel.g_nRowFlag_hd; var oNewProps = row.getHeightProp(); if(false === oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, oThis.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(row.index, true, oOldProps, oNewProps)); } }; if(0 == start && gc_nMaxRow0 == stop) { fProcessRow(this.getAllRow()); for(i in this.aGCells){ fProcessRow(this.aGCells[i]); } } else { for(i = start; i <= stop; ++i){ fProcessRow(this._getRow(i)); } } }; Woorksheet.prototype.getRowHidden=function(index){ var row = this._getRowNoEmptyWithAll(index); return row ? 0 != (AscCommonExcel.g_nRowFlag_hd & row.flags) : false; }; Woorksheet.prototype.setRowHidden=function(bHidden, start, stop){ //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this, i; var startIndex = null, endIndex = null, updateRange; var fProcessRow = function(row){ if(row && bHidden != (0 != (AscCommonExcel.g_nRowFlag_hd & row.flags))) { if(bHidden) row.flags |= AscCommonExcel.g_nRowFlag_hd; else row.flags &= ~AscCommonExcel.g_nRowFlag_hd; if(row.index === endIndex + 1 && startIndex !== null) endIndex++; else { if(startIndex !== null) { updateRange = new Asc.Range(0, startIndex, gc_nMaxCol0, endIndex); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowHide, oThis.getId(), updateRange, new UndoRedoData_FromToRowCol(bHidden, startIndex, endIndex)); } startIndex = row.index; endIndex = row.index; } } }; if(0 == start && gc_nMaxRow0 == stop) { // ToDo реализовать скрытие всех строк! } else { for(i = start; i <= stop; ++i) fProcessRow(false == bHidden ? this._getRowNoEmpty(i) : this._getRow(i)); if(startIndex !== null)//заносим последние строки { updateRange = new Asc.Range(0, startIndex, gc_nMaxCol0, endIndex); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowHide, oThis.getId(),updateRange, new UndoRedoData_FromToRowCol(bHidden, startIndex, endIndex)); } } }; Woorksheet.prototype.setRowBestFit=function(bBestFit, height, start, stop){ //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this, i; var isDefaultProp = (true == bBestFit && oDefaultMetrics.RowHeight == height); var fProcessRow = function(row){ if(row) { var oOldProps = row.getHeightProp(); if(true == bBestFit) row.flags &= ~AscCommonExcel.g_nRowFlag_CustomHeight; else row.flags |= AscCommonExcel.g_nRowFlag_CustomHeight; row.h = height; var oNewProps = row.getHeightProp(); if(false == oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, oThis.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(row.index, true, oOldProps, oNewProps)); } }; if(0 == start && gc_nMaxRow0 == stop) { fProcessRow(isDefaultProp ? this.oSheetFormatPr.oAllRow : this.getAllRow()); for(i in this.aGCells) fProcessRow(this.aGCells[i]); } for(i = start; i <= stop; ++i) fProcessRow(isDefaultProp ? this._getRowNoEmpty(i) : this._getRow(i)); }; Woorksheet.prototype.getCell=function(oCellAdd){ return this.getRange(oCellAdd, oCellAdd); }; Woorksheet.prototype.getCell2=function(sCellAdd){ if( sCellAdd.indexOf("$") > -1) sCellAdd = sCellAdd.replace(/\$/g,""); return this.getRange2(sCellAdd); }; Woorksheet.prototype.getCell3=function(r1, c1){ return this.getRange3(r1, c1, r1, c1); }; Woorksheet.prototype.getRange=function(cellAdd1, cellAdd2){ //Если range находится за границами ячеек расширяем их var nRow1 = cellAdd1.getRow0(); var nCol1 = cellAdd1.getCol0(); var nRow2 = cellAdd2.getRow0(); var nCol2 = cellAdd2.getCol0(); return this.getRange3(nRow1, nCol1, nRow2, nCol2); }; Woorksheet.prototype.getRange2=function(sRange){ var bbox = AscCommonExcel.g_oRangeCache.getAscRange(sRange); if(null != bbox) return Range.prototype.createFromBBox(this, bbox); return null; }; Woorksheet.prototype.getRange3=function(r1, c1, r2, c2){ var nRowMin = r1; var nRowMax = r2; var nColMin = c1; var nColMax = c2; if(r1 > r2){ nRowMax = r1; nRowMin = r2; } if(c1 > c2){ nColMax = c1; nColMin = c2; } return new Range(this, nRowMin, nColMin, nRowMax, nColMax); }; Woorksheet.prototype._getRows=function(){ return this.aGCells; }; Woorksheet.prototype._getCols=function(){ return this.aCols; }; Woorksheet.prototype._removeCell=function(nRow, nCol, cell){ if(null != cell) { nRow = cell.nRow; nCol = cell.nCol; } var row = this.aGCells[nRow]; if(null != row) { var cell = row.c[nCol]; if(null != cell) { var sheetId = this.getId(); var cellId = cell.getName(); if(cell.formulaParsed) this.workbook.dependencyFormulas.deleteMasterNodes2(sheetId, cellId); this.workbook.needRecalc.nodes[getVertexId(sheetId, cellId)] = [sheetId, cellId]; this.workbook.needRecalc.length++; if (null != cell.getConditionalFormattingStyle() || null != cell.getTableStyle()) { cell.setValue(""); cell.setStyle(null); } else { if (false == cell.isEmpty()) { var oUndoRedoData_CellData = new AscCommonExcel.UndoRedoData_CellData(cell.getValueData(), null); if (null != cell.xfs) oUndoRedoData_CellData.style = cell.xfs.clone(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveCell, sheetId, new Asc.Range(nCol, nRow, nCol, nRow), new UndoRedoData_CellSimpleData(nRow, nCol, oUndoRedoData_CellData, null)); } delete row.c[nCol]; if (row.isEmpty()) delete this.aGCells[nRow]; } } } }; Woorksheet.prototype._getCell=function(row, col){ //0-based var oCurRow = this._getRow(row); var oCurCell = oCurRow.c[col]; if(null == oCurCell){ oCurCell = new Cell(this); var oRow = this._getRowNoEmpty(row); var oCol = this._getColNoEmptyWithAll(col); var xfs = null; if(null != oRow && null != oRow.xfs) xfs = oRow.xfs.clone(); else if(null != oCol && null != oCol.xfs) xfs = oCol.xfs.clone(); oCurCell.create(xfs, row, col); oCurRow.c[col] = oCurCell; if(row >= this.nRowsCount) this.nRowsCount = row + 1; if(col >= this.nColsCount) this.nColsCount = col + 1; //History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateCell, this.getId(), null, new UndoRedoData_CellSimpleData(row, col, null, null)); } return oCurCell; }; Woorksheet.prototype._getCellNoEmpty=function(row, col){ //0-based var oCurRow = this.aGCells[row]; if(oCurRow) { var cell = oCurRow.c[col]; return cell ? cell : null; } return null; }; Woorksheet.prototype._getRowNoEmpty=function(row){ //0-based var oCurRow = this.aGCells[row]; if(oCurRow) return oCurRow; return null; }; Woorksheet.prototype._getRowNoEmptyWithAll=function(row){ var oRes = this._getRowNoEmpty(row); if(null == oRes) oRes = this.oSheetFormatPr.oAllRow; return oRes; }; Woorksheet.prototype._getColNoEmpty=function(col){ //0-based var oCurCol = this.aCols[col]; if(oCurCol) return oCurCol; return null; }; Woorksheet.prototype._getColNoEmptyWithAll=function(col){ var oRes = this._getColNoEmpty(col); if(null == oRes) oRes = this.oAllCol; return oRes; }; Woorksheet.prototype._getRow=function(row){ //0-based var oCurRow = null; if (g_nAllRowIndex == row) oCurRow = this.getAllRow(); else { oCurRow = this.aGCells[row]; if (!oCurRow) { if (null != this.oSheetFormatPr.oAllRow) oCurRow = this.oSheetFormatPr.oAllRow.clone(this); else oCurRow = new AscCommonExcel.Row(this); oCurRow.create(row + 1); this.aGCells[row] = oCurRow; this.nRowsCount = row >= this.nRowsCount ? row + 1 : this.nRowsCount; //History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateRow, this.getId(), null, new UndoRedoData_SingleProperty(row)); } } return oCurRow; }; Woorksheet.prototype._removeRow=function(index){ delete this.aGCells[index]; }; Woorksheet.prototype._getCol=function(index){ //0-based var oCurCol; if (g_nAllColIndex == index) oCurCol = this.getAllCol(); else { oCurCol = this.aCols[index]; if(null == oCurCol) { if(null != this.oAllCol) { oCurCol = this.oAllCol.clone(); oCurCol.index = index; } else oCurCol = new AscCommonExcel.Col(this, index); this.aCols[index] = oCurCol; this.nColsCount = index >= this.nColsCount ? index + 1 : this.nColsCount; //History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateCol, this.getId(), null, new UndoRedoData_SingleProperty(index)); } } return oCurCol; }; Woorksheet.prototype._removeCol=function(index){ //0-based delete this.aCols[index]; }; Woorksheet.prototype._moveCellHor=function(nRow, nCol, dif){ var cell = this._getCellNoEmpty(nRow, nCol); if(cell) { cell.moveHor(dif); var row = this._getRow(nRow); row.c[nCol + dif] = cell; delete row.c[nCol]; } }; Woorksheet.prototype._moveCellVer=function(nRow, nCol, dif){ var cell = this._getCellNoEmpty(nRow, nCol); if(cell) { cell.moveVer(dif); var oCurRow = this._getRow(nRow); var oTargetRow = this._getRow(nRow + dif); delete oCurRow.c[nCol]; oTargetRow.c[nCol] = cell; if(oCurRow.isEmpty()) delete this.aGCells[nRow]; } }; Woorksheet.prototype._prepareMoveRangeGetCleanRanges=function(oBBoxFrom, oBBoxTo){ var intersection = oBBoxFrom.intersectionSimple(oBBoxTo); var aRangesToCheck = []; if(null != intersection) { var oThis = this; var fAddToRangesToCheck = function(aRangesToCheck, r1, c1, r2, c2) { if(r1 <= r2 && c1 <= c2) aRangesToCheck.push(oThis.getRange3(r1, c1, r2, c2)); }; if(intersection.r1 == oBBoxTo.r1 && intersection.c1 == oBBoxTo.c1) { fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, intersection.c2 + 1, intersection.r2, oBBoxTo.c2); fAddToRangesToCheck(aRangesToCheck, intersection.r2 + 1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2); } else if(intersection.r2 == oBBoxTo.r2 && intersection.c1 == oBBoxTo.c1) { fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r1 - 1, oBBoxTo.c2); fAddToRangesToCheck(aRangesToCheck, intersection.r1, intersection.c2 + 1, oBBoxTo.r2, oBBoxTo.c2); } else if(intersection.r1 == oBBoxTo.r1 && intersection.c2 == oBBoxTo.c2) { fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r2, intersection.c1 - 1); fAddToRangesToCheck(aRangesToCheck, intersection.r2 + 1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2); } else if(intersection.r2 == oBBoxTo.r2 && intersection.c2 == oBBoxTo.c2) { fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r1 - 1, oBBoxTo.c2); fAddToRangesToCheck(aRangesToCheck, intersection.r1, oBBoxTo.c1, oBBoxTo.r2, intersection.c1 - 1); } } else aRangesToCheck.push(this.getRange3(oBBoxTo.r1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2)); return aRangesToCheck; }; Woorksheet.prototype._prepareMoveRange=function(oBBoxFrom, oBBoxTo){ var res = 0; if(oBBoxFrom.isEqual(oBBoxTo)) return res; var range = this.getRange3(oBBoxTo.r1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2); var aMerged = this.mergeManager.get(range.getBBox0()); if(aMerged.outer.length > 0) return -2; var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo); for(var i = 0, length = aRangesToCheck.length; i < length; i++) { range = aRangesToCheck[i]; range._foreachNoEmpty( function(cell){ if(!cell.isEmptyTextString()) { res = -1; return res; } }); if(0 != res) return res; } return res; }; Woorksheet.prototype._moveRange=function(oBBoxFrom, oBBoxTo, copyRange){ if(oBBoxFrom.isEqual(oBBoxTo)) return; var oThis = this; History.Create_NewPoint(); History.StartTransaction(); var offset = { offsetRow : oBBoxTo.r1 - oBBoxFrom.r1, offsetCol : oBBoxTo.c1 - oBBoxFrom.c1 }; var intersection = oBBoxFrom.intersectionSimple(oBBoxTo); var oRangeIntersection = null; if(null != intersection) oRangeIntersection = this.getRange3(intersection.r1, intersection.c1, intersection.r2, intersection.c2 ); //запоминаем то что нужно переместить var aTempObj = {cells: {}, merged: null, hyperlinks: null}; for(var i = oBBoxFrom.r1; i <= oBBoxFrom.r2; i++) { var row = this._getRowNoEmpty(i); if(null != row) { var oTempRow = {}; aTempObj.cells[i + offset.offsetRow] = oTempRow; for(var j = oBBoxFrom.c1; j <= oBBoxFrom.c2; j++) { var cell = row.c[j]; if(null != cell){ if(copyRange) oTempRow[j + offset.offsetCol] = cell.clone(); else oTempRow[j + offset.offsetCol] = cell; } } } } if(false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges)) { History.LocalChange = true; var aMerged = this.mergeManager.get(oBBoxFrom); if(aMerged.inner.length > 0) aTempObj.merged = aMerged.inner; var aHyperlinks = this.hyperlinkManager.get(oBBoxFrom); if(aHyperlinks.inner.length > 0) aTempObj.hyperlinks = aHyperlinks.inner; var aMergedToRemove = null; if(!copyRange){ aMergedToRemove = aTempObj.merged; } else if(null != intersection){ var aMergedIntersection = this.mergeManager.get(intersection); if(aMergedIntersection.all.length > 0) aMergedToRemove = aMergedIntersection.all; } if(null != aMergedToRemove){ for(var i = 0, length = aMergedToRemove.length; i < length; i++) { var elem = aMergedToRemove[i]; this.mergeManager.removeElement(elem); } } if(!copyRange){ if(null != aTempObj.hyperlinks) { for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++) { var elem = aTempObj.hyperlinks[i]; this.hyperlinkManager.removeElement(elem); } } } History.LocalChange = false; } //удаляем to через историю, для undo var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo); for (var i = 0, length = aRangesToCheck.length; i < length; i++) { var range = aRangesToCheck[i]; range.cleanAll(); //выставляем для slave refError if (!copyRange) this.workbook.dependencyFormulas.deleteNodes(this.getId(), range.getBBox0()); } //удаляем from без истории, потому что эти данные не терются а перемещаются if(!copyRange || (copyRange && this.workbook.bUndoChanges)){ var oRangeFrom = this.getRange3(oBBoxFrom.r1, oBBoxFrom.c1, oBBoxFrom.r2, oBBoxFrom.c2 ); oRangeFrom._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){ var row = oThis._getRowNoEmpty(nRow0); if(null != row) delete row.c[nCol0]; }); } else{ //в случае копирования удаляем пересечение, чтобы затирались значения, если мы копируем пустые ячейки(все что не входит в пересечение удалилось выше через историю) if(null != intersection){ oRangeIntersection._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){ var row = oThis._getRowNoEmpty(nRow0); if(null != row) delete row.c[nCol0]; }); } } if(!copyRange){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.dependencyFormulas.helper(oBBoxFrom, oBBoxTo,this.Id); } for ( var i in aTempObj.cells ) { var oTempRow = aTempObj.cells[i]; var row = this._getRow( i - 0 ); for ( var j in oTempRow ) { var oTempCell = oTempRow[j]; if ( null != oTempCell ) { oTempCell.moveHor( offset.offsetCol ); oTempCell.moveVer( offset.offsetRow ); row.c[j] = oTempCell; if ( oTempCell.sFormula ) { if(copyRange){ oTempCell.formulaParsed = new parserFormula( oTempCell.sFormula, g_oCellAddressUtils.getCellId(oTempCell.nRow, oTempCell.nCol), this ); oTempCell.formulaParsed.parse(); oTempCell.formulaParsed = oTempCell.formulaParsed.changeOffset(offset); oTempCell.sFormula = oTempCell.formulaParsed.assemble(); addToArrRecalc(this.getId(), oTempCell); } } } } } if(false == this.workbook.bUndoChanges && false == this.workbook.bRedoChanges) this.autoFilters._moveAutoFilters( oBBoxTo, oBBoxFrom, null, copyRange, true, oBBoxFrom ); if(false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges)) { History.LocalChange = true; if(null != aTempObj.merged) { for(var i = 0, length = aTempObj.merged.length; i < length; i++) { var elem = aTempObj.merged[i]; var oNewBBox; var oNewData = elem.data; if(copyRange) oNewBBox = elem.bbox.clone(); else oNewBBox = elem.bbox; oNewBBox.setOffset(offset); this.mergeManager.add(oNewBBox, oNewData); } } //todo сделать для пересечения if(null != aTempObj.hyperlinks && (!copyRange || null == intersection)) { for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++) { var elem = aTempObj.hyperlinks[i]; var oNewBBox; var oNewData; if(copyRange){ oNewBBox = elem.bbox.clone(); oNewData = elem.data.clone(); } else{ oNewBBox = elem.bbox; oNewData = elem.data; } oNewBBox.setOffset(offset); this.hyperlinkManager.add(oNewBBox, oNewData); } } History.LocalChange = false; } //расширяем границы if(oBBoxFrom.r2 >= this.nRowsCount) this.nRowsCount = oBBoxFrom.r2 + 1; if(oBBoxFrom.c2 >= this.nColsCount) this.nColsCount = oBBoxFrom.c2 + 1; if(oBBoxTo.r2 >= this.nRowsCount) this.nRowsCount = oBBoxTo.r2 + 1; if(oBBoxTo.c2 >= this.nColsCount) this.nColsCount = oBBoxTo.c2 + 1; if(!copyRange){ var sBBoxFromName = oBBoxFrom.getName(); this.workbook.needRecalc.nodes[getVertexId(this.getId(), sBBoxFromName)] = [this.getId(), sBBoxFromName]; this.workbook.needRecalc.length++; } var sBBoxToName = oBBoxTo.getName(); this.workbook.needRecalc.nodes[getVertexId(this.getId(), sBBoxToName)] = [this.getId(), sBBoxToName]; this.workbook.needRecalc.length++; if (!this.workbook.lockCounter){ /* Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!". */ this.workbook.sortDependency(); } if(true == this.workbook.bUndoChanges || true == this.workbook.bRedoChanges) { this.autoFilters.unmergeTablesAfterMove( oBBoxTo ); } // ToDo возможно нужно уменьшить диапазон обновления History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_MoveRange, this.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromTo(new UndoRedoData_BBox(oBBoxFrom), new UndoRedoData_BBox(oBBoxTo), copyRange)); History.EndTransaction(); return true; }; Woorksheet.prototype._shiftCellsLeft=function(oBBox){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); //todo удаление когда есть замерженые ячейки var nLeft = oBBox.c1; var nRight = oBBox.c2; var dif = nLeft - nRight - 1; this.renameDependencyNodes( {offsetRow:0,offsetCol:dif}, oBBox ); for(var i = oBBox.r1; i <= oBBox.r2; i++){ var row = this.aGCells[i]; if(row){ var aIndexes = []; for(var cellInd in row.c) { var nIndex = cellInd - 0; if(nIndex >= nLeft) aIndexes.push(nIndex); } //По возрастанию aIndexes.sort(fSortAscending); for(var j = 0, length2 = aIndexes.length; j < length2; ++j){ var nCellInd = aIndexes[j]; if(nCellInd <= nRight){ //Удаляем ячейки this._removeCell(i, nCellInd); } else{ //Сдвигаем ячейки this._moveCellHor(i, nCellInd, dif, oBBox); } } } } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsLeft, this.getId(), new Asc.Range(nLeft, oBBox.r1, gc_nMaxCol0, oBBox.r2), new UndoRedoData_BBox(oBBox)); this.autoFilters.insertColumn( "delCell", oBBox, c_oAscDeleteOptions.DeleteCellsAndShiftLeft ); //todo проверить не уменьшились ли границы таблицы }; Woorksheet.prototype._shiftCellsUp=function(oBBox){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); var nTop = oBBox.r1; var nBottom = oBBox.r2; var dif = nTop - nBottom - 1; this.renameDependencyNodes({offsetRow:dif,offsetCol:0}, oBBox ); var aIndexes = []; for(var i in this.aGCells) { var rowInd = i - 0; if(rowInd >= nTop) aIndexes.push(rowInd); } //по возрастанию aIndexes.sort(fSortAscending); for(var i = 0, length = aIndexes.length; i < length; ++i){ var rowInd = aIndexes[i]; var row = this.aGCells[rowInd]; if(row){ if(rowInd <= nBottom){ //Удаляем ячейки for(var j = oBBox.c1; j <= oBBox.c2; j++){ this._removeCell(rowInd, j); } } else{ var nIndex = rowInd + dif; var rowTop = this._getRow(nIndex); //Сдвигаем ячейки for(var j = oBBox.c1; j <= oBBox.c2; j++){ this._moveCellVer(rowInd, j, dif); } } } } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsTop, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, gc_nMaxRow0), new UndoRedoData_BBox(oBBox)); this.autoFilters.insertRows( "delCell", oBBox, c_oAscDeleteOptions.DeleteCellsAndShiftTop ); //todo проверить не уменьшились ли границы таблицы }; Woorksheet.prototype._shiftCellsRight=function(oBBox, displayNameFormatTable){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); var nLeft = oBBox.c1; var nRight = oBBox.c2; var dif = nRight - nLeft + 1; this.renameDependencyNodes({offsetRow:0,offsetCol:dif}, oBBox); for(var i = oBBox.r1; i <= oBBox.r2; i++){ var row = this.aGCells[i]; if(row){ var aIndexes = []; for(var cellInd in row.c) { var nIndex = cellInd - 0; if(nIndex >= nLeft) aIndexes.push(nIndex); } //по убыванию aIndexes.sort(fSortDescending); for(var j = 0, length2 = aIndexes.length; j < length2; ++j){ var nCellInd = aIndexes[j]; //Сдвигаем ячейки var cell = row.c[nCellInd]; if(cell){ if(nCellInd + dif > this.nColsCount) this.nColsCount = nCellInd + dif; this._moveCellHor(/*row*/i, /*col*/nCellInd, dif, oBBox); } } } } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsRight, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, gc_nMaxCol0, oBBox.r2), new UndoRedoData_BBox(oBBox)); this.autoFilters.insertColumn( "insCells", oBBox, c_oAscInsertOptions.InsertCellsAndShiftRight, displayNameFormatTable ); }; Woorksheet.prototype._shiftCellsBottom=function(oBBox, displayNameFormatTable){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); var nTop = oBBox.r1; var nBottom = oBBox.r2; var dif = nBottom - nTop + 1; var aIndexes = []; this.renameDependencyNodes({offsetRow:dif,offsetCol:0}, oBBox); for(var i in this.aGCells){ var rowInd = i - 0; if(rowInd >= nTop) aIndexes.push(rowInd); } //по убыванию aIndexes.sort(fSortDescending); for(var i = 0, length = aIndexes.length; i < length; ++i){ rowInd = aIndexes[i]; var row = this.aGCells[rowInd]; if(row){ var nIndex = rowInd + dif; if(nIndex + dif > this.nRowsCount) this.nRowsCount = nIndex + dif; var rowTop = this._getRow(nIndex); //Сдвигаем ячейки for(var j = oBBox.c1; j <= oBBox.c2; j++){ this._moveCellVer(rowInd, j, dif); } } } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsBottom, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, gc_nMaxRow0), new UndoRedoData_BBox(oBBox)); this.autoFilters.insertRows( "insCell", oBBox, c_oAscInsertOptions.InsertCellsAndShiftDown, displayNameFormatTable ); }; Woorksheet.prototype._setIndex=function(ind){ this.index = ind; }; Woorksheet.prototype._BuildDependencies=function(cellRange){ /* Построение графа зависимостей. */ var c, ca, oLengthCache = {}; for(var i in cellRange){ ca = g_oCellAddressUtils.getCellAddress(i); c = this._getCellNoEmpty(ca.getRow0(),ca.getCol0()); if( c && c.sFormula ){ var elem = oLengthCache[c.sFormula.length]; if(null == elem) { elem = []; oLengthCache[c.sFormula.length] = elem; } elem.push(c); } } for(var i in oLengthCache) { var temp = oLengthCache[i]; var aCache = []; for(var j = 0, length2 = temp.length; j < length2; j++) { var c = temp[j], cellId = g_oCellAddressUtils.getCellId(c.nRow, c.nCol ), aRefs = [], cache = inCache(aCache, c.sFormula, aRefs ), bInCache = false; if(cache) { bInCache = true; var oNewFormula = cache.formulaParsed.clone(c.sFormula, cellId, this); var RefPos = cache.formulaParsed.RefPos; for(var k = 0, length3 = RefPos.length; k < length3; k++) { var pos = RefPos[k]; var elem = oNewFormula.outStack[pos.index]; if(elem) { //todo случай ,если ref число или именованный диапазон var ref = aRefs[k]; var range = AscCommonExcel.g_oRangeCache.getAscRange(ref); if(null != range) { var oNewElem; if(range.isOneCell()) { if(elem instanceof cRef3D) oNewElem = new cRef3D(ref, elem.ws.getName(), elem._wb); else if(elem instanceof cArea3D) { var wsFrom = elem._wb.getWorksheetById( elem.wsFrom ).getName(); var wsTo = elem._wb.getWorksheetById( elem.wsTo ).getName(); oNewElem = new cArea3D(ref, wsFrom, wsTo, elem._wb); } else if(-1 != ref.indexOf(":"))//случай "A1:A1" oNewElem = new AscCommonExcel.cArea(ref, elem.ws); else oNewElem = new AscCommonExcel.cRef(ref, elem.ws); } else { if(elem instanceof cRef3D) oNewElem = new cArea3D(ref, elem.ws.getName(), elem.ws.getName(), elem._wb); else if(elem instanceof cArea3D) { var wsFrom = elem._wb.getWorksheetById( elem.wsFrom ).getName(); var wsTo = elem._wb.getWorksheetById( elem.wsTo ).getName(); oNewElem = new cArea3D(ref, wsFrom, wsTo, elem._wb); } else oNewElem = new AscCommonExcel.cArea(ref, elem.ws); } if ( ref.indexOf( "$" ) > -1 ) oNewElem.isAbsolute = true; // ToDo - пересмотреть этот параметр (есть в Range информация о абсолютной ссылке) oNewFormula.outStack[pos.index] = oNewElem; } else bInCache = false; } } if(bInCache) { c.formulaParsed = oNewFormula; c.formulaParsed.buildDependencies(); } } if(!bInCache) { c.formulaParsed = new parserFormula( c.sFormula, cellId, this ); c.formulaParsed.parse(); c.formulaParsed.buildDependencies(); //error не добавляем в кеш у них не распознались RefPos, их бессмысленно сравнивать.Это только добавит торозов if(0 == c.formulaParsed.error.length) aCache.push(c); } } } }; Woorksheet.prototype._setHandlersTablePart = function(){ if(!this.TableParts) return; for(var i = 0; i < this.TableParts.length; i++) { this.TableParts[i].setHandlers(this.handlers); } }; Woorksheet.prototype.getTableRangeForFormula = function(name, objectParam){ var res = null; if(!this.TableParts) return res; for(var i = 0; i < this.TableParts.length; i++) { if(this.TableParts[i].DisplayName === name) { res = this.TableParts[i].getTableRangeForFormula(objectParam); break; } } return res; }; Woorksheet.prototype.getTableIndexColumnByName = function(tableName, columnName){ var res = null; if(!this.TableParts) return res; for(var i = 0; i < this.TableParts.length; i++) { if(this.TableParts[i].DisplayName === tableName) { res = this.TableParts[i].getTableIndexColumnByName(columnName); break; } } return res; }; Woorksheet.prototype.getTableNameColumnByIndex = function(tableName, columnIndex){ var res = null; if(!this.TableParts) return res; for(var i = 0; i < this.TableParts.length; i++) { if(this.TableParts[i].DisplayName === tableName) { res = this.TableParts[i].getTableNameColumnByIndex(columnIndex); break; } } return res; }; function inCache(aCache, sFormula, aRefs) { var oRes = null; for(var i = 0, length = aCache.length; i < length; i++) { var cache = aCache[i]; var sCurFormula = cache.sFormula; if(null != cache.formulaParsed){ var RefPos = cache.formulaParsed.RefPos; //todo свое сравнение для error if(0 == cache.formulaParsed.error.length && inCacheStrcmp(sCurFormula, sFormula, RefPos, aRefs)){ oRes = cache; break; } } } return oRes; } function inCacheStrcmp(str1, str2, RefPos, aRefs) { var bRes = true; var nStartIndex = 0; for(var i = 0, length = RefPos.length; i < length; i++) { var mask = RefPos[i]; for(var j = nStartIndex; j < mask.start; j++) { if(str1[j] != str2[j]) { bRes = false; break; } } nStartIndex = mask.end; } if(bRes) { for(var i = nStartIndex; i < str1.length; i++) { if(str1[i] != str2[i]) { bRes = false; break; } } } if(bRes) { for(var i = 0, length = RefPos.length; i < length; i++) { var mask = RefPos[i]; aRefs.push(str2.substring(mask.start, mask.end)); } } return bRes; } Woorksheet.prototype._RecalculatedFunctions=function(cell,bad,setCellFormat){ function adjustCellFormat( c ) { // ищет в формуле первый рэндж и устанавливает формат ячейки как формат первой ячейки в рэндже var elem = null; if ( c.formulaParsed && c.formulaParsed.outStack ) { for ( var i = 0, length = c.formulaParsed.outStack.length; i < length; i++ ) { elem = c.formulaParsed.outStack[i]; if ( elem instanceof AscCommonExcel.cRef || elem instanceof cRef3D || elem instanceof AscCommonExcel.cArea || elem instanceof cArea3D ) { var r = elem.getRange(); if ( elem instanceof cArea3D && r.length > 0 ) r = r[0]; if ( r && r.getNumFormatStr ) { var sCurFormat = c.getNumFormatStr(); if ( g_oDefaultFormat.Num.getFormat() == sCurFormat ) { var sNewFormat = r.getNumFormatStr(); if ( sCurFormat != sNewFormat ) c.setNumFormat( sNewFormat ); } } break; } } } } if( cell.indexOf(":")>-1 ) return; var celladd = this.getRange2(cell).getFirst(), __cell = this._getCellNoEmpty( celladd.getRow0(),celladd.getCol0() ), res; if( !__cell || !__cell.sFormula ) return; /* bad - флаг, показывающий, что ячейка находится в списке плохих ячеек (имеются циклические ссылки на ячейку), после сортировки графа зависимостей. */ if(!bad){ res = __cell.formulaParsed.calculate(); } else { res = new AscCommonExcel.cError( AscCommonExcel.cErrorType.bad_reference ) } if(res){ if( res.type == cElementType.cell){ var nF = res.numFormat; res = res.getValue(); res.numFormat = nF; } else if( res.type == cElementType.array ){ var nF = res.numFormat; res = res.getElement(0); res.numFormat = nF; } else if( res.type == cElementType.cellsRange || res.type == cElementType.cellsRange3D ){ var nF = res.numFormat; res = res.cross( new CellAddress(cell), this.Id ); // res = res.getElementByCell(new CellAddress(cell)); res.numFormat = nF; } __cell.oValue.clean(); switch (res.type){ case cElementType.number: __cell.oValue.type = CellValueType.Number; __cell.oValue.number = res.getValue(); break; case cElementType.bool: __cell.oValue.type = CellValueType.Bool; __cell.oValue.number = res.value ? 1 : 0; break; case cElementType.error: __cell.oValue.type = CellValueType.Error; __cell.oValue.text = res.getValue().toString(); break; case cElementType.name: __cell.oValue.type = CellValueType.Error; __cell.oValue.text = res.getValue().toString(); break; default: __cell.oValue.type = CellValueType.String; __cell.oValue.text = res.getValue().toString(); } AscCommonExcel.g_oVLOOKUPCache.remove(__cell); AscCommonExcel.g_oHLOOKUPCache.remove(__cell); __cell.setFormulaCA(res.ca); if(setCellFormat){ if( res.numFormat !== undefined && res.numFormat >= 0){ if( aStandartNumFormatsId[__cell.getNumFormatStr()] == 0 ) __cell.setNumFormat(aStandartNumFormats[res.numFormat]) } else if( res.numFormat !== undefined && res.numFormat == -1 ){ adjustCellFormat(__cell,__cell.sFormula); } } } }; Woorksheet.prototype._ReBuildFormulas=function(cellRange){ /* Если существуют трехмерные ссылки на ячейки, то у них необходимо поменять имя листа на новое после переименования листа. */ var c, ca; for(var i in cellRange){ ca = new CellAddress(i); c = this._getCellNoEmpty(ca.getRow0(),ca.getCol0()); if( c && c.formulaParsed && c.formulaParsed.is3D ){ c.setFormula(c.formulaParsed.assemble()); } } }; Woorksheet.prototype.renameDependencyNodes = function(offset, oBBox, rec, noDelete){ this.workbook.dependencyFormulas.checkOffset(oBBox, offset, this.Id, noDelete); }; Woorksheet.prototype.getAllCol = function(){ if(null == this.oAllCol) this.oAllCol = new AscCommonExcel.Col(this, g_nAllColIndex); return this.oAllCol; }; Woorksheet.prototype.getAllRow = function(){ if (null == this.oSheetFormatPr.oAllRow) { this.oSheetFormatPr.oAllRow = new AscCommonExcel.Row(this); this.oSheetFormatPr.oAllRow.create(g_nAllRowIndex + 1); } return this.oSheetFormatPr.oAllRow; }; Woorksheet.prototype.getHyperlinkByCell = function(row, col){ var oHyperlink = this.hyperlinkManager.getByCell(row, col); return oHyperlink ? oHyperlink.data : null; }; Woorksheet.prototype.getMergedByCell = function(row, col){ var oMergeInfo = this.mergeManager.getByCell(row, col); return oMergeInfo ? oMergeInfo.bbox : null; }; Woorksheet.prototype.getMergedByRange = function(bbox){ return this.mergeManager.get(bbox); }; Woorksheet.prototype._expandRangeByMergedAddToOuter = function(aOuter, range, aMerged){ for(var i = 0, length = aMerged.all.length; i < length; i++) { var elem = aMerged.all[i]; if(!range.containsRange(elem.bbox)) aOuter.push(elem); } }; Woorksheet.prototype._expandRangeByMergedGetOuter = function(range){ var aOuter = []; //смотрим только границы this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c1, r2: range.r2, c2: range.c1})); if(range.c1 != range.c2) { this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c2, r2: range.r2, c2: range.c2})); if(range.c2 - range.c1 > 1) { this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c1 + 1, r2: range.r1, c2: range.c2 - 1})); if(range.r1 != range.r2) this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r2, c1: range.c1 + 1, r2: range.r2, c2: range.c2 - 1})); } } return aOuter; }; Woorksheet.prototype.expandRangeByMerged = function(range){ if(null != range) { var aOuter = this._expandRangeByMergedGetOuter(range); if(aOuter.length > 0) { range = range.clone(); while(aOuter.length > 0) { for(var i = 0, length = aOuter.length; i < length; i++) range.union2(aOuter[i].bbox); aOuter = this._expandRangeByMergedGetOuter(range); } } } return range; }; Woorksheet.prototype.createTablePart = function(){ return new AscCommonExcel.TablePart(this.handlers); }; Woorksheet.prototype.onUpdateRanges = function(ranges) { this.workbook.updateSparklineCache(this.sName, ranges); this._updateConditionalFormatting(new AscCommonExcel.MultiplyRange(ranges)); }; Woorksheet.prototype.updateSparklineCache = function(sheet, ranges) { for (var i = 0; i < this.sparklineGroups.arrSparklineGroup.length; ++i) { this.sparklineGroups.arrSparklineGroup[i].updateCache(sheet, ranges); } }; //------------------------------------------------------------------------------------------------- /** * @constructor */ function Cell(worksheet){ this.ws = worksheet; this.oValue = new AscCommonExcel.CCellValue(); this.xfs = null; this.tableXfs = null; this.conditionalFormattingXfs = null; this.compiledXfs = null; this.nRow = -1; this.nCol = -1; this.sFormula = null; this.sFormulaCA = null; this.formulaParsed = null; } Cell.prototype.getStyle=function(){ return this.xfs; }; Cell.prototype.getCompiledStyle = function () { if (null == this.compiledXfs && (null != this.xfs || null != this.tableXfs || null != this.conditionalFormattingXfs)) { this.compileXfs(); } return this.compiledXfs; }; Cell.prototype.compileXfs=function(){ this.compiledXfs = null; if(null != this.xfs || null != this.tableXfs || null != this.conditionalFormattingXfs) { if(null != this.tableXfs) this.compiledXfs = this.tableXfs; if(null != this.xfs) { if(null != this.compiledXfs) this.compiledXfs = this.xfs.merge(this.compiledXfs); else this.compiledXfs = this.xfs; } if(null != this.conditionalFormattingXfs) { if(null != this.compiledXfs) this.compiledXfs = this.conditionalFormattingXfs.merge(this.compiledXfs); else this.compiledXfs = this.xfs; } } }; Cell.prototype.clone=function(oNewWs){ if(!oNewWs) oNewWs = this.ws; var oNewCell = new Cell(oNewWs); oNewCell.nRow = this.nRow; oNewCell.nCol = this.nCol; if(null != this.xfs) oNewCell.xfs = this.xfs.clone(); oNewCell.oValue = this.oValue.clone(); if(null != this.sFormula) oNewCell.sFormula = this.sFormula; return oNewCell; }; Cell.prototype.create=function(xfs, nRow, nCol){ this.xfs = xfs; this.nRow = nRow; this.nCol = nCol; }; Cell.prototype.isEmptyText=function(){ if(false == this.oValue.isEmpty()) return false; if(null != this.sFormula) return false; return true; }; Cell.prototype.isEmptyTextString=function(){ return this.oValue.isEmpty(); }; Cell.prototype.isEmpty=function(){ if(false == this.isEmptyText()) return false; if(null != this.xfs) return false; return true; }; Cell.prototype.isFormula=function(){ return this.sFormula ? true : false; }; Cell.prototype.Remove=function(){ this.ws._removeCell(null, null, this); }; Cell.prototype.getName=function(){ return g_oCellAddressUtils.getCellId(this.nRow, this.nCol); }; Cell.prototype.cleanCache=function(){ this.oValue.cleanCache(); }; Cell.prototype.setFormula=function(val, bAddToHistory){ if(bAddToHistory) { History.Add( AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveCellFormula, this.ws.getId(), new Asc.Range( this.nCol, this.nRow, this.nCol, this.nRow ), new UndoRedoData_CellSimpleData( this.nRow, this.nCol, null, null, this.sFormula )); } this.sFormula = val; this.oValue.cleanCache(); }; Cell.prototype.setValue=function(val,callback, isCopyPaste){ var ret = true; var DataOld = null; if(History.Is_On()) DataOld = this.getValueData(); var bIsTextFormat = false; if(!isCopyPaste){ var sNumFormat; if(null != this.xfs && null != this.xfs.num) sNumFormat = this.xfs.num.getFormat(); else sNumFormat = g_oDefaultFormat.Num.getFormat(); var numFormat = oNumFormatCache.get(sNumFormat); bIsTextFormat = numFormat.isTextFormat(); } var wb = this.ws.workbook; var ws = this.ws; if(false == bIsTextFormat) { /* Устанавливаем значение в Range ячеек. При этом происходит проверка значения на формулу. Если значение является формулой, то проверяем содержиться ли в ячейке формула или нет, если "да" - то очищаем в графе зависимостей список, от которых зависит формула(masterNodes), позже будет построен новый. Затем выставляем флаг о необходимости дальнейшего пересчета, и заносим ячейку в список пересчитываемых ячеек. */ if( null != val && val[0] == "=" && val.length > 1){ var oldFP = undefined; if( this.formulaParsed ) oldFP = this.formulaParsed; var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol); this.formulaParsed = new parserFormula(val.substring(1),cellId,this.ws); var formulaLocaleParse = isCopyPaste === true ? false : oFormulaLocaleInfo.Parse; var formulaLocaleDigetSep = isCopyPaste === true ? false : oFormulaLocaleInfo.DigitSep; if( !this.formulaParsed.parse( formulaLocaleParse, formulaLocaleDigetSep ) ){ switch( this.formulaParsed.error[this.formulaParsed.error.length-1] ){ case c_oAscError.ID.FrmlWrongFunctionName: break; case c_oAscError.ID.FrmlParenthesesCorrectCount: this.setValue("="+this.formulaParsed.Formula, callback, isCopyPaste); return; default :{ wb.handlers.trigger("asc_onError",this.formulaParsed.error[this.formulaParsed.error.length-1], c_oAscError.Level.NoCritical); if( callback ) callback(false); if( oldFP !== undefined ){ this.formulaParsed = oldFP; } return; } } } else{ val = "="+this.formulaParsed.assemble(); } } else{ this.formulaParsed = null; } } //удаляем старые значения this.oValue.clean(); var sheetId = this.ws.getId(); var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol); if (this.sFormula) wb.dependencyFormulas.deleteMasterNodes2( ws.Id, cellId ); if( !(null != val && val[0] != "=" || true == bIsTextFormat)) addToArrRecalc(this.ws.getId(), this); wb.needRecalc.nodes[getVertexId(sheetId,cellId)] = [sheetId, cellId]; wb.needRecalc.length++; this.sFormula = null; this.setFormulaCA(false); if(val){ if(false == bIsTextFormat && val[0] == "=" && val.length > 1){ this.setFormula( val.substring(1) ); } else { this.oValue.setValue(this, val); this.formulaParsed = null; } } var DataNew = null; if(History.Is_On()) DataNew = this.getValueData(); if(History.Is_On() && false == DataOld.isEqual(DataNew)) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew)); if (!this.ws.workbook.lockCounter) { /* Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!". */ //sortDependency вызывается ниже History.Add(AscCH.historyitem_Cell_ChangeValue, потому что в ней может быть выставлен формат ячейки(если это текстовый, то принимая изменения формула станет текстом) this.ws.workbook.sortDependency(true); } //todo не должны удаляться ссылки, если сделать merge ее части. if(this.isEmptyTextString()) { var cell = this.ws.getCell3(this.nRow, this.nCol); cell.removeHyperlink(); } return ret; }; Cell.prototype.setValue2=function(array){ var DataOld = null; if(History.Is_On()) DataOld = this.getValueData(); //[{text:"",format:TextFormat},{}...] this.setValueCleanFormula(); this.oValue.clean(); this.oValue.setValue2(this, array); this.ws.workbook.sortDependency(); var DataNew = null; if(History.Is_On()) DataNew = this.getValueData(); if(History.Is_On() && false == DataOld.isEqual(DataNew)) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew)); //todo не должны удаляться ссылки, если сделать merge ее части. if(this.isEmptyTextString()) { var cell = this.ws.getCell3(this.nRow, this.nCol); cell.removeHyperlink(); } }; Cell.prototype.setValueCleanFormula = function (array) { //удаляем сторое значение var ws = this.ws; var wb = this.ws.workbook; var sheetId = this.ws.getId(); var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol); if (this.sFormula) wb.dependencyFormulas.deleteMasterNodes2(ws.Id, cellId); this.sFormula = null; this.formulaParsed = null; this.setFormulaCA(false); wb.needRecalc.nodes[getVertexId(sheetId, cellId)] = [sheetId, cellId]; wb.needRecalc.length++; }; Cell.prototype.setType=function(type){ if(type != this.oValue.type){ var DataOld = this.getValueData(); this.oValue.setValueType(type); var DataNew = this.getValueData(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew)); } return this.oValue.type; }; Cell.prototype.getType=function(){ return this.oValue.type; }; Cell.prototype.setCellStyle=function(val){ var newVal = this.ws.workbook.CellStyles._prepareCellStyle(val); var oRes = this.ws.workbook.oStyleManager.setCellStyle(this, newVal); if(History.Is_On()) { var oldStyleName = this.ws.workbook.CellStyles.getStyleNameByXfId(oRes.oldVal); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Style, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldStyleName, val)); // Выставляем стиль var oStyle = this.ws.workbook.CellStyles.getStyleByXfId(oRes.newVal); if (oStyle.ApplyFont) this.setFont(oStyle.getFont()); if (oStyle.ApplyFill) this.setFill(oStyle.getFill()); if (oStyle.ApplyBorder) this.setBorder(oStyle.getBorder()); if (oStyle.ApplyNumberFormat) this.setNumFormat(oStyle.getNumFormatStr()); } this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setNumFormat=function(val){ var oRes; /*if( val == aStandartNumFormats[0] && this.formulaParsed && this.formulaParsed.value && this.formulaParsed.value.numFormat !== null && this.formulaParsed.value.numFormat !== undefined && aStandartNumFormats[this.formulaParsed.value.numFormat] ) oRes = this.ws.workbook.oStyleManager.setNumFormat(this, aStandartNumFormats[this.formulaParsed.value.numFormat]); else*/ oRes = this.ws.workbook.oStyleManager.setNumFormat(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Numformat, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.shiftNumFormat=function(nShift, dDigitsCount){ var bRes = false; var bGeneral = true; var sNumFormat; if(null != this.xfs && null != this.xfs.num) sNumFormat = this.xfs.num.getFormat(); else sNumFormat = g_oDefaultFormat.Num.getFormat(); if("General" != sNumFormat) { var oCurNumFormat = oNumFormatCache.get(sNumFormat); if(null != oCurNumFormat && false == oCurNumFormat.isGeneralFormat()) { bGeneral = false; var output = {}; bRes = oCurNumFormat.shiftFormat(output, nShift); if(true == bRes) this.setNumFormat(output.format); } } if(bGeneral) { if(CellValueType.Number == this.oValue.type) { var sGeneral = AscCommon.DecodeGeneralFormat(this.oValue.number, this.oValue.type, dDigitsCount); var oGeneral = oNumFormatCache.get(sGeneral); if(null != oGeneral && false == oGeneral.isGeneralFormat()) { var output = {}; bRes = oGeneral.shiftFormat(output, nShift); if(true == bRes) this.setNumFormat(output.format); } } } this.oValue.cleanCache(); return bRes; }; Cell.prototype.setFont=function(val, bModifyValue){ if(false != bModifyValue) { //убираем комплексные строки if(null != this.oValue.multiText) { var oldVal = null; if(History.Is_On()) oldVal = this.getValueData(); this.oValue.makeSimpleText(); if(History.Is_On()) { var newVal = this.getValueData(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal)); } } } var oRes = this.ws.workbook.oStyleManager.setFont(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) { var oldVal = null; if(null != oRes.oldVal) oldVal = oRes.oldVal.clone(); var newVal = null; if(null != oRes.newVal) newVal = oRes.newVal.clone(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetFont, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal)); } this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setFontname=function(val){ var oRes = this.ws.workbook.oStyleManager.setFontname(this, val); this.oValue.setFontname(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontname, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setFontsize=function(val){ var oRes = this.ws.workbook.oStyleManager.setFontsize(this, val); this.oValue.setFontsize(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontsize, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setFontcolor=function(val){ var oRes = this.ws.workbook.oStyleManager.setFontcolor(this, val); this.oValue.setFontcolor(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontcolor, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setBold=function(val){ var oRes = this.ws.workbook.oStyleManager.setBold(this, val); this.oValue.setBold(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Bold, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setItalic=function(val){ var oRes = this.ws.workbook.oStyleManager.setItalic(this, val); this.oValue.setItalic(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Italic, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setUnderline=function(val){ var oRes = this.ws.workbook.oStyleManager.setUnderline(this, val); this.oValue.setUnderline(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Underline, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setStrikeout=function(val){ var oRes = this.ws.workbook.oStyleManager.setStrikeout(this, val); this.oValue.setStrikeout(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Strikeout, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setFontAlign=function(val){ var oRes = this.ws.workbook.oStyleManager.setFontAlign(this, val); this.oValue.setFontAlign(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_FontAlign, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setAlignVertical=function(val){ var oRes = this.ws.workbook.oStyleManager.setAlignVertical(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_AlignVertical, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setAlignHorizontal=function(val){ var oRes = this.ws.workbook.oStyleManager.setAlignHorizontal(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_AlignHorizontal, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setFill=function(val){ var oRes = this.ws.workbook.oStyleManager.setFill(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fill, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setBorder=function(val){ var oRes = this.ws.workbook.oStyleManager.setBorder(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal){ var oldVal = null; if(null != oRes.oldVal) oldVal = oRes.oldVal.clone(); var newVal = null; if(null != oRes.newVal) newVal = oRes.newVal.clone(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Border, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal)); } this.compiledXfs = null; }; Cell.prototype.setShrinkToFit=function(val){ var oRes = this.ws.workbook.oStyleManager.setShrinkToFit(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ShrinkToFit, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setWrap=function(val){ var oRes = this.ws.workbook.oStyleManager.setWrap(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Wrap, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setAngle=function(val){ var oRes = this.ws.workbook.oStyleManager.setAngle(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Angle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setVerticalText=function(val){ var oRes = this.ws.workbook.oStyleManager.setVerticalText(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Angle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setQuotePrefix=function(val){ var oRes = this.ws.workbook.oStyleManager.setQuotePrefix(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetQuotePrefix, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.oValue.cleanCache(); }; Cell.prototype.setConditionalFormattingStyle=function(xfs){ this.conditionalFormattingXfs = xfs; this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.getConditionalFormattingStyle = function (xfs) { return this.conditionalFormattingXfs; }; Cell.prototype.setTableStyle=function(xfs){ this.tableXfs = xfs; this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.getTableStyle=function(){ return this.tableXfs; }; Cell.prototype.setStyle=function(xfs){ var oldVal = this.xfs; var newVal = null; this.xfs = null; if(null != xfs) { this.xfs = xfs.clone(); newVal = this.xfs; } this.compiledXfs = null; this.oValue.cleanCache(); if(History.Is_On() && false == ((null == oldVal && null == newVal) || (null != oldVal && null != newVal && true == oldVal.isEqual(newVal)))) { if(null != oldVal) oldVal = oldVal.clone(); if(null != newVal) newVal = newVal.clone(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetStyle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal)); } // if(this.isEmpty()) // this.Remove(); }; Cell.prototype.getFormula=function(){ if(null != this.sFormula) return this.sFormula; else return ""; }; Cell.prototype.getValueForEdit=function(numFormat){ return this.oValue.getValueForEdit(this); }; Cell.prototype.getValueForEdit2=function(numFormat){ return this.oValue.getValueForEdit2(this); }; Cell.prototype.getValueWithoutFormat=function(){ return this.oValue.getValueWithoutFormat(); }; Cell.prototype.getValue=function(numFormat, dDigitsCount){ return this.oValue.getValue(this); }; Cell.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){ if(null == fIsFitMeasurer) fIsFitMeasurer = function(aText){return true;}; if(null == dDigitsCount) dDigitsCount = AscCommon.gc_nMaxDigCountView; return this.oValue.getValue2(this, dDigitsCount, fIsFitMeasurer); }; Cell.prototype.getNumFormatStr=function(){ if(null != this.xfs && null != this.xfs.num) return this.xfs.num.getFormat(); return g_oDefaultFormat.Num.getFormat(); }; Cell.prototype.getNumFormat=function(){ return oNumFormatCache.get(this.getNumFormatStr()); }; Cell.prototype.getNumFormatType=function(){ return this.getNumFormat().getType(); }; Cell.prototype.moveHor=function(val){ this.nCol += val; }; Cell.prototype.moveVer=function(val){ this.nRow += val; }; Cell.prototype.getOffset=function(cell){ return {offsetCol:(this.nCol - cell.nCol), offsetRow:(this.nRow - cell.nRow)}; }; Cell.prototype.getOffset2=function(cellId){ var cAddr2 = new CellAddress(cellId); return {offsetCol:(this.nCol - cAddr2.col + 1), offsetRow:(this.nRow - cAddr2.row + 1)}; }; Cell.prototype.getOffset3=function(cellAddr){ var cAddr2 = cellAddr; return {offsetCol:(this.nCol - cAddr2.col + 1), offsetRow:(this.nRow - cAddr2.row + 1)}; }; Cell.prototype.getValueData = function(){ return new UndoRedoData_CellValueData(this.sFormula, this.oValue.clone()); }; Cell.prototype.setValueData = function(Val){ //значения устанавляваются через setValue, чтобы пересчитались формулы if(null != Val.formula) this.setValue("=" + Val.formula); else if(null != Val.value) { var DataOld = null; var DataNew = null; if (History.Is_On()) DataOld = this.getValueData(); this.setValueCleanFormula(); this.oValue = Val.value.clone(this); this.ws.workbook.sortDependency(); if (History.Is_On()) { DataNew = this.getValueData(); if (false == DataOld.isEqual(DataNew)) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew)); } } else this.setValue(""); }; Cell.prototype.setFormulaCA = function(ca){ if(ca) this.sFormulaCA = true; else if( this.sFormulaCA ) this.sFormulaCA = null; }; //------------------------------------------------------------------------------------------------- /** * @constructor */ function Range(worksheet, r1, c1, r2, c2){ this.worksheet = worksheet; this.bbox = new Asc.Range(c1, r1, c2, r2); //first last устарели, не убраны только для совместимости this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0); this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0); } Range.prototype.createFromBBox=function(worksheet, bbox){ var oRes = new Range(worksheet, bbox.r1, bbox.c1, bbox.r2, bbox.c2); oRes.bbox = bbox.clone(); return oRes; }; Range.prototype.clone=function(oNewWs){ if(!oNewWs) oNewWs = this.worksheet; return new Range(oNewWs, this.bbox.r1, this.bbox.c1, this.bbox.r2, this.bbox.c2); }; Range.prototype.getFirst=function(){ return this.first; }; Range.prototype.getLast=function(){ return this.last; }; Range.prototype._foreach=function(action){ if(null != action) { var oBBox = this.bbox; for(var i = oBBox.r1; i <= oBBox.r2; i++){ for(var j = oBBox.c1; j <= oBBox.c2; j++){ var oCurCell = this.worksheet._getCell(i, j); action(oCurCell, i, j, oBBox.r1, oBBox.c1); } } } }; Range.prototype._foreach2=function(action){ if(null != action) { var oBBox = this.bbox, minC = Math.min( this.worksheet.getColsCount(), oBBox.c2 ), minR = Math.min( this.worksheet.getRowsCount(), oBBox.r2 ); for(var i = oBBox.r1; i <= minR; i++){ for(var j = oBBox.c1; j <= minC; j++){ var oCurCell = this.worksheet._getCellNoEmpty(i, j); var oRes = action(oCurCell, i, j, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } }; Range.prototype._foreachNoEmpty=function(action){ if(null != action) { var oBBox = this.bbox, minC = Math.min( this.worksheet.getColsCount(), oBBox.c2 ), minR = Math.min( this.worksheet.getRowsCount(), oBBox.r2 ); for(var i = oBBox.r1; i <= minR; i++){ for(var j = oBBox.c1; j <= minC; j++){ var oCurCell = this.worksheet._getCellNoEmpty(i, j); if(null != oCurCell) { var oRes = action(oCurCell, i, j, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } }; Range.prototype._foreachRow=function(actionRow, actionCell){ var oBBox = this.bbox; for(var i = oBBox.r1; i <= oBBox.r2; i++){ var row = this.worksheet._getRow(i); if(row) { if(null != actionRow) actionRow(row); if(null != actionCell) { for(var j in row.c){ var oCurCell = row.c[j]; if(null != oCurCell) actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1); } } } } }; Range.prototype._foreachRowNoEmpty=function(actionRow, actionCell){ var oBBox = this.bbox; if(0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2) { var aRows = this.worksheet._getRows(); for(var i in aRows) { var row = aRows[i]; if( null != actionRow ) { var oRes = actionRow(row); if(null != oRes) return oRes; } if( null != actionCell ) for(var j in row.c){ var oCurCell = row.c[j]; if(null != oCurCell) { var oRes = actionCell(oCurCell, i - 0, j - 0, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } else { var minR = Math.min(oBBox.r2,this.worksheet.getRowsCount()); for(var i = oBBox.r1; i <= minR; i++){ var row = this.worksheet._getRowNoEmpty(i); if(row) { if( null != actionRow ) { var oRes = actionRow(row); if(null != oRes) return oRes; } if( null != actionCell ) for(var j in row.c){ var oCurCell = row.c[j]; if(null != oCurCell) { var oRes = actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } } }; Range.prototype._foreachCol=function(actionCol, actionCell){ var oBBox = this.bbox; if(null != actionCol) { for(var i = oBBox.c1; i <= oBBox.c2; ++i) { var col = this.worksheet._getCol(i); if(null != col) actionCol(col); } } if(null != actionCell) { var aRows = this.worksheet._getRows(); for(var i in aRows) { var row = aRows[i]; if(row) { if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) { for(var j in row.c) { var oCurCell = row.c[j]; if(null != oCurCell) actionCell(oCurCell, i - 0, j - 0, oBBox.r1, oBBox.c1); } } else { for(var j = oBBox.c1; j <= oBBox.c2; ++j) { var oCurCell = row.c[j]; if(null != oCurCell) actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1); } } } } } }; Range.prototype._foreachColNoEmpty=function(actionCol, actionCell){ var oBBox = this.bbox; var minC = Math.min( oBBox.c2,this.worksheet.getColsCount() ); if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) { if(null != actionCol) { var aCols = this.worksheet._getCols(); for(var i in aCols) { var nIndex = i - 0; if(nIndex >= oBBox.c1 && nIndex <= minC ) { var col = this.worksheet._getColNoEmpty(nIndex); if(null != col) { var oRes = actionCol(col); if(null != oRes) return oRes; } } } } if(null != actionCell) { var aRows = this.worksheet._getRows(); for(var i in aRows) { var row = aRows[i]; if(row) { for(var j in row.c) { var nIndex = j - 0; if(nIndex >= oBBox.c1 && nIndex <= minC) { var oCurCell = row.c[j]; if(null != oCurCell) { var oRes = actionCell(oCurCell, i - 0, nIndex, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } } } } else { if(null != actionCol) { for(var i = oBBox.c1; i <= minC; ++i) { var col = this.worksheet._getColNoEmpty(i); if(null != col) { var oRes = actionCol(col); if(null != oRes) return oRes; } } } if(null != actionCell) { var aRows = this.worksheet._getRows(); for(var i in aRows) { var row = aRows[i]; if(row) { for(var j = oBBox.c1; j <= minC; ++j) { var oCurCell = row.c[j]; if(null != oCurCell) { var oRes = actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } } } }; Range.prototype._foreachIndex=function(action){ var oBBox = this.bbox; for(var i = oBBox.r1; i <= oBBox.r2; i++){ for(var j = oBBox.c1; j <= oBBox.c2; j++){ var res = action(i, j); if(null != res) return res; } } return null; }; Range.prototype._getRangeType=function(oBBox){ if(null == oBBox) oBBox = this.bbox; return getRangeType(oBBox); }; Range.prototype._setProperty=function(actionRow, actionCol, actionCell){ var nRangeType = this._getRangeType(); if(c_oRangeType.Range == nRangeType) this._foreach(actionCell); else if(c_oRangeType.Row == nRangeType) this._foreachRow(actionRow, actionCell); else if(c_oRangeType.Col == nRangeType) this._foreachCol(actionCol, actionCell); else { //сюда не должны заходить вообще // this._foreachRow(actionRow, actionCell); // if(null != actionCol) // this._foreachCol(actionCol, null); } }; Range.prototype._setPropertyNoEmpty=function(actionRow, actionCol, actionCell){ var nRangeType = this._getRangeType(); if(c_oRangeType.Range == nRangeType) return this._foreachNoEmpty(actionCell); else if(c_oRangeType.Row == nRangeType) return this._foreachRowNoEmpty(actionRow, actionCell); else if(c_oRangeType.Col == nRangeType) return this._foreachColNoEmpty(actionCol, actionCell); else { var oRes = this._foreachRowNoEmpty(actionRow, actionCell); if(null != oRes) return oRes; if(null != actionCol) oRes = this._foreachColNoEmpty(actionCol, null); return oRes; } }; Range.prototype.containCell=function(cellId){ var cellAddress = cellId; return cellAddress.getRow0() >= this.bbox.r1 && cellAddress.getCol0() >= this.bbox.c1 && cellAddress.getRow0() <= this.bbox.r2 && cellAddress.getCol0() <= this.bbox.c2; }; Range.prototype.containCell2=function(cell){ return cell.nRow >= this.bbox.r1 && cell.nCol >= this.bbox.c1 && cell.nRow <= this.bbox.r2 && cell.nCol <= this.bbox.c2; }; Range.prototype.cross = function(cellAddress){ if( cellAddress.getRow0() >= this.bbox.r1 && cellAddress.getRow0() <= this.bbox.r2 && this.bbox.c1 == this.bbox.c2) return {r:cellAddress.getRow()}; if( cellAddress.getCol0() >= this.bbox.c1 && cellAddress.getCol0() <= this.bbox.c2 && this.bbox.r1 == this.bbox.r2) return {c:cellAddress.getCol()}; return undefined; }; Range.prototype.getWorksheet=function(){ return this.worksheet; }; Range.prototype.isFormula = function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); return cell.isFormula(); }; Range.prototype.isOneCell=function(){ var oBBox = this.bbox; return oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2; }; Range.prototype.isColumn = function(){ if(this.first.getRow() == 1 && this.last.getRow() == AscCommon.gc_nMaxRow) return true; else return false; }; Range.prototype.isRow = function(){ if(this.first.getCol() == 1 && this.last.getCol() == AscCommon.gc_nMaxCol) return true; else return false; }; Range.prototype.getBBox=function(){ //1 - based return {r1: this.bbox.r1 + 1, r2: this.bbox.r2 + 1, c1: this.bbox.c1 + 1, c2: this.bbox.c2 + 1}; }; Range.prototype.getBBox0=function(){ //0 - based return this.bbox; }; Range.prototype.getName=function(){ return this.bbox.getName(); }; Range.prototype.getCells=function(){ var aResult = []; var oBBox = this.bbox; if(!((0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) || (0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2))) { for(var i = oBBox.r1; i <= oBBox.r2; i++){ for(var j = oBBox.c1; j <= oBBox.c2; j++){ aResult.push(this.worksheet._getCell(i, j)); } } } return aResult; }; Range.prototype.setValue=function(val,callback, isCopyPaste){ History.Create_NewPoint(); History.StartTransaction(); this._foreach(function(cell){ cell.setValue(val,callback, isCopyPaste); // if(cell.isEmpty()) // cell.Remove(); }); History.EndTransaction(); }; Range.prototype.setValue2=function(array){ History.Create_NewPoint(); History.StartTransaction(); //[{"text":"qwe","format":{"b":true, "i":false, "u":Asc.EUnderline.underlineNone, "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript" }},{}...] /* Устанавливаем значение в Range ячеек. В отличае от setValue, сюда мы попадаем только в случае ввода значения отличного от формулы. Таким образом, если в ячейке была формула, то для нее в графе очищается список ячеек от которых зависела. После чего выставляем флаг о необходимости пересчета. */ this._foreach(function(cell){ cell.setValue2(array); // if(cell.isEmpty()) // cell.Remove(); }); History.EndTransaction(); }; Range.prototype.setCellStyle=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setCellStyle(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setCellStyle(val); }, function(col){ col.setCellStyle(val); }, function(cell){ cell.setCellStyle(val); }); }; Range.prototype.setTableStyle=function(val){ this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType || null === val) { //this.worksheet.getAllCol().setCellStyle(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; //row.setCellStyle(val); }, function(col){ //col.setCellStyle(val); }, function(cell){ cell.setTableStyle(val); }); }; Range.prototype.setNumFormat=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setNumFormat(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setNumFormat(val); }, function(col){ col.setNumFormat(val); }, function(cell){ cell.setNumFormat(val); }); }; Range.prototype.shiftNumFormat=function(nShift, aDigitsCount){ History.Create_NewPoint(); var bRes = false; this._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){ bRes |= cell.shiftNumFormat(nShift, aDigitsCount[nCol0 - nColStart] || 8); }); return bRes; }; Range.prototype.setFont=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFont(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFont(val); }, function(col){ col.setFont(val); }, function(cell){ cell.setFont(val); }); }; Range.prototype.setFontname=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFontname(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFontname(val); }, function(col){ col.setFontname(val); }, function(cell){ cell.setFontname(val); }); }; Range.prototype.setFontsize=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFontsize(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFontsize(val); }, function(col){ col.setFontsize(val); }, function(cell){ cell.setFontsize(val); }); }; Range.prototype.setFontcolor=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFontcolor(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFontcolor(val); }, function(col){ col.setFontcolor(val); }, function(cell){ cell.setFontcolor(val); }); }; Range.prototype.setBold=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setBold(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setBold(val); }, function(col){ col.setBold(val); }, function(cell){ cell.setBold(val); }); }; Range.prototype.setItalic=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setItalic(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setItalic(val); }, function(col){ col.setItalic(val); }, function(cell){ cell.setItalic(val); }); }; Range.prototype.setUnderline=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setUnderline(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setUnderline(val); }, function(col){ col.setUnderline(val); }, function(cell){ cell.setUnderline(val); }); }; Range.prototype.setStrikeout=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setStrikeout(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setStrikeout(val); }, function(col){ col.setStrikeout(val); }, function(cell){ cell.setStrikeout(val); }); }; Range.prototype.setFontAlign=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFontAlign(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFontAlign(val); }, function(col){ col.setFontAlign(val); }, function(cell){ cell.setFontAlign(val); }); }; Range.prototype.setAlignVertical=function(val){ History.Create_NewPoint(); if("none" == val) val = null; this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setAlignVertical(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setAlignVertical(val); }, function(col){ col.setAlignVertical(val); }, function(cell){ cell.setAlignVertical(val); }); }; Range.prototype.setAlignHorizontal=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setAlignHorizontal(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setAlignHorizontal(val); }, function(col){ col.setAlignHorizontal(val); }, function(cell){ cell.setAlignHorizontal(val); }); }; Range.prototype.setFill=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFill(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFill(val); }, function(col){ col.setFill(val); }, function(cell){ cell.setFill(val); }); }; Range.prototype.setBorderSrc=function(border){ History.Create_NewPoint(); History.StartTransaction(); if (null == border) border = new Border(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setBorder(border.clone()); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setBorder(border.clone()); }, function(col){ col.setBorder(border.clone()); }, function(cell){ cell.setBorder(border.clone()); }); History.EndTransaction(); }; Range.prototype._setBorderMerge=function(bLeft, bTop, bRight, bBottom, oNewBorder, oCurBorder){ var oTargetBorder = new Border(); //не делаем clone для свойств потому у нас нельзя поменять свойство отдельное свойство border можно только применить border целиком if(bLeft) oTargetBorder.l = oNewBorder.l; else oTargetBorder.l = oNewBorder.iv; if(bTop) oTargetBorder.t = oNewBorder.t; else oTargetBorder.t = oNewBorder.ih; if(bRight) oTargetBorder.r = oNewBorder.r; else oTargetBorder.r = oNewBorder.iv; if(bBottom) oTargetBorder.b = oNewBorder.b; else oTargetBorder.b = oNewBorder.ih; oTargetBorder.d = oNewBorder.d; oTargetBorder.dd = oNewBorder.dd; oTargetBorder.du = oNewBorder.du; var oRes = null; if(null != oCurBorder) { oCurBorder.mergeInner(oTargetBorder); oRes = oCurBorder; } else oRes = oTargetBorder; return oRes; }; Range.prototype._setCellBorder=function(bbox, cell, oNewBorder){ if(null == oNewBorder) cell.setBorder(oNewBorder); else { var oCurBorder = null; if(null != cell.xfs && null != cell.xfs.border) oCurBorder = cell.xfs.border.clone(); else oCurBorder = g_oDefaultFormat.Border.clone(); var nRow = cell.nRow; var nCol = cell.nCol; cell.setBorder(this._setBorderMerge(nCol == bbox.c1, nRow == bbox.r1, nCol == bbox.c2, nRow == bbox.r2, oNewBorder, oCurBorder)); } }; Range.prototype._setRowColBorder=function(bbox, rowcol, bRow, oNewBorder){ if(null == oNewBorder) rowcol.setBorder(oNewBorder); else { var oCurBorder = null; if(null != rowcol.xfs && null != rowcol.xfs.border) oCurBorder = rowcol.xfs.border.clone(); var bLeft, bTop, bRight, bBottom = false; if(bRow) { bTop = rowcol.index == bbox.r1; bBottom = rowcol.index == bbox.r2; } else { bLeft = rowcol.index == bbox.c1; bRight = rowcol.index == bbox.c2; } rowcol.setBorder(this._setBorderMerge(bLeft, bTop, bRight, bBottom, oNewBorder, oCurBorder)); } }; Range.prototype._setBorderEdge=function(bbox, oItemWithXfs, nRow, nCol, oNewBorder){ var oCurBorder = null; if(null != oItemWithXfs.xfs && null != oItemWithXfs.xfs.border) oCurBorder = oItemWithXfs.xfs.border; if(null != oCurBorder) { var oCurBorderProp = null; if(nCol == bbox.c1 - 1) oCurBorderProp = oCurBorder.r; else if(nRow == bbox.r1 - 1) oCurBorderProp = oCurBorder.b; else if(nCol == bbox.c2 + 1) oCurBorderProp = oCurBorder.l; else if(nRow == bbox.r2 + 1) oCurBorderProp = oCurBorder.t; var oNewBorderProp = null; if(null == oNewBorder) oNewBorderProp = new AscCommonExcel.BorderProp(); else { if(nCol == bbox.c1 - 1) oNewBorderProp = oNewBorder.l; else if(nRow == bbox.r1 - 1) oNewBorderProp = oNewBorder.t; else if(nCol == bbox.c2 + 1) oNewBorderProp = oNewBorder.r; else if(nRow == bbox.r2 + 1) oNewBorderProp = oNewBorder.b; } if(null != oNewBorderProp && null != oCurBorderProp && c_oAscBorderStyles.None != oCurBorderProp.s && (null == oNewBorder || c_oAscBorderStyles.None != oNewBorderProp.s) && (oNewBorderProp.s != oCurBorderProp.s || oNewBorderProp.getRgbOrNull() != oCurBorderProp.getRgbOrNull())){ var oTargetBorder = oCurBorder.clone(); if(nCol == bbox.c1 - 1) oTargetBorder.r = new AscCommonExcel.BorderProp(); else if(nRow == bbox.r1 - 1) oTargetBorder.b = new AscCommonExcel.BorderProp(); else if(nCol == bbox.c2 + 1) oTargetBorder.l = new AscCommonExcel.BorderProp(); else if(nRow == bbox.r2 + 1) oTargetBorder.t = new AscCommonExcel.BorderProp(); oItemWithXfs.setBorder(oTargetBorder); } } }; Range.prototype.setBorder=function(border){ //border = null очисть border //"ih" - внутренние горизонтальные, "iv" - внутренние вертикальные History.Create_NewPoint(); var _this = this; var oBBox = this.bbox; this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { var oAllCol = this.worksheet.getAllCol(); _this._setRowColBorder(oBBox, oAllCol, false, border); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; _this._setRowColBorder(oBBox, row, true, border); }, function(col){ _this._setRowColBorder(oBBox, col, false, border); }, function(cell){ _this._setCellBorder(oBBox, cell, border); }); //убираем граничные border var aEdgeBorders = []; if(oBBox.c1 > 0 && (null == border || !border.l.isEmpty())) aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1, oBBox.c1 - 1, oBBox.r2, oBBox.c1 - 1)); if(oBBox.r1 > 0 && (null == border || !border.t.isEmpty())) aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1 - 1, oBBox.c1, oBBox.r1 - 1, oBBox.c2)); if(oBBox.c2 < gc_nMaxCol0 && (null == border || !border.r.isEmpty())) aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1, oBBox.c2 + 1, oBBox.r2, oBBox.c2 + 1)); if(oBBox.r2 < gc_nMaxRow0 && (null == border || !border.b.isEmpty())) aEdgeBorders.push(this.worksheet.getRange3(oBBox.r2 + 1, oBBox.c1, oBBox.r2 + 1, oBBox.c2)); for(var i = 0, length = aEdgeBorders.length; i < length; i++) { var range = aEdgeBorders[i]; range._setPropertyNoEmpty(function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; _this._setBorderEdge(oBBox, row, row.index, 0, border); }, function(col){ _this._setBorderEdge(oBBox, col, 0, col.index, border); }, function(cell){ _this._setBorderEdge(oBBox, cell, cell.nRow, cell.nCol, border); }); } }; Range.prototype.setShrinkToFit=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setShrinkToFit(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setShrinkToFit(val); }, function(col){ col.setShrinkToFit(val); }, function(cell){ cell.setShrinkToFit(val); }); }; Range.prototype.setWrap=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setWrap(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setWrap(val); }, function(col){ col.setWrap(val); }, function(cell){ cell.setWrap(val); }); }; Range.prototype.setAngle=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setAngle(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setAngle(val); }, function(col){ col.setAngle(val); }, function(cell){ cell.setAngle(val); }); }; Range.prototype.setVerticalText=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setVerticalText(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setVerticalText(val); }, function(col){ col.setVerticalText(val); }, function(cell){ cell.setVerticalText(val); }); }; Range.prototype.setType=function(type){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) fSetProperty = this._setPropertyNoEmpty; fSetProperty.call(this, null, null, function(cell){ cell.setType(type); }); }; Range.prototype.getType=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); if(null != cell) return cell.getType(); else return null; }; Range.prototype.isEmptyText=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); return (null != cell) ? cell.isEmptyText() : true; }; Range.prototype.isEmptyTextString=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); return (null != cell) ? cell.isEmptyTextString() : true; }; Range.prototype.isFormula=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); return (null != cell) ? cell.isFormula() : false; }; Range.prototype.getFormula=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); if(null != cell) return cell.getFormula(); else return ""; }; Range.prototype.getValueForEdit=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); if(null != cell) { var numFormat = this.getNumFormat(); return cell.getValueForEdit(numFormat); } else return ""; }; Range.prototype.getValueForEdit2=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); if(null != cell) { var numFormat = this.getNumFormat(); return cell.getValueForEdit2(numFormat); } else { var oRow = this.worksheet._getRowNoEmpty(this.bbox.r1); var oCol = this.worksheet._getColNoEmptyWithAll(this.bbox.c1); var xfs = null; if(null != oRow && null != oRow.xfs) xfs = oRow.xfs.clone(); else if(null != oCol && null != oCol.xfs) xfs = oCol.xfs.clone(); var oTempCell = new Cell(this.worksheet); oTempCell.create(xfs, this.bbox.r1, this.bbox.c1); return oTempCell.getValueForEdit2(); } }; Range.prototype.getValueWithoutFormat=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1); if(null != cell) return cell.getValueWithoutFormat(); else return ""; }; Range.prototype.getValue=function(){ return this.getValueWithoutFormat(); }; Range.prototype.getValueWithFormat=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1); if(null != cell) return cell.getValue(); else return ""; }; Range.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){ //[{"text":"qwe","format":{"b":true, "i":false, "u":Asc.EUnderline.underlineNone, "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript" }},{}...] var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1); if(null != cell) return cell.getValue2(dDigitsCount, fIsFitMeasurer); else { var oRow = this.worksheet._getRowNoEmpty(this.bbox.r1); var oCol = this.worksheet._getColNoEmptyWithAll(this.bbox.c1); var xfs = null; if(null != oRow && null != oRow.xfs) xfs = oRow.xfs.clone(); else if(null != oCol && null != oCol.xfs) xfs = oCol.xfs.clone(); var oTempCell = new Cell(this.worksheet); oTempCell.create(xfs, this.bbox.r1, this.bbox.c1); return oTempCell.getValue2(dDigitsCount, fIsFitMeasurer); } }; Range.prototype.getXfId=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.XfId) return xfs.XfId; } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.XfId) return row.xfs.XfId; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.XfId) return col.xfs.XfId; } return g_oDefaultFormat.XfId; }; Range.prototype.getStyleName=function(){ var res = this.worksheet.workbook.CellStyles.getStyleNameByXfId(this.getXfId()); // ToDo убрать эту заглушку (нужно делать на открытии) в InitStyleManager return res || this.worksheet.workbook.CellStyles.getStyleNameByXfId(g_oDefaultFormat.XfId); }; Range.prototype.getTableStyle=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); return cell ? cell.getTableStyle() : null; }; Range.prototype.getNumFormat=function(){ return oNumFormatCache.get(this.getNumFormatStr()); }; Range.prototype.getNumFormatStr=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.num) return xfs.num.getFormat(); } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.num) return row.xfs.num.getFormat(); var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.num) return col.xfs.num.getFormat(); } return g_oDefaultFormat.Num.getFormat(); }; Range.prototype.getNumFormatType=function(){ return this.getNumFormat().getType(); }; // Узнаем отличается ли шрифт (размер и гарнитура) в ячейке от шрифта в строке Range.prototype.isNotDefaultFont = function () { // Получаем фонт ячейки var cellFont = this.getFont(); var rowFont = g_oDefaultFormat.Font; var row = this.worksheet._getRowNoEmpty(this.bbox.r1); if (null != row && null != row.xfs && null != row.xfs.font) rowFont = row.xfs.font; else if (null != this.oAllCol) rowFont = this.oAllCol; return (cellFont.fn !== rowFont.fn || cellFont.fs !== rowFont.fs); }; Range.prototype.getFont = function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.font) return xfs.font; } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.font) return row.xfs.font; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.font) return col.xfs.font; } return g_oDefaultFormat.Font; }; Range.prototype.getFontname=function(){ return this.getFont().fn; }; Range.prototype.getFontsize=function(){ return this.getFont().fs; }; Range.prototype.getFontcolor=function(){ return this.getFont().c; }; Range.prototype.getBold=function(){ return this.getFont().b; }; Range.prototype.getItalic=function(){ return this.getFont().i; }; Range.prototype.getUnderline=function(){ return this.getFont().u; }; Range.prototype.getStrikeout=function(){ return this.getFont().s; }; Range.prototype.getFontAlign=function(){ return this.getFont().va; }; Range.prototype.getQuotePrefix=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.QuotePrefix) return xfs.QuotePrefix; } return false; }; Range.prototype.getAlignVertical=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return xfs.align.ver; else return g_oDefaultFormat.AlignAbs.ver; } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return row.xfs.align.ver; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return col.xfs.align.ver; } return g_oDefaultFormat.Align.ver; }; Range.prototype.getAlignHorizontal=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return xfs.align.hor; else return g_oDefaultFormat.AlignAbs.hor; } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return row.xfs.align.hor; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return col.xfs.align.hor; } return g_oDefaultFormat.Align.hor; }; Range.prototype.getAlignHorizontalByValue=function(){ //возвращает Align в зависимости от значния в ячейке //values: none, center, justify, left , right, null var align = this.getAlignHorizontal(); if("none" == align){ //пытаемся определить по значению var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(cell){ switch(cell.getType()){ case CellValueType.String:align = "left";break; case CellValueType.Bool: case CellValueType.Error:align = "center";break; default: //Если есть value и не проставлен тип значит это число, у всех остальных типов значение не null if(this.getValueWithoutFormat()) { //смотрим var oNumFmt = this.getNumFormat(); if(true == oNumFmt.isTextFormat()) align = "left"; else align = "right"; } else align = "left"; break; } } if("none" == align) align = "left"; } return align; }; Range.prototype.getFill=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.fill) return xfs.fill.bg; } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.fill) return row.xfs.fill.bg; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.fill) return col.xfs.fill.bg; } return g_oDefaultFormat.Fill.bg; }; Range.prototype.getBorderSrc=function(_cell){ //Возвращает как записано в файле, не проверяя бордеры соседних ячеек //формат //\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false } //"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot //"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell //"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell if(null == _cell) _cell = this.getFirst(); var nRow = _cell.getRow0(); var nCol = _cell.getCol0(); var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.border) return xfs.border; } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.border) return row.xfs.border; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.border) return col.xfs.border; } return g_oDefaultFormat.Border; }; Range.prototype.getBorder=function(_cell){ //_cell - optional //Возвращает как записано в файле, не проверяя бордеры соседних ячеек //формат //\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false } //"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot //"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell //"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell var oRes = this.getBorderSrc(_cell); if(null != oRes) return oRes; else return g_oDefaultFormat.Border; }; Range.prototype.getBorderFull=function(){ //Возвращает как excel, т.е. проверяет бордеры соседних ячеек // //\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false } //"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot // //"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell //"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell var borders = this.getBorder(this.getFirst()).clone(); var nRow = this.bbox.r1; var nCol = this.bbox.c1; if(c_oAscBorderStyles.None === borders.l.s){ if(nCol > 1){ var left = this.getBorder(new CellAddress(nRow, nCol - 1, 0)); if(c_oAscBorderStyles.None !== left.r.s) borders.l = left.r; } } if(c_oAscBorderStyles.None === borders.t.s){ if(nRow > 1){ var top = this.getBorder(new CellAddress(nRow - 1, nCol, 0)); if(c_oAscBorderStyles.None !== top.b.s) borders.t = top.b; } } if(c_oAscBorderStyles.None === borders.r.s){ var right = this.getBorder(new CellAddress(nRow, nCol + 1, 0)); if(c_oAscBorderStyles.None !== right.l.s) borders.r = right.l; } if(c_oAscBorderStyles.None === borders.b.s){ var bottom = this.getBorder(new CellAddress(nRow + 1, nCol, 0)); if(c_oAscBorderStyles.None !== bottom.t.s) borders.b = bottom.t; } return borders; }; Range.prototype.getShrinkToFit=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return xfs.align.shrink; else return g_oDefaultFormat.AlignAbs.shrink; } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return row.xfs.align.shrink; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return col.xfs.align.shrink; } return g_oDefaultFormat.Align.shrink; }; Range.prototype.getWrapByAlign = function (align) { // Для justify wrap всегда true return "justify" === align.hor ? true : align.wrap; }; Range.prototype.getWrap=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return this.getWrapByAlign(xfs.align); else return this.getWrapByAlign(g_oDefaultFormat.AlignAbs); } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return this.getWrapByAlign(row.xfs.align); var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return this.getWrapByAlign(col.xfs.align); } return this.getWrapByAlign(g_oDefaultFormat.Align); }; Range.prototype.getAngle=function(){ //угол от -90 до 90 против часовой стрелки от оси OX var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return angleFormatToInterface(xfs.align.angle); else return angleFormatToInterface(g_oDefaultFormat.AlignAbs.angle); } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return angleFormatToInterface(row.xfs.align.angle); var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return angleFormatToInterface(col.xfs.align.angle); } return angleFormatToInterface(g_oDefaultFormat.Align.angle); }; Range.prototype.getVerticalText=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return g_nVerticalTextAngle == xfs.align.angle; else return g_nVerticalTextAngle == g_oDefaultFormat.AlignAbs.angle; } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return g_nVerticalTextAngle == row.xfs.align.angle; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return g_nVerticalTextAngle == col.xfs.align.angle; } return g_nVerticalTextAngle == g_oDefaultFormat.Align.angle; }; Range.prototype.hasMerged=function(){ var aMerged = this.worksheet.mergeManager.get(this.bbox); if(aMerged.all.length > 0) return aMerged.all[0].bbox; return null; }; Range.prototype.mergeOpen=function(){ this.worksheet.mergeManager.add(this.bbox, 1); }; Range.prototype.merge=function(type){ if(null == type) type = Asc.c_oAscMergeOptions.Merge; var oBBox = this.bbox; History.Create_NewPoint(); History.StartTransaction(); if(oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2){ if(type == Asc.c_oAscMergeOptions.MergeCenter) this.setAlignHorizontal("center"); History.EndTransaction(); return; } if(this.hasMerged()) { this.unmerge(); if(type == Asc.c_oAscMergeOptions.MergeCenter) { //сбрасываем AlignHorizontal this.setAlignHorizontal("none"); History.EndTransaction(); return; } } //пробегаемся по границе диапазона, чтобы посмотреть какие границы нужно оставлять var oLeftBorder = null; var oTopBorder = null; var oRightBorder = null; var oBottomBorder = null; var nRangeType = this._getRangeType(oBBox); if(c_oRangeType.Range == nRangeType) { var oThis = this; var fGetBorder = function(bRow, v1, v2, v3, type) { var oRes = null; for(var i = v1; i <= v2; ++i) { var bNeedDelete = true; var oCurCell; if(bRow) oCurCell = oThis.worksheet._getCellNoEmpty(v3, i); else oCurCell = oThis.worksheet._getCellNoEmpty(i, v3); if(null != oCurCell && null != oCurCell.xfs && null != oCurCell.xfs.border) { var border = oCurCell.xfs.border; var oBorderProp; switch(type) { case 1: oBorderProp = border.l;break; case 2: oBorderProp = border.t;break; case 3: oBorderProp = border.r;break; case 4: oBorderProp = border.b;break; } if(false == oBorderProp.isEmpty()) { if(null == oRes) { oRes = oBorderProp; bNeedDelete = false; } else if(true == oRes.isEqual(oBorderProp)) bNeedDelete = false; } } if(bNeedDelete) { oRes = null; break; } } return oRes; }; oLeftBorder = fGetBorder(false, oBBox.r1, oBBox.r2, oBBox.c1, 1); oTopBorder = fGetBorder(true, oBBox.c1, oBBox.c2, oBBox.r1, 2); oRightBorder = fGetBorder(false, oBBox.r1, oBBox.r2, oBBox.c2, 3); oBottomBorder = fGetBorder(true, oBBox.c1, oBBox.c2, oBBox.r2, 4); } else if(c_oRangeType.Row == nRangeType) { var oTopRow = this.worksheet._getRowNoEmpty(oBBox.r1); if(null != oTopRow && null != oTopRow.xfs && null != oTopRow.xfs.border && false == oTopRow.xfs.border.t.isEmpty()) oTopBorder = oTopRow.xfs.border.t; if(oBBox.r1 != oBBox.r2) { var oBottomRow = this.worksheet._getRowNoEmpty(oBBox.r2); if(null != oBottomRow && null != oBottomRow.xfs && null != oBottomRow.xfs.border && false == oBottomRow.xfs.border.b.isEmpty()) oBottomBorder = oBottomRow.xfs.border.b; } } else { var oLeftCol = this.worksheet._getColNoEmptyWithAll(oBBox.c1); if(null != oLeftCol && null != oLeftCol.xfs && null != oLeftCol.xfs.border && false == oLeftCol.xfs.border.l.isEmpty()) oLeftBorder = oLeftCol.xfs.border.l; if(oBBox.c1 != oBBox.c2) { var oRightCol = this.worksheet._getColNoEmptyWithAll(oBBox.c2); if(null != oRightCol && null != oRightCol.xfs && null != oRightCol.xfs.border && false == oRightCol.xfs.border.r.isEmpty()) oRightBorder = oRightCol.xfs.border.r; } } var bFirst = true; var oLeftTopCellStyle = null; var oFirstCellStyle = null; var oFirstCellValue = null; var oFirstCellRow = null; var oFirstCellCol = null; var oFirstCellHyperlink = null; this._setPropertyNoEmpty(null,null, function(cell, nRow0, nCol0, nRowStart, nColStart){ if(bFirst && false == cell.isEmptyText()) { bFirst = false; oFirstCellStyle = cell.getStyle(); oFirstCellValue = cell.getValueData(); oFirstCellRow = cell.nRow; oFirstCellCol = cell.nCol; } if(nRow0 == nRowStart && nCol0 == nColStart) oLeftTopCellStyle = cell.getStyle(); }); //правила работы с гиперссылками во время merge(отличются от Excel в случаем областей, например hyperlink: C3:D3 мержим C2:C3) // 1)оставляем все ссылки, которые не полностью лежат в merge области // 2)оставляем многоклеточные ссылки, top граница которых совпадает с top границей merge области, а высота merge > 1 или совпадает с высотой области merge // 3)оставляем и переносим в первую ячейку одну одноклеточную ссылку, если она находится в первой ячейке с данными var aHyperlinks = this.worksheet.hyperlinkManager.get(oBBox); var aHyperlinksToRestore = []; for(var i = 0, length = aHyperlinks.inner.length; i < length; i++) { var elem = aHyperlinks.inner[i]; if(oFirstCellRow == elem.bbox.r1 && oFirstCellCol == elem.bbox.c1 && elem.bbox.r1 == elem.bbox.r2 && elem.bbox.c1 == elem.bbox.c2) { var oNewHyperlink = elem.data.clone(); oNewHyperlink.Ref.setOffset({offsetCol:oBBox.c1 - oFirstCellCol, offsetRow:oBBox.r1 - oFirstCellRow}); aHyperlinksToRestore.push(oNewHyperlink); } else if( oBBox.r1 == elem.bbox.r1 && (elem.bbox.r1 != elem.bbox.r2 || (elem.bbox.c1 != elem.bbox.c2 && oBBox.r1 == oBBox.r2))) aHyperlinksToRestore.push(elem.data); } this.cleanAll(); //восстанавливаем hyperlink for(var i = 0, length = aHyperlinksToRestore.length; i < length; i++) { var elem = aHyperlinksToRestore[i]; this.worksheet.hyperlinkManager.add(elem.Ref.getBBox0(), elem); } var oTargetStyle = null; if(null != oFirstCellValue && null != oFirstCellRow && null != oFirstCellCol) { if(null != oFirstCellStyle) oTargetStyle = oFirstCellStyle.clone(); var oLeftTopCell = this.worksheet._getCell(oBBox.r1, oBBox.c1); oLeftTopCell.setValueData(oFirstCellValue); if(null != oFirstCellHyperlink) { var oLeftTopRange = this.worksheet.getCell3(oBBox.r1, oBBox.c1); oLeftTopRange.setHyperlink(oFirstCellHyperlink, true); } } else if(null != oLeftTopCellStyle) oTargetStyle = oLeftTopCellStyle.clone(); //убираем бордеры if(null != oTargetStyle) { if(null != oTargetStyle.border) oTargetStyle.border = null; } else if(null != oLeftBorder || null != oTopBorder || null != oRightBorder || null != oBottomBorder) oTargetStyle = new AscCommonExcel.CellXfs(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { fSetProperty = this._setPropertyNoEmpty; oTargetStyle = null } fSetProperty.call(this, function(row){ if(null == oTargetStyle) row.setStyle(null); else { var oNewStyle = oTargetStyle.clone(); if(row.index == oBBox.r1 && null != oTopBorder) { oNewStyle.border = new Border(); oNewStyle.border.t = oTopBorder.clone(); } else if(row.index == oBBox.r2 && null != oBottomBorder) { oNewStyle.border = new Border(); oNewStyle.border.b = oBottomBorder.clone(); } row.setStyle(oNewStyle); } },function(col){ if(null == oTargetStyle) col.setStyle(null); else { var oNewStyle = oTargetStyle.clone(); if(col.index == oBBox.c1 && null != oLeftBorder) { oNewStyle.border = new Border(); oNewStyle.border.l = oLeftBorder.clone(); } else if(col.index == oBBox.c2 && null != oRightBorder) { oNewStyle.border = new Border(); oNewStyle.border.r = oRightBorder.clone(); } col.setStyle(oNewStyle); } }, function(cell, nRow, nCol, nRowStart, nColStart){ //важно установить именно здесь, чтобы ячейка не удалилась после применения стилей. if(null == oTargetStyle) cell.setStyle(null); else { var oNewStyle = oTargetStyle.clone(); if(oBBox.r1 == nRow && oBBox.c1 == nCol) { if(null != oLeftBorder || null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder) || (oBBox.c1 == oBBox.c2 && null != oRightBorder)) { oNewStyle.border = new Border(); if(null != oLeftBorder) oNewStyle.border.l = oLeftBorder.clone(); if(null != oTopBorder) oNewStyle.border.t = oTopBorder.clone(); if(oBBox.r1 == oBBox.r2 && null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); if(oBBox.c1 == oBBox.c2 && null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); } } else if(oBBox.r1 == nRow && oBBox.c2 == nCol) { if(null != oRightBorder || null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder)) { oNewStyle.border = new Border(); if(null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); if(null != oTopBorder) oNewStyle.border.t = oTopBorder.clone(); if(oBBox.r1 == oBBox.r2 && null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); } } else if(oBBox.r2 == nRow && oBBox.c1 == nCol) { if(null != oLeftBorder || null != oBottomBorder || (oBBox.c1 == oBBox.c2 && null != oRightBorder)) { oNewStyle.border = new Border(); if(null != oLeftBorder) oNewStyle.border.l = oLeftBorder.clone(); if(null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); if(oBBox.c1 == oBBox.c2 && null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); } } else if(oBBox.r2 == nRow && oBBox.c2 == nCol) { if(null != oRightBorder || null != oBottomBorder) { oNewStyle.border = new Border(); if(null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); if(null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); } } else if(oBBox.r1 == nRow) { if(null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder)) { oNewStyle.border = new Border(); if(null != oTopBorder) oNewStyle.border.t = oTopBorder.clone(); if(oBBox.r1 == oBBox.r2 && null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); } } else if(oBBox.r2 == nRow) { if(null != oBottomBorder) { oNewStyle.border = new Border(); oNewStyle.border.b = oBottomBorder.clone(); } } else if(oBBox.c1 == nCol) { if(null != oLeftBorder || (oBBox.c1 == oBBox.c2 && null != oRightBorder)) { oNewStyle.border = new Border(); if(null != oLeftBorder) oNewStyle.border.l = oLeftBorder.clone(); if(oBBox.c1 == oBBox.c2 && null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); } } else if(oBBox.c2 == nCol) { if(null != oRightBorder) { oNewStyle.border = new Border(); oNewStyle.border.r = oRightBorder.clone(); } } cell.setStyle(oNewStyle); } }); if(type == Asc.c_oAscMergeOptions.MergeCenter) this.setAlignHorizontal("center"); if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) this.worksheet.mergeManager.add(this.bbox, 1); History.EndTransaction(); }; Range.prototype.unmerge=function(bOnlyInRange){ History.Create_NewPoint(); History.StartTransaction(); if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) this.worksheet.mergeManager.remove(this.bbox); History.EndTransaction(); }; Range.prototype._getHyperlinks=function(){ var nRangeType = this._getRangeType(); var result = []; var oThis = this; if(c_oRangeType.Range == nRangeType) { var oTempRows = {}; var fAddToTempRows = function(oTempRows, bbox, data){ if(null != bbox) { for(var i = bbox.r1; i <= bbox.r2; i++) { var row = oTempRows[i]; if(null == row) { row = {}; oTempRows[i] = row; } for(var j = bbox.c1; j <= bbox.c2; j++) { var cell = row[j]; if(null == cell) row[j] = data; } } } }; //todo возможно надо сделать оптимизацию для скрытых строк var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(var i = 0, length = aHyperlinks.all.length; i < length; i++) { var hyp = aHyperlinks.all[i]; var hypBBox = hyp.bbox.intersectionSimple(this.bbox); fAddToTempRows(oTempRows, hypBBox, hyp.data); //расширяем гиперссылки на merge ячейках var aMerged = this.worksheet.mergeManager.get(hyp.bbox); for(var j = 0, length2 = aMerged.all.length; j < length2; j++) { var merge = aMerged.all[j]; var mergeBBox = merge.bbox.intersectionSimple(this.bbox); fAddToTempRows(oTempRows, mergeBBox, hyp.data); } } //формируем результат for(var i in oTempRows) { var nRowIndex = i - 0; var row = oTempRows[i]; for(var j in row) { var nColIndex = j - 0; var oCurHyp = row[j]; result.push({hyperlink: oCurHyp, col: nColIndex, row: nRowIndex}); } } } return result; }; Range.prototype.getHyperlink=function(){ var aHyperlinks = this._getHyperlinks(); if(null != aHyperlinks && aHyperlinks.length > 0) return aHyperlinks[0].hyperlink; return null; }; Range.prototype.getHyperlinks=function(){ return this._getHyperlinks(); }; Range.prototype.setHyperlinkOpen=function(val){ if(null != val && false == val.isValid()) return; this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val); }; Range.prototype.setHyperlink=function(val, bWithoutStyle){ if(null != val && false == val.isValid()) return; //проверяем, может эта ссылка уже существует var i, length, hyp; var bExist = false; var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(i = 0, length = aHyperlinks.all.length; i < length; i++) { hyp = aHyperlinks.all[i]; if(hyp.data.isEqual(val)) { bExist = true; break; } } if(false == bExist) { History.Create_NewPoint(); History.StartTransaction(); if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) { //удаляем ссылки с тем же адресом for(i = 0, length = aHyperlinks.all.length; i < length; i++) { hyp = aHyperlinks.all[i]; if(hyp.bbox.isEqual(this.bbox)) this.worksheet.hyperlinkManager.removeElement(hyp); } } //todo перейти на CellStyle if(true != bWithoutStyle) { var oHyperlinkFont = new AscCommonExcel.Font(); oHyperlinkFont.fn = this.worksheet.workbook.getDefaultFont(); oHyperlinkFont.fs = this.worksheet.workbook.getDefaultSize(); oHyperlinkFont.u = Asc.EUnderline.underlineSingle; oHyperlinkFont.c = AscCommonExcel.g_oColorManager.getThemeColor(AscCommonExcel.g_nColorHyperlink); this.setFont(oHyperlinkFont); } if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val); History.EndTransaction(); } }; Range.prototype.removeHyperlink = function (val, removeStyle) { var bbox = this.bbox; var elem = null; if(null != val) { bbox = val.Ref.getBBox0(); elem = new RangeDataManagerElem(bbox, val); } if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) { History.Create_NewPoint(); History.StartTransaction(); var oChangeParam = { removeStyle: removeStyle }; if(null != elem) this.worksheet.hyperlinkManager.removeElement(elem, oChangeParam); else this.worksheet.hyperlinkManager.remove(bbox, !bbox.isOneCell(), oChangeParam); History.EndTransaction(); } }; Range.prototype.deleteCellsShiftUp=function(preDeleteAction){ return this._shiftUpDown(true, preDeleteAction); }; Range.prototype.addCellsShiftBottom=function(displayNameFormatTable){ return this._shiftUpDown(false, null, displayNameFormatTable); }; Range.prototype.addCellsShiftRight=function(displayNameFormatTable){ return this._shiftLeftRight(false, null,displayNameFormatTable); }; Range.prototype.deleteCellsShiftLeft=function(preDeleteAction){ return this._shiftLeftRight(true, preDeleteAction); }; Range.prototype._canShiftLeftRight=function(bLeft){ var aColsToDelete = [], aCellsToDelete = []; var oBBox = this.bbox; var nRangeType = this._getRangeType(oBBox); if(c_oRangeType.Range != nRangeType && c_oRangeType.Col != nRangeType) return null; var nWidth = oBBox.c2 - oBBox.c1 + 1; if(!bLeft && !this.worksheet.workbook.bUndoChanges && !this.worksheet.workbook.bRedoChanges){ var rangeEdge = this.worksheet.getRange3(oBBox.r1, gc_nMaxCol0 - nWidth + 1, oBBox.r2, gc_nMaxCol0); var aMerged = this.worksheet.mergeManager.get(rangeEdge.bbox); if(aMerged.all.length > 0) return null; var aHyperlink = this.worksheet.hyperlinkManager.get(rangeEdge.bbox); if(aHyperlink.all.length > 0) return null; var bError = rangeEdge._setPropertyNoEmpty(null, function(col){ if(null != col){ if(null != col && null != col.xfs && null != col.xfs.fill && null != col.xfs.fill.getRgbOrNull()) return true; aColsToDelete.push(col); } }, function(cell){ if(null != cell){ if(null != cell.xfs && null != cell.xfs.fill && null != cell.xfs.fill.getRgbOrNull()) return true; if(!cell.isEmptyText()) return true; aCellsToDelete.push(cell); } }); if(bError) return null; } return {aColsToDelete: aColsToDelete, aCellsToDelete: aCellsToDelete}; }; Range.prototype._shiftLeftRight=function(bLeft, preDeleteAction, displayNameFormatTable){ var canShiftRes = this._canShiftLeftRight(bLeft); if(null === canShiftRes) return false; if (preDeleteAction) preDeleteAction(); //удаляем крайние колонки и ячейки var i, length, colIndex; for(i = 0, length = canShiftRes.aColsToDelete.length; i < length; ++i){ colIndex = canShiftRes.aColsToDelete[i].index; this.worksheet._removeCols(colIndex, colIndex); } for(i = 0, length = canShiftRes.aCellsToDelete.length; i < length; ++i) this.worksheet._removeCell(null, null, canShiftRes.aCellsToDelete[i]); var oBBox = this.bbox; var nWidth = oBBox.c2 - oBBox.c1 + 1; var nRangeType = this._getRangeType(oBBox); var mergeManager = this.worksheet.mergeManager; this.worksheet.workbook.lockDraw(); //todo вставить предупреждение, что будет unmerge History.Create_NewPoint(); History.StartTransaction(); var oShiftGet = null; if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; oShiftGet = mergeManager.shiftGet(this.bbox, true); var aMerged = oShiftGet.elems; if(null != aMerged.outer && aMerged.outer.length > 0) { var bChanged = false; for(i = 0, length = aMerged.outer.length; i < length; i++) { var elem = aMerged.outer[i]; if(!(elem.bbox.c1 < oShiftGet.bbox.c1 && oShiftGet.bbox.r1 <= elem.bbox.r1 && elem.bbox.r2 <= oShiftGet.bbox.r2)) { mergeManager.removeElement(elem); bChanged = true; } } if(bChanged) oShiftGet = null; } History.LocalChange = false; } //сдвигаем ячейки if(bLeft) { if(c_oRangeType.Range == nRangeType) this.worksheet._shiftCellsLeft(oBBox); else this.worksheet._removeCols(oBBox.c1, oBBox.c2); } else { if(c_oRangeType.Range == nRangeType) this.worksheet._shiftCellsRight(oBBox, displayNameFormatTable); else this.worksheet._insertColsBefore(oBBox.c1, nWidth); } if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; mergeManager.shift(this.bbox, !bLeft, true, oShiftGet); this.worksheet.hyperlinkManager.shift(this.bbox, !bLeft, true); History.LocalChange = false; } History.EndTransaction(); this.worksheet.workbook.unLockDraw(); this.worksheet.workbook.buildRecalc(); return true; }; Range.prototype._canShiftUpDown=function(bUp){ var aRowsToDelete = [], aCellsToDelete = []; var oBBox = this.bbox; var nRangeType = this._getRangeType(oBBox); if(c_oRangeType.Range != nRangeType && c_oRangeType.Row != nRangeType) return null; var nHeight = oBBox.r2 - oBBox.r1 + 1; if(!bUp && !this.worksheet.workbook.bUndoChanges && !this.worksheet.workbook.bRedoChanges){ var rangeEdge = this.worksheet.getRange3(gc_nMaxRow0 - nHeight + 1, oBBox.c1, gc_nMaxRow0, oBBox.c2); var aMerged = this.worksheet.mergeManager.get(rangeEdge.bbox); if(aMerged.all.length > 0) return null; var aHyperlink = this.worksheet.hyperlinkManager.get(rangeEdge.bbox); if(aHyperlink.all.length > 0) return null; var bError = rangeEdge._setPropertyNoEmpty(function(row){ if(null != row){ if(null != row.xfs && null != row.xfs.fill && null != row.xfs.fill.getRgbOrNull()) return true; aRowsToDelete.push(row); } }, null, function(cell){ if(null != cell){ if(null != cell.xfs && null != cell.xfs.fill && null != cell.xfs.fill.getRgbOrNull()) return true; if(!cell.isEmptyText()) return true; aCellsToDelete.push(cell); } }); if(bError) return null; } return {aRowsToDelete: aRowsToDelete, aCellsToDelete: aCellsToDelete}; }; Range.prototype._shiftUpDown = function (bUp, preDeleteAction, displayNameFormatTable) { var canShiftRes = this._canShiftUpDown(bUp); if(null === canShiftRes) return false; if (preDeleteAction) preDeleteAction(); //удаляем крайние колонки и ячейки var i, length, rowIndex; for(i = 0, length = canShiftRes.aRowsToDelete.length; i < length; ++i){ rowIndex = canShiftRes.aRowsToDelete[i].index; this.worksheet._removeRows(rowIndex, rowIndex); } for(i = 0, length = canShiftRes.aCellsToDelete.length; i < length; ++i) this.worksheet._removeCell(null, null, canShiftRes.aCellsToDelete[i]); var oBBox = this.bbox; var nHeight = oBBox.r2 - oBBox.r1 + 1; var nRangeType = this._getRangeType(oBBox); var mergeManager = this.worksheet.mergeManager; this.worksheet.workbook.lockDraw(); //todo вставить предупреждение, что будет unmerge History.Create_NewPoint(); History.StartTransaction(); var oShiftGet = null; if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; oShiftGet = mergeManager.shiftGet(this.bbox, false); var aMerged = oShiftGet.elems; if(null != aMerged.outer && aMerged.outer.length > 0) { var bChanged = false; for(i = 0, length = aMerged.outer.length; i < length; i++) { var elem = aMerged.outer[i]; if(!(elem.bbox.r1 < oShiftGet.bbox.r1 && oShiftGet.bbox.c1 <= elem.bbox.c1 && elem.bbox.c2 <= oShiftGet.bbox.c2)) { mergeManager.removeElement(elem); bChanged = true; } } if(bChanged) oShiftGet = null; } History.LocalChange = false; } //сдвигаем ячейки if(bUp) { if(c_oRangeType.Range == nRangeType) this.worksheet._shiftCellsUp(oBBox); else this.worksheet._removeRows(oBBox.r1, oBBox.r2); } else { if(c_oRangeType.Range == nRangeType) this.worksheet._shiftCellsBottom(oBBox, displayNameFormatTable); else this.worksheet._insertRowsBefore(oBBox.r1, nHeight); } if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; mergeManager.shift(this.bbox, !bUp, false, oShiftGet); this.worksheet.hyperlinkManager.shift(this.bbox, !bUp, false); History.LocalChange = false; } History.EndTransaction(); this.worksheet.workbook.unLockDraw(); this.worksheet.workbook.buildRecalc(); return true; }; Range.prototype.setOffset=function(offset){//offset = {offsetCol:intNumber, offsetRow:intNumber} this.bbox.c1 += offset.offsetCol; if( this.bbox.c1 < 0 ) this.bbox.c1 = 0; this.bbox.r1 += offset.offsetRow; if( this.bbox.r1 < 0 ) this.bbox.r1 = 0; this.bbox.c2 += offset.offsetCol; if( this.bbox.c2 < 0 ) this.bbox.c2 = 0; this.bbox.r2 += offset.offsetRow; if( this.bbox.r2 < 0 ) this.bbox.r2 = 0; this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0); this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0); }; Range.prototype.setOffsetFirst=function(offset){//offset = {offsetCol:intNumber, offsetRow:intNumber} this.bbox.c1 += offset.offsetCol; if( this.bbox.c1 < 0 ) this.bbox.c1 = 0; this.bbox.r1 += offset.offsetRow; if( this.bbox.r1 < 0 ) this.bbox.r1 = 0; this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0); }; Range.prototype.setOffsetLast=function(offset){//offset = {offsetCol:intNumber, offsetRow:intNumber} this.bbox.c2 += offset.offsetCol; if( this.bbox.c2 < 0 ) this.bbox.c2 = 0; this.bbox.r2 += offset.offsetRow; if( this.bbox.r2 < 0 ) this.bbox.r2 = 0; this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0); }; Range.prototype.intersect=function(range){ var oBBox1 = this.bbox; var oBBox2 = range.bbox; var r1 = Math.max(oBBox1.r1, oBBox2.r1); var c1 = Math.max(oBBox1.c1, oBBox2.c1); var r2 = Math.min(oBBox1.r2, oBBox2.r2); var c2 = Math.min(oBBox1.c2, oBBox2.c2); if(r1 <= r2 && c1 <= c2) return this.worksheet.getRange3(r1, c1, r2, c2); return null; }; Range.prototype.cleanCache=function(){ this._setPropertyNoEmpty(null,null,function(cell, nRow0, nCol0, nRowStart, nColStart){ cell.cleanCache(); }); }; Range.prototype.cleanFormat=function(){ History.Create_NewPoint(); History.StartTransaction(); this.unmerge(); this._setPropertyNoEmpty(function(row){ row.setStyle(null); // if(row.isEmpty()) // row.Remove(); },function(col){ col.setStyle(null); // if(col.isEmpty()) // col.Remove(); },function(cell, nRow0, nCol0, nRowStart, nColStart){ cell.setStyle(null); // if(cell.isEmpty()) // cell.Remove(); }); History.EndTransaction(); }; Range.prototype.cleanText=function(){ History.Create_NewPoint(); History.StartTransaction(); this._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){ cell.setValue(""); // if(cell.isEmpty()) // cell.Remove(); }); History.EndTransaction(); }; Range.prototype.cleanAll=function(){ History.Create_NewPoint(); History.StartTransaction(); this.unmerge(); //удаляем только гиперссылки, которые полностью лежат в области var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(var i = 0, length = aHyperlinks.inner.length; i < length; ++i) this.removeHyperlink(aHyperlinks.inner[i].data); var oThis = this; this._setPropertyNoEmpty(function(row){ row.setStyle(null); // if(row.isEmpty()) // row.Remove(); },function(col){ col.setStyle(null); // if(col.isEmpty()) // col.Remove(); },function(cell, nRow0, nCol0, nRowStart, nColStart){ oThis.worksheet._removeCell(nRow0, nCol0); }); this.worksheet.workbook.buildRecalc(); History.EndTransaction(); }; Range.prototype.cleanHyperlinks=function(){ History.Create_NewPoint(); History.StartTransaction(); //удаляем только гиперссылки, которые полностью лежат в области var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(var i = 0, length = aHyperlinks.inner.length; i < length; ++i) this.removeHyperlink(aHyperlinks.inner[i].data); History.EndTransaction(); }; Range.prototype.sort=function(nOption, nStartCol, colorText, colorFill){ //todo горизонтальная сортировка var aMerged = this.worksheet.mergeManager.get(this.bbox); if(aMerged.outer.length > 0 || (aMerged.inner.length > 0 && null == _isSameSizeMerged(this.bbox, aMerged.inner))) return null; var nMergedHeight = 1; if(aMerged.inner.length > 0) { var merged = aMerged.inner[0]; nMergedHeight = merged.bbox.r2 - merged.bbox.r1 + 1; //меняем nStartCol, потому что приходит колонка той ячейки, на которой начали выделение nStartCol = merged.bbox.c1; } this.worksheet.workbook.lockDraw(); var isSortColor = !!(colorText || colorFill); var oRes = null; var oThis = this; var bAscent = false; if(nOption == AscCommonExcel.c_oAscSortOptions.Ascending) bAscent = true; var nRowFirst0 = this.bbox.r1; var nRowLast0 = this.bbox.r2; var nColFirst0 = this.bbox.c1; var nColLast0 = this.bbox.c2; var bWholeCol = false; var bWholeRow = false; if(0 == nRowFirst0 && gc_nMaxRow0 == nRowLast0) bWholeCol = true; if(0 == nColFirst0 && gc_nMaxCol0 == nColLast0) bWholeRow = true; var oRangeCol = this.worksheet.getRange(new CellAddress(nRowFirst0, nStartCol, 0), new CellAddress(nRowLast0, nStartCol, 0)); var nLastRow0 = 0; var nLastCol0 = nColLast0; if(true == bWholeRow) { nLastCol0 = 0; this._foreachRowNoEmpty(function(){}, function(cell){ var nCurCol0 = cell.nCol; if(nCurCol0 > nLastCol0) nLastCol0 = nCurCol0; }); } //собираем массив обьектов для сортировки var aSortElems = []; var aHiddenRow = {}; var fAddSortElems = function(oCell, nRow0, nCol0,nRowStart0, nColStart0){ //не сортируем сткрытие строки var row = oThis.worksheet._getRowNoEmpty(nRow0); if(null != row) { if(0 != (AscCommonExcel.g_nRowFlag_hd & row.flags)) aHiddenRow[nRow0] = 1; else { if(nLastRow0 < nRow0) nLastRow0 = nRow0; var val = oCell.getValueWithoutFormat(); //for sort color var colorFillCell, colorsTextCell = null; if(colorFill) { var styleCell = oCell.getStyle(); colorFillCell = styleCell !== null ? styleCell.fill : null; } else if(colorText) { var value2 = oCell.getValue2(); for(var n = 0; n < value2.length; n++) { colorsTextCell.push(value2[n].c); } } var nNumber = null; var sText = null; if("" != val) { var nVal = val - 0; if(nVal == val) nNumber = nVal; else sText = val; aSortElems.push({row: nRow0, num: nNumber, text: sText, colorFill: colorFillCell, colorsText: colorsTextCell}); } else if(isSortColor) { aSortElems.push({row: nRow0, num: nNumber, text: sText, colorFill: colorFillCell, colorsText: colorsTextCell}); } } } }; if(nColFirst0 == nStartCol) { while(0 == aSortElems.length && nStartCol <= nLastCol0) { if(false == bWholeCol) oRangeCol._foreachNoEmpty(fAddSortElems); else oRangeCol._foreachColNoEmpty(null, fAddSortElems); if(0 == aSortElems.length) { nStartCol++; oRangeCol = this.worksheet.getRange(new CellAddress(nRowFirst0, nStartCol, 0), new CellAddress(nRowLast0, nStartCol, 0)); } } } else { if(false == bWholeCol) oRangeCol._foreachNoEmpty(fAddSortElems); else oRangeCol._foreachColNoEmpty(null, fAddSortElems); } function strcmp ( str1, str2 ) { return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) ); } //color sort var colorFillCmp = function(color1, color2) { var res = false; if(colorFill) { res = color1 !== null && color2 !== null && color1.isEqual(color2) === true ? true : false; } else if(colorText && color1 && color1.length) { for(var n = 0; n < color1.length; n++) { if(color1[n] && color1[n].isEqual(color2)) { res = true; break; } } } return res; }; if(isSortColor) { var newArrayNeedColor = []; var newArrayAnotherColor = []; var sortColor = colorText ? colorText : colorFill; for(var i = 0; i < aSortElems.length; i++) { var color = colorFill ? aSortElems[i].colorFill : aSortElems[i].colorText; if(colorFillCmp(color, sortColor)) { newArrayNeedColor.push(aSortElems[i]); } else { newArrayAnotherColor.push(aSortElems[i]); } } aSortElems = newArrayAnotherColor.concat(newArrayNeedColor); } else { aSortElems.sort(function(a, b){ var res = 0; if(null != a.text) { if(null != b.text) res = strcmp(a.text.toUpperCase(), b.text.toUpperCase()); else res = 1; } else if(null != a.num) { if(null != b.num) res = a.num - b.num; else res = -1; } if(0 == res) res = a.row - b.row; else if(!bAscent) res = -res; return res; }); } //проверяем что это не пустая операция var aSortData = []; var nHiddenCount = 0; var oFromArray = {}; var nRowMax = 0; var nRowMin = gc_nMaxRow0; var nToMax = 0; for(var i = 0, length = aSortElems.length; i < length; ++i) { var item = aSortElems[i]; var nNewIndex = i * nMergedHeight + nRowFirst0 + nHiddenCount; while(null != aHiddenRow[nNewIndex]) { nHiddenCount++; nNewIndex = i * nMergedHeight + nRowFirst0 + nHiddenCount; } var oNewElem = new UndoRedoData_FromToRowCol(true, item.row, nNewIndex); oFromArray[item.row] = 1; if(nRowMax < item.row) nRowMax = item.row; if(nRowMax < nNewIndex) nRowMax = nNewIndex; if(nRowMin > item.row) nRowMin = item.row; if(nRowMin > nNewIndex) nRowMin = nNewIndex; if(nToMax < nNewIndex) nToMax = nNewIndex; if(oNewElem.from != oNewElem.to) aSortData.push(oNewElem); } if(aSortData.length > 0) { //добавляем индексы перехода пустых ячеек(нужно для сортировки комментариев) for(var i = nRowMin; i <= nRowMax; ++i) { if(null == oFromArray[i] && null == aHiddenRow[i]) { var nFrom = i; var nTo = ++nToMax; while(null != aHiddenRow[nTo]) nTo = ++nToMax; if(nFrom != nTo) { var oNewElem = new UndoRedoData_FromToRowCol(true, nFrom, nTo); aSortData.push(oNewElem); } } } History.Create_NewPoint(); var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(nColFirst0, nRowFirst0, nLastCol0, nLastRow0); History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } var oUndoRedoBBox = new UndoRedoData_BBox({r1:nRowFirst0, c1:nColFirst0, r2:nLastRow0, c2:nLastCol0}); oRes = new AscCommonExcel.UndoRedoData_SortData(oUndoRedoBBox, aSortData); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Sort, this.worksheet.getId(), new Asc.Range(0, nRowFirst0, gc_nMaxCol0, nLastRow0), oRes); this._sortByArray(oUndoRedoBBox, aSortData); } this.worksheet.workbook.unLockDraw(); this.worksheet.workbook.buildRecalc(); return oRes; }; Range.prototype._sortByArray=function(oBBox, aSortData, bUndo){ var rec = {length:0}; var oSortedIndexes = {}; for(var i = 0, length = aSortData.length; i < length; ++i) { var item = aSortData[i]; var nFrom = item.from; var nTo = item.to; if(true == this.worksheet.workbook.bUndoChanges) { nFrom = item.to; nTo = item.from; } oSortedIndexes[nFrom] = nTo; } //сортируются только одинарные гиперссылки, все неодинарные оставляем var aSortedHyperlinks = []; if(false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(var i = 0, length = aHyperlinks.inner.length; i < length; i++) { var elem = aHyperlinks.inner[i]; var hyp = elem.data; if(hyp.Ref.isOneCell()) { var nFrom = elem.bbox.r1; var nTo = oSortedIndexes[nFrom]; if(null != nTo) { //удаляем ссылки, а не перемеаем, чтобы не было конфликтов(например в случае если все ячейки имеют ссылки и их надо передвинуть) var oTempBBox = hyp.Ref.getBBox0(); this.worksheet.hyperlinkManager.removeElement(new RangeDataManagerElem(oTempBBox, hyp)); var oNewHyp = hyp.clone(); oNewHyp.Ref.setOffset({offsetCol: 0, offsetRow: nTo - nFrom}); aSortedHyperlinks.push(oNewHyp); } } } History.LocalChange = false; } //окончательно устанавливаем ячейки var nColFirst0 = oBBox.c1; var nLastCol0 = oBBox.c2; for(var i = nColFirst0; i <= nLastCol0; ++i) { //запоминаем ячейки в которые уже что-то передвинули, чтобы не потерять их var oTempCellsTo = {}; for(var j in oSortedIndexes) { var nIndexFrom = j - 0; var nIndexTo = oSortedIndexes[j]; var shift = nIndexTo - nIndexFrom; var rowFrom = this.worksheet._getRow(nIndexFrom); var rowTo = this.worksheet._getRow(nIndexTo); var oCurCell; if(oTempCellsTo.hasOwnProperty(nIndexFrom)) oCurCell = oTempCellsTo[nIndexFrom]; else{ oCurCell = rowFrom.c[i]; delete rowFrom.c[i]; } oTempCellsTo[nIndexTo] = rowTo.c[i]; if(null != oCurCell) { var lastName = oCurCell.getName(); oCurCell.moveVer(shift); rowTo.c[i] = oCurCell; if(oCurCell.sFormula) { var sNewName = oCurCell.getName(); oCurCell.setFormula(oCurCell.formulaParsed.changeOffset({offsetCol:0, offsetRow:shift}).assemble());//получаем новую формулу, путем сдвига входящих в нее ссылок на ячейки на offsetCol и offsetRow. не путать с shiftCells - меняет одну конкретную ячейку в формуле, changeOffset - меняет оффсет для всех входящих в формулу ячеек. this.worksheet.workbook.dependencyFormulas.deleteMasterNodes2( this.worksheet.Id, lastName );//разрываем ссылки между старой ячейкой и ведущими ячейками для нее. addToArrRecalc(this.worksheet.getId(), oCurCell); } } else { if(null != rowTo.c[i]) { //здесь достаточно простого delete, потому что на самом деле в функции ячейки только меняются местами, удаления не происходит delete rowTo.c[i]; } } } } var aNodes = this.worksheet.workbook.dependencyFormulas.getInRange( this.worksheet.Id, new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2) ); if(aNodes && aNodes.length > 0) { for(var i = 0, length = aNodes.length; i < length; ++i) { var node = aNodes[i]; this.worksheet.workbook.needRecalc.nodes[ node.nodeId ] = [ node.sheetId, node.cellId ]; this.worksheet.workbook.needRecalc.length++; } } if (!this.worksheet.workbook.lockCounter) this.worksheet.workbook.sortDependency(); if(false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; //восстанавливаем удаленые гиперссылки if(aSortedHyperlinks.length > 0) { for(var i = 0, length = aSortedHyperlinks.length; i < length; i++) { var hyp = aSortedHyperlinks[i]; this.worksheet.hyperlinkManager.add(hyp.Ref.getBBox0(), hyp); } } History.LocalChange = false; } }; function _isSameSizeMerged(bbox, aMerged) { var oRes = null; var nWidth = null; var nHeight = null; for(var i = 0, length = aMerged.length; i < length; i++) { var mergedBBox = aMerged[i].bbox; var nCurWidth = mergedBBox.c2 - mergedBBox.c1 + 1; var nCurHeight = mergedBBox.r2 - mergedBBox.r1 + 1; if(null == nWidth || null == nHeight) { nWidth = nCurWidth; nHeight = nCurHeight; } else if(nCurWidth != nWidth || nCurHeight != nHeight) { nWidth = null; nHeight = null; break; } } if(null != nWidth && null != nHeight) { //проверяем что merge ячеки полностью заполняют область var nBBoxWidth = bbox.c2 - bbox.c1 + 1; var nBBoxHeight = bbox.r2 - bbox.r1 + 1; if(nBBoxWidth == nWidth || nBBoxHeight == nHeight) { var bRes = false; var aRowColTest = null; if(nBBoxWidth == nWidth && nBBoxHeight == nHeight) bRes = true; else if(nBBoxWidth == nWidth) { aRowColTest = new Array(nBBoxHeight); for(var i = 0, length = aMerged.length; i < length; i++) { var merged = aMerged[i]; for(var j = merged.bbox.r1; j <= merged.bbox.r2; j++) aRowColTest[j - bbox.r1] = 1; } } else if(nBBoxHeight == nHeight) { aRowColTest = new Array(nBBoxWidth); for(var i = 0, length = aMerged.length; i < length; i++) { var merged = aMerged[i]; for(var j = merged.bbox.c1; j <= merged.bbox.c2; j++) aRowColTest[j - bbox.c1] = 1; } } if(null != aRowColTest) { var bExistNull = false; for(var i = 0, length = aRowColTest.length; i < length; i++) { if(null == aRowColTest[i]) { bExistNull = true; break; } } if(!bExistNull) bRes = true; } if(bRes) oRes = {width: nWidth, height: nHeight}; } } return oRes; } function _canPromote(from, wsFrom, to, wsTo, bIsPromote, nWidth, nHeight, bVertical, nIndex) { var oRes = {oMergedFrom: null, oMergedTo: null}; //если надо только удалить внутреннее содержимое не смотрим на замерженость if(!bIsPromote || !((true == bVertical && nIndex >= 0 && nIndex < nHeight) || (false == bVertical && nIndex >= 0 && nIndex < nWidth))) { if(null != to){ var oMergedTo = wsTo.mergeManager.get(to); if(oMergedTo.outer.length > 0) oRes = null; else { var oMergedFrom = wsFrom.mergeManager.get(from); oRes.oMergedFrom = oMergedFrom; if(oMergedTo.inner.length > 0) { oRes.oMergedTo = oMergedTo; if (bIsPromote) { if (oMergedFrom.inner.length > 0) { //merge области должны иметь одинаковый размер var oSizeFrom = _isSameSizeMerged(from, oMergedFrom.inner); var oSizeTo = _isSameSizeMerged(to, oMergedTo.inner); if (!(null != oSizeFrom && null != oSizeTo && oSizeTo.width == oSizeFrom.width && oSizeTo.height == oSizeFrom.height)) oRes = null; } else oRes = null; } } } } } return oRes; } // Подготовка Copy Style function preparePromoteFromTo(from, to) { var bSuccess = true; if (to.isOneCell()) to.setOffsetLast({offsetCol: (from.c2 - from.c1) - (to.c2 - to.c1), offsetRow: (from.r2 - from.r1) - (to.r2 - to.r1)}); if(!from.isIntersect(to)) { var bFromWholeCol = (0 == from.c1 && gc_nMaxCol0 == from.c2); var bFromWholeRow = (0 == from.r1 && gc_nMaxRow0 == from.r2); var bToWholeCol = (0 == to.c1 && gc_nMaxCol0 == to.c2); var bToWholeRow = (0 == to.r1 && gc_nMaxRow0 == to.r2); bSuccess = (bFromWholeCol === bToWholeCol && bFromWholeRow === bToWholeRow); } else bSuccess = false; return bSuccess; } // Перед promoteFromTo обязательно должна быть вызывана функция preparePromoteFromTo function promoteFromTo(from, wsFrom, to, wsTo) { var bVertical = true; var nIndex = 1; //проверяем можно ли осуществить promote var oCanPromote = _canPromote(from, wsFrom, to, wsTo, false, 1, 1, bVertical, nIndex); if(null != oCanPromote) { History.Create_NewPoint(); var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(from.c1, from.r1, from.c2, from.r2); History.SetSelection(oSelection); } var oSelectionRedo = History.GetSelectionRedo(); if(null != oSelectionRedo) { oSelectionRedo = oSelectionRedo.clone(); oSelectionRedo.assign(to.c1, to.r1, to.c2, to.r2); History.SetSelectionRedo(oSelectionRedo); } //удаляем merge ячейки в to(после _canPromote должны остаться только inner) wsTo.mergeManager.remove(to, true); _promoteFromTo(from, wsFrom, to, wsTo, false, oCanPromote, false, bVertical, nIndex); } } Range.prototype.promote=function(bCtrl, bVertical, nIndex){ //todo отдельный метод для promote в таблицах и merge в таблицах var oBBox = this.bbox; var nWidth = oBBox.c2 - oBBox.c1 + 1; var nHeight = oBBox.r2 - oBBox.r1 + 1; var bWholeCol = false; var bWholeRow = false; if(0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2) bWholeCol = true; if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) bWholeRow = true; if((bWholeCol && bWholeRow) || (true == bVertical && bWholeCol) || (false == bVertical && bWholeRow)) return false; var oPromoteAscRange = null; if(0 == nIndex) oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2); else { if(bVertical) { if(nIndex > 0) { if(nIndex >= nHeight) oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r2 + 1, oBBox.c2, oBBox.r1 + nIndex); else oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r2); } else oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r1 - 1); } else { if(nIndex > 0) { if(nIndex >= nWidth) oPromoteAscRange = Asc.Range(oBBox.c2 + 1, oBBox.r1, oBBox.c1 + nIndex, oBBox.r2); else oPromoteAscRange = Asc.Range(oBBox.c1 + nIndex, oBBox.r1, oBBox.c2, oBBox.r2); } else oPromoteAscRange = Asc.Range(oBBox.c1 + nIndex, oBBox.r1, oBBox.c1 - 1, oBBox.r2); } } //проверяем можно ли осуществить promote var oCanPromote = _canPromote(oBBox, this.worksheet, oPromoteAscRange, this.worksheet, true, nWidth, nHeight, bVertical, nIndex); if(null == oCanPromote) return false; History.Create_NewPoint(); var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2); History.SetSelection(oSelection); } var oSelectionRedo = History.GetSelectionRedo(); if(null != oSelectionRedo) { oSelectionRedo = oSelectionRedo.clone(); if(0 == nIndex) oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2); else { if(bVertical) { if(nIndex > 0) { if(nIndex >= nHeight) oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r1 + nIndex); else oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r1 + nIndex - 1); } else oSelectionRedo.assign(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r2); } else { if(nIndex > 0) { if(nIndex >= nWidth) oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c1 + nIndex, oBBox.r2); else oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c1 + nIndex - 1, oBBox.r2); } else oSelectionRedo.assign(oBBox.c1 + nIndex, oBBox.r1, oBBox.c2, oBBox.r2); } } History.SetSelectionRedo(oSelectionRedo); } oFormulaLocaleInfo.Parse = false; oFormulaLocaleInfo.DigitSep = false; _promoteFromTo(oBBox, this.worksheet, oPromoteAscRange, this.worksheet, true, oCanPromote, bCtrl, bVertical, nIndex); oFormulaLocaleInfo.Parse = true; oFormulaLocaleInfo.DigitSep = true; return true; }; function _promoteFromTo(from, wsFrom, to, wsTo, bIsPromote, oCanPromote, bCtrl, bVertical, nIndex) { var wb = wsFrom.workbook; wb.lockDraw(); History.StartTransaction(); var toRange = wsTo.getRange3(to.r1, to.c1, to.r2, to.c2); var fromRange = wsFrom.getRange3(from.r1, from.c1, from.r2, from.c2); var bChangeRowColProp = false; var nLastCol = from.c2; if (0 == from.c1 && gc_nMaxCol0 == from.c2) { var aRowProperties = []; nLastCol = 0; fromRange._foreachRowNoEmpty(function(row){ if(!row.isEmptyProp()) aRowProperties.push({index: row.index - from.r1, prop: row.getHeightProp(), style: row.getStyle()}); }, function(cell){ var nCurCol0 = cell.nCol; if(nCurCol0 > nLastCol) nLastCol = nCurCol0; }); if(aRowProperties.length > 0) { bChangeRowColProp = true; var nCurCount = 0; var nCurIndex = 0; while (true) { for (var i = 0, length = aRowProperties.length; i < length; ++i) { var propElem = aRowProperties[i]; nCurIndex = to.r1 + nCurCount * (from.r2 - from.r1 + 1) + propElem.index; if (nCurIndex > to.r2) break; else{ var row = wsTo._getRow(nCurIndex); if (null != propElem.style) row.setStyle(propElem.style); if (null != propElem.prop) { var oNewProps = propElem.prop; var oOldProps = row.getHeightProp(); if (false === oOldProps.isEqual(oNewProps)) { row.setHeightProp(oNewProps); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, wsTo.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(nCurIndex, true, oOldProps, oNewProps)); } } } } nCurCount++; if (nCurIndex > to.r2) break; } } } var nLastRow = from.r2; if (0 == from.r1 && gc_nMaxRow0 == from.r2) { var aColProperties = []; nLastRow = 0; fromRange._foreachColNoEmpty(function(col){ if(!col.isEmpty()) aColProperties.push({ index: col.index - from.c1, prop: col.getWidthProp(), style: col.getStyle() }); }, function(cell){ var nCurRow0 = cell.nRow; if(nCurRow0 > nLastRow) nLastRow = nCurRow0; }); if (aColProperties.length > 0) { bChangeRowColProp = true; var nCurCount = 0; var nCurIndex = 0; while (true) { for (var i = 0, length = aColProperties.length; i < length; ++i) { var propElem = aColProperties[i]; nCurIndex = to.c1 + nCurCount * (from.c2 - from.c1 + 1) + propElem.index; if (nCurIndex > to.c2) break; else{ var col = wsTo._getCol(nCurIndex); if (null != propElem.style) col.setStyle(propElem.style); if (null != propElem.prop) { var oNewProps = propElem.prop; var oOldProps = col.getWidthProp(); if (false == oOldProps.isEqual(oNewProps)) { col.setWidthProp(oNewProps); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, wsTo.getId(), new Asc.Range(nCurIndex, 0, nCurIndex, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(nCurIndex, false, oOldProps, oNewProps)); } } } } nCurCount++; if (nCurIndex > to.c2) break; } } } if (bChangeRowColProp) wb.handlers.trigger("changeWorksheetUpdate", wsTo.getId()); if(nLastCol != from.c2 || nLastRow != from.r2) { var offset = {offsetCol:nLastCol - from.c2, offsetRow:nLastRow - from.r2}; toRange.setOffsetLast(offset); to = toRange.getBBox0(); fromRange.setOffsetLast(offset); from = fromRange.getBBox0(); } var nWidth = from.c2 - from.c1 + 1; var nHeight = from.r2 - from.r1 + 1; //удаляем текст или все в области для заполнения if(bIsPromote && nIndex >= 0 && ((true == bVertical && nHeight > nIndex) || (false == bVertical && nWidth > nIndex))) { //удаляем только текст в области для заполнения toRange.cleanText(); } else { //удаляем все в области для заполнения if(bIsPromote) toRange.cleanAll(); else toRange.cleanFormat(); //собираем все данные var bReverse = false; if(nIndex < 0) bReverse = true; var oPromoteHelper = new PromoteHelper(bVertical, bReverse, from); fromRange._foreachNoEmpty(function(oCell, nRow0, nCol0, nRowStart0, nColStart0){ if(null != oCell) { var nVal = null; var bDelimiter = false; var sPrefix = null; var bDate = false; if(bIsPromote) { if (!oCell.sFormula) { var sValue = oCell.getValueWithoutFormat(); if("" != sValue) { bDelimiter = true; var nType = oCell.getType(); if(CellValueType.Number == nType || CellValueType.String == nType) { if(CellValueType.Number == nType) nVal = sValue - 0; else { //если текст заканчивается на цифру тоже используем ее var nEndIndex = sValue.length; for(var k = sValue.length - 1; k >= 0; --k) { var sCurChart = sValue[k]; if('0' <= sCurChart && sCurChart <= '9') nEndIndex--; else break; } if(sValue.length != nEndIndex) { sPrefix = sValue.substring(0, nEndIndex); nVal = sValue.substring(nEndIndex) - 0; } } } if(null != oCell.xfs && null != oCell.xfs.num && null != oCell.xfs.num.getFormat()){ var numFormat = oNumFormatCache.get(oCell.xfs.num.getFormat()); if(numFormat.isDateTimeFormat()) bDate = true; } if(null != nVal) bDelimiter = false; } } else bDelimiter = true; } oPromoteHelper.add(nRow0 - nRowStart0, nCol0 - nColStart0, nVal, bDelimiter, sPrefix, bDate, oCell); } }); var bCopy = false; if(bCtrl) bCopy = true; //в случае одной ячейки с числом меняется смысл bCtrl if(1 == nWidth && 1 == nHeight && oPromoteHelper.isOnlyIntegerSequence()) bCopy = !bCopy; oPromoteHelper.finishAdd(bCopy); //заполняем ячейки данными var nStartRow, nEndRow, nStartCol, nEndCol, nColDx, bRowFirst; if(bVertical) { nStartRow = to.c1; nEndRow = to.c2; bRowFirst = false; if(bReverse) { nStartCol = to.r2; nEndCol = to.r1; nColDx = -1; } else { nStartCol = to.r1; nEndCol = to.r2; nColDx = 1; } } else { nStartRow = to.r1; nEndRow = to.r2; bRowFirst = true; if(bReverse) { nStartCol = to.c2; nEndCol = to.c1; nColDx = -1; } else { nStartCol = to.c1; nEndCol = to.c2; nColDx = 1; } } for(var i = nStartRow; i <= nEndRow; i ++) { oPromoteHelper.setIndex(i - nStartRow); for(var j = nStartCol; (nStartCol - j) * (nEndCol - j) <= 0; j += nColDx) { var data = oPromoteHelper.getNext(); if(null != data && (data.oAdditional || (false == bCopy && null != data.nCurValue))) { var oFromCell = data.oAdditional; var oCopyCell = null; if(bRowFirst) oCopyCell = wsTo._getCell(i, j); else oCopyCell = wsTo._getCell(j, i); if(bIsPromote) { if(false == bCopy && null != data.nCurValue) { var sVal = ""; if(null != data.sPrefix) sVal += data.sPrefix; //change javascript NumberDecimalSeparator '.' , to cultural NumberDecimalSeparator sVal += data.nCurValue.toString().replace(/\./g, AscCommon.g_oDefaultCultureInfo.NumberDecimalSeparator); oCopyCell.setValue(sVal); } else if(null != oFromCell) { //копируем полностью if(!oFromCell.formulaParsed){ var DataOld = oCopyCell.getValueData(); oCopyCell.oValue = oFromCell.oValue.clone(); var DataNew = oCopyCell.getValueData(); if(false == DataOld.isEqual(DataNew)) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, wsTo.getId(), new Asc.Range(oCopyCell.nCol, oCopyCell.nRow, oCopyCell.nCol, oCopyCell.nRow), new UndoRedoData_CellSimpleData(oCopyCell.nRow, oCopyCell.nCol, DataOld, DataNew)); //todo // if(oCopyCell.isEmptyTextString()) // wsTo._getHyperlink().remove({r1: oCopyCell.nRow, c1: oCopyCell.nCol, r2: oCopyCell.nRow, c2: oCopyCell.nCol}); } else{ var assemb; var _p_ = new parserFormula(oFromCell.sFormula,oCopyCell.getName(),wsTo); if( _p_.parse() ){ assemb = _p_.changeOffset(oCopyCell.getOffset2(oFromCell.getName())).assemble(); oCopyCell.setValue("="+assemb); } } } } //выставляем стиль после текста, потому что если выставить числовой стиль ячейки 'text', то после этого не применится формула if (null != oFromCell) { oCopyCell.setStyle(oFromCell.getStyle()); if (bIsPromote) oCopyCell.setType(oFromCell.getType()); } } } } if(bIsPromote) { var aNodes = wb.dependencyFormulas.getInRange( wsTo.Id, to ); if(aNodes && aNodes.length > 0) { for(var i = 0, length = aNodes.length; i < length; ++i) { var node = aNodes[i]; wb.needRecalc.nodes[ node.nodeId ] = [ node.sheetId, node.cellId ]; wb.needRecalc.length++; } } } //добавляем замерженые области var nDx = from.c2 - from.c1 + 1; var nDy = from.r2 - from.r1 + 1; var oMergedFrom = oCanPromote.oMergedFrom; if(null != oMergedFrom && oMergedFrom.all.length > 0) { for (var i = to.c1; i <= to.c2; i += nDx) { for (var j = to.r1; j <= to.r2; j += nDy) { for (var k = 0, length3 = oMergedFrom.all.length; k < length3; k++) { var oMergedBBox = oMergedFrom.all[k].bbox; var oNewMerged = Asc.Range(i + oMergedBBox.c1 - from.c1, j + oMergedBBox.r1 - from.r1, i + oMergedBBox.c2 - from.c1, j + oMergedBBox.r2 - from.r1); if(to.contains(oNewMerged.c1, oNewMerged.r1)) { if(to.c2 < oNewMerged.c2) oNewMerged.c2 = to.c2; if(to.r2 < oNewMerged.r2) oNewMerged.r2 = to.r2; if(!oNewMerged.isOneCell()) wsTo.mergeManager.add(oNewMerged, 1); } } } } } if(bIsPromote) { //добавляем ссылки //не как в Excel поддерживаются ссылки на диапазоны var oHyperlinks = wsFrom.hyperlinkManager.get(from); if(oHyperlinks.inner.length > 0) { for (var i = to.c1; i <= to.c2; i += nDx) { for (var j = to.r1; j <= to.r2; j += nDy) { for(var k = 0, length3 = oHyperlinks.inner.length; k < length3; k++){ var oHyperlink = oHyperlinks.inner[k]; var oHyperlinkBBox = oHyperlink.bbox; var oNewHyperlink = Asc.Range(i + oHyperlinkBBox.c1 - from.c1, j + oHyperlinkBBox.r1 - from.r1, i + oHyperlinkBBox.c2 - from.c1, j + oHyperlinkBBox.r2 - from.r1); if (to.containsRange(oNewHyperlink)) wsTo.hyperlinkManager.add(oNewHyperlink, oHyperlink.data.clone()); } } } } } } History.EndTransaction(); wb.unLockDraw(); wb.buildRecalc(); } Range.prototype.createCellOnRowColCross=function(){ var oThis = this; var bbox = this.bbox; var nRangeType = this._getRangeType(bbox); if(c_oRangeType.Row == nRangeType) { this._foreachColNoEmpty(function(col){ if(null != col.xfs) { for(var i = bbox.r1; i <= bbox.r2; ++i) oThis.worksheet._getCell(i, col.index); } }, null); } else if(c_oRangeType.Col == nRangeType) { this._foreachRowNoEmpty(function(row){ if(null != row.xfs) { for(var i = bbox.c1; i <= bbox.c2; ++i) oThis.worksheet._getCell(row.index, i); } }, null); } }; //------------------------------------------------------------------------------------------------- /** * @constructor */ function PromoteHelper(bVerical, bReverse, bbox){ //автозаполнение происходит всегда в правую сторону, поэтому менются индексы в методе add, и это надо учитывать при вызове getNext this.bVerical = bVerical; this.bReverse = bReverse; this.bbox = bbox; this.oDataRow = {}; //для get this.oCurRow = null; this.nCurColIndex = null; this.nRowLength = 0; this.nColLength = 0; if(this.bVerical) { this.nRowLength = this.bbox.c2 - this.bbox.c1 + 1; this.nColLength = this.bbox.r2 - this.bbox.r1 + 1; } else { this.nRowLength = this.bbox.r2 - this.bbox.r1 + 1; this.nColLength = this.bbox.c2 - this.bbox.c1 + 1; } } PromoteHelper.prototype = { add: function(nRow, nCol, nVal, bDelimiter, sPrefix, bDate, oAdditional){ if(this.bVerical) { //транспонируем для удобства var temp = nRow; nRow = nCol; nCol = temp; } if(this.bReverse) nCol = this.nColLength - nCol - 1; var row = this.oDataRow[nRow]; if(null == row) { row = {}; this.oDataRow[nRow] = row; } row[nCol] = {nCol: nCol, nVal: nVal, bDelimiter: bDelimiter, sPrefix: sPrefix, bDate: bDate, oAdditional: oAdditional, oSequence: null, nCurValue: null}; }, isOnlyIntegerSequence: function(){ var bRes = true; var bEmpty = true; for(var i in this.oDataRow) { var row = this.oDataRow[i]; for(var j in row) { var data = row[j]; bEmpty = false; if(!(null != data.nVal && true != data.bDate && null == data.sPrefix)) { bRes = false; break; } } if(!bRes) break; } if(bEmpty) bRes = false; return bRes; }, _promoteSequence: function(aDigits){ // Это коэффициенты линейного приближения (http://office.microsoft.com/ru-ru/excel-help/HP010072685.aspx) // y=a1*x+a0 (где: x=0,1....; y=значения в ячейках; a0 и a1 - это решения приближения функции методом наименьших квадратов // (n+1)*a0 + (x0+x1+....) *a1=(y0+y1+...) // (x0+x1+....)*a0 + (x0*x0+x1*x1+....)*a1=(y0*x0+y1*x1+...) // http://www.exponenta.ru/educat/class/courses/vvm/theme_7/theory.asp var a0 = 0.0; var a1 = 0.0; // Индекс X var nX = 0; if(1 == aDigits.length) { nX = 1; a1 = 1; a0 = aDigits[0].y; } else { // (n+1) var nN = aDigits.length; // (x0+x1+....) var nXi = 0; // (x0*x0+x1*x1+....) var nXiXi = 0; // (y0+y1+...) var dYi = 0.0; // (y0*x0+y1*x1+...) var dYiXi = 0.0; // Цикл по всем строкам for (var i = 0, length = aDigits.length; i < length; ++i) { var data = aDigits[i]; nX = data.x; var dValue = data.y; // Вычисляем значения nXi += nX; nXiXi += nX * nX; dYi += dValue; dYiXi += dValue * nX; } nX++; // Теперь решаем систему уравнений // Общий детерминант var dD = nN * nXiXi - nXi * nXi; // Детерминант первого корня var dD1 = dYi * nXiXi - nXi * dYiXi; // Детерминант второго корня var dD2 = nN * dYiXi - dYi * nXi; a0 = dD1 / dD; a1 = dD2 / dD; } return {a0: a0, a1: a1, nX: nX}; }, _addSequenceToRow : function(nRowIndex, aSortRowIndex, row, aCurSequence){ if(aCurSequence.length > 0) { var oFirstData = aCurSequence[0]; var bCanPromote = true; //если последовательность состоит из одного числа и той же колонке есть еще последовательности, то надо копировать, а не автозаполнять if(1 == aCurSequence.length) { var bVisitRowIndex = false; var oVisitData = null; for(var i = 0, length = aSortRowIndex.length; i < length; i++) { var nCurRowIndex = aSortRowIndex[i]; if(nRowIndex == nCurRowIndex) { bVisitRowIndex = true; if(oVisitData && oFirstData.sPrefix == oVisitData.sPrefix && oFirstData.bDate == oVisitData.bDate) { bCanPromote = false; break; } } else { var oCurRow = this.oDataRow[nCurRowIndex]; if(oCurRow) { var data = oCurRow[oFirstData.nCol]; if(null != data) { if(null != data.nVal) { oVisitData = data; if(bVisitRowIndex) { if(oFirstData.sPrefix == oVisitData.sPrefix && oFirstData.bDate == oVisitData.bDate) bCanPromote = false; break; } } else if(data.bDelimiter) { oVisitData = null; if(bVisitRowIndex) break; } } } } } } if(bCanPromote) { var nMinIndex = null; var nMaxIndex = null; var bValidIndexDif = true; var nPrevX = null; var nPrevVal = null; var nIndexDif = null; var nValueDif = null; //анализируем последовательность, если числа расположены не на одинаковом расстоянии, то считаем их сплошной последовательностью //последовательность с промежутками может быть только целочисленной for(var i = 0, length = aCurSequence.length; i < length; i++) { var data = aCurSequence[i]; var nCurX = data.nCol; if(null == nMinIndex || null == nMaxIndex) nMinIndex = nMaxIndex = nCurX; else { if(nCurX < nMinIndex) nMinIndex = nCurX; if(nCurX > nMaxIndex) nMaxIndex = nCurX; } if(bValidIndexDif) { if(null != nPrevX && null != nPrevVal) { var nCurDif = nCurX - nPrevX; var nCurValDif = data.nVal - nPrevVal; if(null == nIndexDif || null == nCurValDif) { nIndexDif = nCurDif; nValueDif = nCurValDif; } else if(nIndexDif != nCurDif || nValueDif != nCurValDif) { nIndexDif = null; bValidIndexDif = false; } } } nPrevX = nCurX; nPrevVal = data.nVal; } var bWithSpace = false; if(null != nIndexDif) { nIndexDif = Math.abs(nIndexDif); if(nIndexDif > 1) bWithSpace = true; } //заполняем массив с координатами var bExistSpace = false; nPrevX = null; var aDigits = []; for(var i = 0, length = aCurSequence.length; i < length; i++) { var data = aCurSequence[i]; var nCurX = data.nCol; var x = nCurX - nMinIndex; if(null != nIndexDif && nIndexDif > 0) x /= nIndexDif; if(null != nPrevX && nCurX - nPrevX > 1) bExistSpace = true; var y = data.nVal; //даты автозаполняем только по целой части if(data.bDate) y = parseInt(y); aDigits.push({x: x, y: y}); nPrevX = nCurX; } if(aDigits.length > 0) { var oSequence = this._promoteSequence(aDigits); if(1 == aDigits.length && this.bReverse) { //меняем коэффициенты для случая одного числа в последовательности, иначе она в любую сторону будет возрастающей oSequence.a1 *= -1; } var bIsIntegerSequence = oSequence.a1 != parseInt(oSequence.a1); //для дат и чисел с префиксом автозаполняются только целочисленные последовательности if(!((null != oFirstData.sPrefix || true == oFirstData.bDate) && bIsIntegerSequence)) { if(false == bWithSpace && bExistSpace) { for(var i = nMinIndex; i <= nMaxIndex; i++) { var data = row[i]; if(null == data) { data = {nCol: i, nVal: null, bDelimiter: oFirstData.bDelimiter, sPrefix: oFirstData.sPrefix, bDate: oFirstData.bDate, oAdditional: null, oSequence: null, nCurValue: null}; row[i] = data; } data.oSequence = oSequence; } } else { for(var i = 0, length = aCurSequence.length; i < length; i++) { var nCurX = aCurSequence[i].nCol; if(null != nCurX) row[nCurX].oSequence = oSequence; } } } } } } }, finishAdd : function(bCopy){ if(true != bCopy) { var aSortRowIndex = []; for(var i in this.oDataRow) aSortRowIndex.push(i - 0); aSortRowIndex.sort(fSortAscending); for(var i = 0, length = aSortRowIndex.length; i < length; i++) { var nRowIndex = aSortRowIndex[i]; var row = this.oDataRow[nRowIndex]; //собираем информация о последовательностях в row var aSortIndex = []; for(var j in row) aSortIndex.push(j - 0); aSortIndex.sort(fSortAscending); var aCurSequence = []; var oPrevData = null; for(var j = 0, length2 = aSortIndex.length; j < length2; j++) { var nColIndex = aSortIndex[j]; var data = row[nColIndex]; var bAddToSequence = false; if(null != data.nVal) { bAddToSequence = true; if(null != oPrevData && (oPrevData.bDelimiter != data.bDelimiter || oPrevData.sPrefix != data.sPrefix || oPrevData.bDate != data.bDate)) { this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence); aCurSequence = []; oPrevData = null; } oPrevData = data; } else if(data.bDelimiter) { this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence); aCurSequence = []; oPrevData = null; } if(bAddToSequence) aCurSequence.push(data); } this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence); } } }, setIndex: function(index){ if(0 != this.nRowLength && index >= this.nRowLength) index = index % (this.nRowLength); this.oCurRow = this.oDataRow[index]; this.nCurColIndex = 0; }, getNext: function(){ var oRes = null; if(this.oCurRow) { var oRes = this.oCurRow[this.nCurColIndex]; if(null != oRes) { oRes.nCurValue = null; if(null != oRes.oSequence) { var sequence = oRes.oSequence; if(oRes.bDate || null != oRes.sPrefix) oRes.nCurValue = Math.abs(sequence.a1 * sequence.nX + sequence.a0); else oRes.nCurValue = sequence.a1 * sequence.nX + sequence.a0; sequence.nX ++; } } this.nCurColIndex++; if(this.nCurColIndex >= this.nColLength) this.nCurColIndex = 0; } return oRes; } }; function DefinedName(){ this.Name = null; this.Ref = null; this.LocalSheetId = null; this.Hidden = null; this.bTable = false; } //------------------------------------------------------------------------------------------------- /** * @constructor */ function DrawingObjectsManager(worksheet) { this.worksheet = worksheet; } DrawingObjectsManager.prototype.updateChartReferences = function(oldWorksheet, newWorksheet) { AscFormat.ExecuteNoHistory(function(){ this.updateChartReferencesWidthHistory(oldWorksheet, newWorksheet); }, this, []); }; DrawingObjectsManager.prototype.updateChartReferencesWidthHistory = function(oldWorksheet, newWorksheet, bNoRebuildCache) { var aObjects = this.worksheet.Drawings; for (var i = 0; i < aObjects.length; i++) { var graphicObject = aObjects[i].graphicObject; if ( graphicObject.updateChartReferences ) { graphicObject.updateChartReferences(oldWorksheet, newWorksheet, bNoRebuildCache); } } }; DrawingObjectsManager.prototype.rebuildCharts = function(data) { var aObjects = this.worksheet.Drawings; for(var i = 0; i < aObjects.length; ++i) { if(aObjects[i].graphicObject.rebuildSeries) { aObjects[i].graphicObject.rebuildSeries(data); } } }; window['AscCommonExcel'] = window['AscCommonExcel'] || {}; window['AscCommonExcel'].g_nVerticalTextAngle = g_nVerticalTextAngle; window['AscCommonExcel'].oDefaultMetrics = oDefaultMetrics; window['AscCommonExcel'].g_nAllColIndex = g_nAllColIndex; window['AscCommonExcel'].g_nAllRowIndex = g_nAllRowIndex; window['AscCommonExcel'].aStandartNumFormats = aStandartNumFormats; window['AscCommonExcel'].aStandartNumFormatsId = aStandartNumFormatsId; window['AscCommonExcel'].oFormulaLocaleInfo = oFormulaLocaleInfo; window['AscCommonExcel'].DependencyGraph = DependencyGraph; window['AscCommonExcel'].getVertexId = getVertexId; window['AscCommonExcel'].buildDefNameAfterRenameWorksheet = buildDefNameAfterRenameWorksheet; window['AscCommonExcel'].angleFormatToInterface2 = angleFormatToInterface2; window['AscCommonExcel'].angleInterfaceToFormat = angleInterfaceToFormat; window['AscCommonExcel'].Workbook = Workbook; window['AscCommonExcel'].Woorksheet = Woorksheet; window['AscCommonExcel'].Cell = Cell; window['AscCommonExcel'].Range = Range; window['AscCommonExcel'].preparePromoteFromTo = preparePromoteFromTo; window['AscCommonExcel'].promoteFromTo = promoteFromTo; window['AscCommonExcel'].DefinedName = DefinedName; })(window);
cell/model/Workbook.js
"use strict"; (function(window, undefined){ // Import var g_memory = AscFonts.g_memory; var CellValueType = AscCommon.CellValueType; var c_oAscBorderStyles = AscCommon.c_oAscBorderStyles; var fSortAscending = AscCommon.fSortAscending; var fSortDescending = AscCommon.fSortDescending; var parserHelp = AscCommon.parserHelp; var oNumFormatCache = AscCommon.oNumFormatCache; var gc_nMaxRow0 = AscCommon.gc_nMaxRow0; var gc_nMaxCol0 = AscCommon.gc_nMaxCol0; var g_oCellAddressUtils = AscCommon.g_oCellAddressUtils; var CellAddress = AscCommon.CellAddress; var isRealObject = AscCommon.isRealObject; var History = AscCommon.History; var UndoRedoItemSerializable = AscCommonExcel.UndoRedoItemSerializable; var UndoRedoData_CellSimpleData = AscCommonExcel.UndoRedoData_CellSimpleData; var UndoRedoData_CellValueData = AscCommonExcel.UndoRedoData_CellValueData; var UndoRedoData_FromToRowCol = AscCommonExcel.UndoRedoData_FromToRowCol; var UndoRedoData_FromTo = AscCommonExcel.UndoRedoData_FromTo; var UndoRedoData_IndexSimpleProp = AscCommonExcel.UndoRedoData_IndexSimpleProp; var UndoRedoData_BBox = AscCommonExcel.UndoRedoData_BBox; var UndoRedoData_SheetAdd = AscCommonExcel.UndoRedoData_SheetAdd; var UndoRedoData_SheetPositions = AscCommonExcel.UndoRedoData_SheetPositions; var UndoRedoData_DefinedNames = AscCommonExcel.UndoRedoData_DefinedNames; var UndoRedoData_DefinedNamesChange = AscCommonExcel.UndoRedoData_DefinedNamesChange; var g_oDefaultFormat = AscCommonExcel.g_oDefaultFormat; var Border = AscCommonExcel.Border; var RangeDataManagerElem = AscCommonExcel.RangeDataManagerElem; var RangeDataManager = AscCommonExcel.RangeDataManager; var cElementType = AscCommonExcel.cElementType; var cArea3D = AscCommonExcel.cArea3D; var cRef3D = AscCommonExcel.cRef3D; var parserFormula = AscCommonExcel.parserFormula; var c_oAscError = Asc.c_oAscError; var c_oAscInsertOptions = Asc.c_oAscInsertOptions; var c_oAscDeleteOptions = Asc.c_oAscDeleteOptions; var c_oAscGetDefinedNamesList = Asc.c_oAscGetDefinedNamesList; var c_oAscDefinedNameReason = Asc.c_oAscDefinedNameReason; var g_nVerticalTextAngle = 255; //определяется в WorksheetView.js var oDefaultMetrics = { ColWidthChars: 0, RowHeight: 0 }; var g_sNewSheetNamePattern = "Sheet"; var g_nSheetNameMaxLength = 31; var g_nAllColIndex = -1; var g_nAllRowIndex = -1; var aStandartNumFormats = []; var aStandartNumFormatsId = {}; var arrRecalc = {}, arrDefNameRecalc = {}; var oFormulaLocaleInfo = { Parse: true, DigitSep: true }; (function(){ aStandartNumFormats[0] = "General"; aStandartNumFormats[1] = "0"; aStandartNumFormats[2] = "0.00"; aStandartNumFormats[3] = "#,##0"; aStandartNumFormats[4] = "#,##0.00"; aStandartNumFormats[9] = "0%"; aStandartNumFormats[10] = "0.00%"; aStandartNumFormats[11] = "0.00E+00"; aStandartNumFormats[12] = "# ?/?"; aStandartNumFormats[13] = "# ??/??"; aStandartNumFormats[14] = "m/d/yyyy"; aStandartNumFormats[15] = "d-mmm-yy"; aStandartNumFormats[16] = "d-mmm"; aStandartNumFormats[17] = "mmm-yy"; aStandartNumFormats[18] = "h:mm AM/PM"; aStandartNumFormats[19] = "h:mm:ss AM/PM"; aStandartNumFormats[20] = "h:mm"; aStandartNumFormats[21] = "h:mm:ss"; aStandartNumFormats[22] = "m/d/yyyy h:mm"; aStandartNumFormats[37] = "#,##0_);(#,##0)"; aStandartNumFormats[38] = "#,##0_);[Red](#,##0)"; aStandartNumFormats[39] = "#,##0.00_);(#,##0.00)"; aStandartNumFormats[40] = "#,##0.00_);[Red](#,##0.00)"; aStandartNumFormats[45] = "mm:ss"; aStandartNumFormats[46] = "[h]:mm:ss"; aStandartNumFormats[47] = "mm:ss.0"; aStandartNumFormats[48] = "##0.0E+0"; aStandartNumFormats[49] = "@"; for(var i in aStandartNumFormats) { aStandartNumFormatsId[aStandartNumFormats[i]] = i - 0; } })(); var c_oRangeType = { Range:0, Col:1, Row:2, All:3 }; function getRangeType(oBBox){ if(null == oBBox) oBBox = this.bbox; if(oBBox.c1 == 0 && gc_nMaxCol0 == oBBox.c2 && oBBox.r1 == 0 && gc_nMaxRow0 == oBBox.r2) return c_oRangeType.All; if(oBBox.c1 == 0 && gc_nMaxCol0 == oBBox.c2) return c_oRangeType.Row; else if(oBBox.r1 == 0 && gc_nMaxRow0 == oBBox.r2) return c_oRangeType.Col; else return c_oRangeType.Range; } /** @constructor */ function DependencyGraph( wb ) { this.wb = wb; this.nodesId = null; this.nodesCell = null; this.nodesArea = null; this.defNameList = {}; this.defNameSheets = {}; this.nodeslength = null; this.bSetRefError = false; this.oChangeNodeSlave = null; this.sTableNamePattern = "Table"; this.nTableNameMaxIndex = 0; this.clear(); } DependencyGraph.prototype = { clear:function () { this.nodesId = {}; this.nodesCell = {}; this.nodesArea = {}; this.nodeslength = 0; this.bSetRefError = false; }, nodeExist:function ( node ) { return this.nodeExist2( node.sheetId, node.cellId ); }, nodeExist2:function ( sheetId, cellId ) { return null != this.getNode( sheetId, cellId ); }, nodeExistWithArea:function ( sheetId, cellId ) { var bRes = this.nodeExist2( sheetId, cellId ); if ( !bRes ) { var nodesSheetArea = this.nodesArea[sheetId]; if ( null != nodesSheetArea ) { var bbox = AscCommonExcel.g_oRangeCache.getAscRange( cellId ); bRes = nodesSheetArea.get( bbox ).all.length > 0; } } return bRes; }, getNode3:function ( nodeId ) { return this.nodesId[nodeId]; }, getNode2:function ( node ) { return this.nodesId[node.nodeId]; }, getNode:function ( sheetId, cellId ) { return this.nodesId[getVertexId( sheetId, cellId )]; }, addNode2:function ( node ) { return this.addNode( node.sheetId, node.cellId ); }, addNode:function ( sheetId, cellId ) { var _this = this; var nodeId = getVertexId( sheetId, cellId ); var oRes = this.nodesId[nodeId]; if ( null == oRes ) { var node = new Vertex( sheetId, cellId, this.wb ); var oBBoxNode = node.getBBox(); if ( node.isArea ) { var nodesSheetArea = this.nodesArea[node.sheetId]; if ( null == nodesSheetArea ) { nodesSheetArea = new RangeDataManager(function(data, from, to){_this._changeNode(data, from, to);}); this.nodesArea[node.sheetId] = nodesSheetArea; } nodesSheetArea.add( oBBoxNode, node ); } else { var nodesSheetCell = this.nodesCell[node.sheetId]; if ( null == nodesSheetCell ) { nodesSheetCell = new AscCommonExcel.CellArea(function(data, from, to){_this._changeNode(data, from, to);}); this.nodesCell[node.sheetId] = nodesSheetCell; } nodesSheetCell.add( oBBoxNode.r1, oBBoxNode.c1, node ); } oRes = node; } return oRes; }, addEdge2:function ( nodeFrom, nodeTo ) { nodeFrom.addMasterEdge( nodeTo ); nodeTo.addSlaveEdge( nodeFrom ); }, addEdge:function ( sheetIdFrom, cellIdFrom, sheetIdTo, cellIdTo ) { var n1 = this.addNode( sheetIdFrom, cellIdFrom ), n2 = this.addNode( sheetIdTo, cellIdTo ); this.addEdge2( n1, n2 ); }, getNodeBySheetId:function ( sheetId ) { var arr = []; var nodesSheetCell = this.nodesCell[sheetId]; if ( nodesSheetCell ) { var aNodes = nodesSheetCell.getAll(); for ( var i = 0, length = aNodes.length; i < length; i++ ) { var node = aNodes[i].data; var n = node.getSlaveEdges(); if ( n ) { arr.push( node ); } } } var nodesSheetArea = this.nodesArea[sheetId]; if ( nodesSheetArea ) { var aNodes = nodesSheetArea.getAll(); for ( var i = 0, length = aNodes.length; i < length; i++ ) { var node = aNodes[i].data; var n = node.getSlaveEdges(); if ( n ) { arr.push( node ); } } } return arr; }, getNodeBySheetIdAll:function ( sheetId ) { var arr = []; var nodesSheetCell = this.nodesCell[sheetId]; if ( nodesSheetCell ) { var aNodes = nodesSheetCell.getAll(); for ( var i = 0, length = aNodes.length; i < length; i++ ) { arr.push( aNodes[i].data ); } } var nodesSheetArea = this.nodesArea[sheetId]; if ( nodesSheetArea ) { var aNodes = nodesSheetArea.getAll(); for ( var i = 0, length = aNodes.length; i < length; i++ ) { arr.push( aNodes[i].data ); } } return arr; }, deleteNode:function ( node ) { if(node.isDefinedName) return; if ( node.isArea ) { var nodesSheetArea = this.nodesArea[node.sheetId]; if ( nodesSheetArea ) nodesSheetArea.removeElement( new RangeDataManagerElem( node.getBBox(), node ) ); } else { var nodesSheetCell = this.nodesCell[node.sheetId]; if ( nodesSheetCell ) nodesSheetCell.removeElement( new RangeDataManagerElem( node.getBBox(), node ) ); } }, deleteNodes : function(sheetId, bbox){ var bSetRefErrorOld = this.bSetRefError; this.bSetRefError = true; this.oChangeNodeSlave = { toDelete: {}, toMove: {} }; var nodesSheetArea = this.nodesArea[sheetId]; var oGetRes; if(nodesSheetArea) { oGetRes = nodesSheetArea.get(bbox); for(var i = 0, length = oGetRes.inner.length; i < length; ++i) nodesSheetArea.removeElement(oGetRes.inner[i]); } var nodesSheetCell = this.nodesCell[sheetId]; if(nodesSheetCell) { oGetRes = nodesSheetCell.get(bbox); for(var i = 0, length = oGetRes.length; i < length; ++i) nodesSheetCell.removeElement(oGetRes[i]); } this.changeNodeEnd(); this.bSetRefError = bSetRefErrorOld; }, deleteMasterNodes:function ( sheetId, cellId ) { var node = this.getNode( sheetId, cellId ); if ( node ) { var arr = node.deleteAllMasterEdges(); for ( var i in arr ) { var nodeMaster = arr[i]; if ( nodeMaster.refCount <= 0 ) this.deleteNode( nodeMaster ); } } return node; }, deleteMasterNodes2 : function(sheetId, cellId){ var node = this.deleteMasterNodes(sheetId, cellId); if(node && node.refCount <= 0) this.deleteNode(node); return node; }, deleteMasterNodes3:function ( node ) { var arr = node.deleteAllMasterEdges(); for (var i in arr) { var nodeMaster = arr[i]; if (nodeMaster.refCount <= 0) this.deleteNode(nodeMaster); } }, getSlaveNodes:function ( sheetId, cellId ) { //todo return null; }, getMasterNodes:function ( sheetId, cellId ) { //todo return null; }, getNodesLength:function () { return this.nodeslength; }, checkOffset:function ( BBox, offset, wsId, noDelete ) { var _this = this, bHor = 0 != offset.offsetCol, toDelete = offset.offsetCol < 0 || offset.offsetRow < 0, bSetRefErrorOld = this.bSetRefError; this.bSetRefError = true; var oShiftGetBBox = AscCommonExcel.shiftGetBBox(BBox, bHor); var sShiftGetBBoxName = oShiftGetBBox.getName(); this.wb.needRecalc.nodes[getVertexId(wsId, sShiftGetBBoxName)] = [wsId, sShiftGetBBoxName]; this.wb.needRecalc.length++; this.oChangeNodeSlave = { toDelete: {}, toMove: {}}; var nodesSheetArea = this.nodesArea[wsId]; if(nodesSheetArea) nodesSheetArea.shift(BBox, !toDelete, bHor); var nodesSheetCell = this.nodesCell[wsId]; if(nodesSheetCell) nodesSheetCell.shift( BBox, !toDelete, bHor ); this.changeNodeEnd(); this.bSetRefError = bSetRefErrorOld; }, changeNodeProcessDelete: function (node, oFormulas, toDelete) { //todo deleteAllSlaveEdges deleteMasterNodes var oSlaves = node.deleteAllSlaveEdges(), slave, formula; if (this.bSetRefError) { //выставляем #REF! for (var i in oSlaves) { slave = oSlaves[i]; if( slave instanceof DefNameVertex ){ if(!slave.isTable) this.wb.delDefinesNames(slave.getAscCDefName()); continue; } if (null == toDelete || slave != toDelete[slave.nodeId]) { formula = slave.setRefError(node); if (null != formula) { if (oFormulas) oFormulas[slave.nodeId] = { node: slave, formula: formula }; else slave.setFormula(formula, true, false); } } } } this.deleteMasterNodes3(node); }, changeNodeProcessMove: function (node, from, to, oFormulas, toDelete) { if (null == toDelete || node != toDelete[node.nodeId]) node.moveOuter(from, to, oFormulas); }, changeNodeEnd : function(){ var oChangeNodeSlave = this.oChangeNodeSlave; //обнуляем, потому что в цикле можем опять попасть в _changeNode со старым this.oChangeNodeSlave this.oChangeNodeSlave = null; //накапливаем формулы, потому что когда мы меняем формулу мы удаляем masterNodes, а эти node могут быть необработаными и влиять на формулу(C2=A2+B2 -> C1=A1+B2) var oFormulas = {}; for (var i in oChangeNodeSlave.toDelete) { var elem = oChangeNodeSlave.toDelete[i]; this.changeNodeProcessDelete(elem.node, oFormulas, oChangeNodeSlave.toDelete); } for (var i in oChangeNodeSlave.toMove) { var elem = oChangeNodeSlave.toMove[i]; this.changeNodeProcessMove(elem.node, elem.from, elem.to, oFormulas, oChangeNodeSlave.toDelete); } for (var i in oFormulas) { var elem = oFormulas[i]; if (null == elem.formula) { var node = elem.node; var cell = node.returnCell(); if (cell && cell.formulaParsed) { this.wb.dependencyFormulas.deleteMasterNodes2(node.sheetId, node.cellId); addToArrRecalc(node.sheetId, cell); } } else elem.node.setFormula(elem.formula, true, false); } }, _changeNode : function(node, from, to){ var toDelete = null == to; var toAdd = null == from; var wsId = node.sheetId; var sOldCellId = node.cellId; if(toAdd) { this.nodesId[node.nodeId] = node; this.nodeslength++; } else if(toDelete) { if (this.oChangeNodeSlave) this.oChangeNodeSlave.toDelete[node.nodeId] = { node: node, from: from, to: to }; else { this.changeNodeProcessDelete(node, null); } delete this.nodesId[node.nodeId]; this.nodeslength--; } else { var sOldnodeId = node.nodeId; node.moveInner(to); if (this.oChangeNodeSlave) this.oChangeNodeSlave.toMove[node.nodeId] = { node: node, from: from, to: to }; else this.changeNodeProcessMove(node, from, to, null); delete this.nodesId[sOldnodeId]; this.nodesId[node.nodeId] = node; } //важно что ячейки уже сдвинулись, поэтому до вызова returnCell нужно сделать node.move и сдвинуть ячейки в aGCells if(!node.isArea) { var cwf = this.wb.cwf[wsId]; if(cwf) { if(!toAdd) delete cwf.cells[sOldCellId]; if(!toDelete) { var cell = node.returnCell(); if ( cell && cell.formulaParsed ) cwf.cells[node.cellId] = node.cellId; } } } }, getCellInRange : function(sheetId, bbox){ var res = [], oGetRes, nodesSheetCell = this.nodesCell[sheetId]; if ( nodesSheetCell ) { oGetRes = nodesSheetCell.get(bbox); for ( var i = 0, length = oGetRes.length; i < length; i++ ) { res.push(oGetRes[i].data); } } return res; }, getAreaInRange : function(sheetId, bbox){ var res = [], oGetRes, nodesSheetArea = this.nodesArea[sheetId]; if(nodesSheetArea) { oGetRes = nodesSheetArea.get(bbox); for(var i = 0, length = oGetRes.all.length; i < length; i++) { res.push(oGetRes.all[i].data); } } return res; }, getInRange : function(sheetId, bbox){ return this.getCellInRange(sheetId, bbox).concat(this.getAreaInRange(sheetId, bbox)); }, helper : function(BBoxFrom, oBBoxTo, wsId){ var oGetRes, node, nodesSheetCell = this.nodesCell[wsId], nodesSheetArea = this.nodesArea[wsId]; var offset = { offsetCol: oBBoxTo.c1 - BBoxFrom.c1, offsetRow: oBBoxTo.r1 - BBoxFrom.r1 }; this.oChangeNodeSlave = { toDelete: {}, toMove: {} }; var elem, bbox; if(nodesSheetCell) oGetRes = nodesSheetCell.move(BBoxFrom, oBBoxTo); if(nodesSheetArea) oGetRes = nodesSheetArea.move(BBoxFrom, oBBoxTo); this.changeNodeEnd(); }, drawDep:function ( cellId, se ) { // ToDo неиспользуемая функция, реализовать после выпуска if ( !cellId ) return; var _wsV = this.wb.oApi.wb.getWorksheet(), _cc = _wsV.cellCommentator, ctx = _wsV.overlayCtx, _wsVM = _wsV.model, nodeId = getVertexId( _wsVM.getId(), cellId ), node = this.getNode( _wsVM.getId(), cellId ), cell; function gCM( _this, col, row ) { var metrics = { top:0, left:0, width:0, height:0, result:false }; // px var fvr = _this.getFirstVisibleRow(); var fvc = _this.getFirstVisibleCol(); var mergedRange = _wsVM.getMergedByCell( row, col ); if ( mergedRange && (fvc < mergedRange.c2) && (fvr < mergedRange.r2) ) { var startCol = (mergedRange.c1 > fvc) ? mergedRange.c1 : fvc; var startRow = (mergedRange.r1 > fvr) ? mergedRange.r1 : fvr; metrics.top = _this.getCellTop( startRow, 0 ) - _this.getCellTop( fvr, 0 ) + _this.getCellTop( 0, 0 ); metrics.left = _this.getCellLeft( startCol, 0 ) - _this.getCellLeft( fvc, 0 ) + _this.getCellLeft( 0, 0 ); for ( var i = startCol; i <= mergedRange.c2; i++ ) { metrics.width += _this.getColumnWidth( i, 0 ) } for ( var i = startRow; i <= mergedRange.r2; i++ ) { metrics.height += _this.getRowHeight( i, 0 ) } metrics.result = true; } else { metrics.top = _this.getCellTop( row, 0 ) - _this.getCellTop( fvr, 0 ) + _this.getCellTop( 0, 0 ); metrics.left = _this.getCellLeft( col, 0 ) - _this.getCellLeft( fvc, 0 ) + _this.getCellLeft( 0, 0 ); metrics.width = _this.getColumnWidth( col, 0 ); metrics.height = _this.getRowHeight( row, 0 ); metrics.result = true; } return metrics; } if ( !node ) return; cell = node.returnCell(); if ( !cell ) return; var m = [cell.nRow, cell.nCol], rc = [], me = se ? node.getSlaveEdges() : node.getMasterEdges(); for ( var id in me ) { if ( me[id].sheetId != node.sheetId ) return; if ( !me[id].isArea ) { var _t1 = gCM( _wsV, me[id].returnCell().nCol, me[id].returnCell().nRow ) rc.push( { t:_t1.top, l:_t1.left, w:_t1.width, h:_t1.height, apt:_t1.top + _t1.height / 2, apl:_t1.left + _t1.width / 4} ); } else { var _t1 = gCM( _wsV, me[id].getBBox().c1, me[id].getBBox().r1 ), _t2 = gCM( _wsV, me[id].getBBox().c2, me[id].getBBox().r2 ); rc.push( { t:_t1.top, l:_t1.left, w:_t2.left + _t2.width - _t1.left, h:_t2.top + _t2.height - _t1.top, apt:_t1.top + _t1.height / 2, apl:_t1.left + _t1.width / 4 } ); } } if ( rc.length == 0 ) return; var color = new AscCommon.CColor( 0, 0, 255 ); function draw_arrow( context, fromx, fromy, tox, toy ) { var headlen = 9; var dx = tox - fromx; var dy = toy - fromy; var angle = Math.atan2( dy, dx ), _a = Math.PI / 18; // ToDo посмотреть на четкость moveTo, lineTo context.save() .setLineWidth( 1 ) .beginPath() .moveTo( _cc.pxToPt( fromx ), _cc.pxToPt( fromy ) ) .lineTo( _cc.pxToPt( tox ), _cc.pxToPt( toy ) ); // .dashLine(_cc.pxToPt(fromx-.5), _cc.pxToPt(fromy-.5), _cc.pxToPt(tox-.5), _cc.pxToPt(toy-.5), 15, 5) context .moveTo( _cc.pxToPt( tox - headlen * Math.cos( angle - _a ) ), _cc.pxToPt( toy - headlen * Math.sin( angle - _a ) ) ) .lineTo( _cc.pxToPt( tox ), _cc.pxToPt( toy ) ) .lineTo( _cc.pxToPt( tox - headlen * Math.cos( angle + _a ) ), _cc.pxToPt( toy - headlen * Math.sin( angle + _a ) ) ) .lineTo( _cc.pxToPt( tox - headlen * Math.cos( angle - _a ) ), _cc.pxToPt( toy - headlen * Math.sin( angle - _a ) ) ) .setStrokeStyle( color ) .setFillStyle( color ) .stroke() .fill() .closePath() .restore(); } function h( m, rc ) { var m = gCM( _wsV, m[1], m[0] ); var arrowPointTop = 10, arrowPointLeft = 10; for ( var i = 0; i < rc.length; i++ ) { var m2 = rc[i], x1 = Math.floor( m2.apl ), y1 = Math.floor( m2.apt ), x2 = Math.floor( m.left + m.width / 4 ), y2 = Math.floor( m.top + m.height / 2 ); if ( x1 < 0 && x2 < 0 || y1 < 0 && y2 < 0 ) continue; // ToDo посмотреть на четкость rect if ( m2.apl > 0 && m2.apt > 0 ) ctx.save() .setLineWidth( 1 ) .setStrokeStyle( color ) .rect( _cc.pxToPt( m2.l ), _cc.pxToPt( m2.t ), _cc.pxToPt( m2.w - 1 ), _cc.pxToPt( m2.h - 1 ) ) .stroke() .restore(); if ( y1 < 0 && x1 != x2 ) x1 = x1 - Math.floor( Math.sqrt( ((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) * y1 * y1 / ((y2 - y1) * (y2 - y1)) ) / 2 ) if ( x1 < 0 && y1 != y2 ) y1 = y1 - Math.floor( Math.sqrt( ((y1 - y2) * (y1 - y2) + (x1 - x2) * (x1 - x2)) * x1 * x1 / ((x2 - x1) * (x2 - x1)) ) / 2 ) draw_arrow( ctx, x1 < 0 ? _wsV.getCellLeft( 0, 0 ) : x1, y1 < 0 ? _wsV.getCellTop( 0, 0 ) : y1, x2, y2 ); if ( m2.apl > 0 && m2.apt > 0 ) ctx.save() .beginPath() .arc( _cc.pxToPt( Math.floor( m2.apl ) ), _cc.pxToPt( Math.floor( m2.apt ) ), 3, 0, 2 * Math.PI, false, -0.5, -0.5 ) .setFillStyle( color ) .fill() .closePath() .restore(); } } ctx.clear(); _wsV._drawSelection(); if ( se ) { for ( var i = 0; i < rc.length; i++ ) h( rc[i], [m] ); } else h( m, rc ); }, removeNodeBySheetId: function (sheetId) { this.oChangeNodeSlave = { toDelete: {}, toMove: {} }; var nodesSheetArea = this.nodesArea[sheetId]; if(nodesSheetArea) nodesSheetArea.removeAll(); var nodesSheetCell = this.nodesCell[sheetId]; if(nodesSheetCell) nodesSheetCell.removeAll(); this.changeNodeEnd(); }, getNodeDependence:function ( aElems, aDefinedNames ) { var oRes = { oMasterNodes: {}, oMasterAreaNodes: {}, oMasterAreaNodesRestricted: {}, oWeightMap: {}, oNodeToArea: {}, nCounter: 0 }, aWeightMapMasters = [], aWeightMapMastersNodes = [], node, elem, oSheetRanges = {}, oSheetWithArea = {};//все sheet на которых есть area для пересчета while ( null != aElems || null != aDefinedNames ) { if(null != aElems){ for ( var i in aElems ) { elem = aElems[i]; var sheetId = elem[0]; var cellId = elem[1]; //нужно обавлять в oSheetRanges даже несушествующие node, чтобы поддержать именении ячеек в SUM(A1:B2) this._getNodeDependenceNodeToRange(sheetId, AscCommonExcel.g_oRangeCache.getAscRange(cellId), oSheetRanges); node = this.getNode(sheetId, cellId); if ( node && null == oRes.oWeightMap[node.nodeId] ) { //все node из aElems записываем в master var oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 0, gray: false, bad: false, master: true, area: node.isArea }; if (node.isArea) oSheetWithArea[node.sheetId] = 1; aWeightMapMasters.push( oWeightMapElem ); aWeightMapMastersNodes.push( node ); oRes.oWeightMap[node.nodeId] = oWeightMapElem; this._getNodeDependence( oRes, oSheetRanges, node ); } } } if(null != aDefinedNames){ for(var i = 0; i < aDefinedNames.length; ++i){ var node = aDefinedNames[i]; if ( node && null == oRes.oWeightMap[node.nodeId] ) { //все node из aDefinedNames записываем в master var oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 0, gray: false, bad: false, master: true, area: false }; aWeightMapMasters.push( oWeightMapElem ); aWeightMapMastersNodes.push( node ); oRes.oWeightMap[node.nodeId] = oWeightMapElem; this._getNodeDependence( oRes, oSheetRanges, node ); } } } aElems = null; aDefinedNames = null; //расширяем за счет area nodes for ( var i in oSheetRanges ) { var oSheetRange = oSheetRanges[i]; if ( oSheetRange.changed ) { oSheetRange.changed = false; var nodesSheetArea = this.nodesArea[i]; if ( null != nodesSheetArea ) { var aAllOuter = null; if ( null == oSheetRange.prevRange ) { var oGetRes = nodesSheetArea.get( oSheetRange.range ); if ( oGetRes.all.length > 0 ) aAllOuter = oGetRes.all; } else { var aEdgeBBox = []; var bLeft = oSheetRange.range.c1 < oSheetRange.prevRange.c1; var bRight = oSheetRange.range.c2 > oSheetRange.prevRange.c2; var bTop = oSheetRange.range.r1 < oSheetRange.prevRange.r1; var bBottom = oSheetRange.range.r2 > oSheetRange.prevRange.r2; if (bLeft) aEdgeBBox.push(new Asc.Range(oSheetRange.range.c1, oSheetRange.range.r1, oSheetRange.prevRange.c1 - 1, oSheetRange.range.r2)); if (bRight) aEdgeBBox.push(new Asc.Range(oSheetRange.prevRange.c2 + 1, oSheetRange.range.r1, oSheetRange.range.c2, oSheetRange.range.r2)); if (bTop || bBottom){ var nNewC1, nNewC2; if(bLeft) nNewC1 = oSheetRange.range.c1 + 1; else nNewC1 = oSheetRange.range.c1; if(bRight) nNewC2 = oSheetRange.range.c2 - 1; else nNewC2 = oSheetRange.range.c2; if(bTop) aEdgeBBox.push(new Asc.Range(nNewC1, oSheetRange.range.r1, nNewC2, oSheetRange.prevRange.r1 - 1)); if(bBottom) aEdgeBBox.push(new Asc.Range(nNewC1, oSheetRange.prevRange.r2 + 1, nNewC2, oSheetRange.range.r2)); } aAllOuter = []; for ( var j = 0, length = aEdgeBBox.length; j < length; j++ ) { var bbox = aEdgeBBox[j]; var oGetRes = nodesSheetArea.get( bbox ); if ( oGetRes.all.length > 0 ) aAllOuter = aAllOuter.concat( oGetRes.all ); } } if ( aAllOuter && aAllOuter.length > 0 ) { if ( null == aElems ) aElems = []; for ( var j in aAllOuter ) { var node = aAllOuter[j].data; aElems[node.nodeId] = [node.sheetId, node.cellId]; } } } } } } var bMasterAreaNodesExist = false; var oAllMasterAreaNodes = {}; for ( var i = 0, length = aWeightMapMasters.length; i < length; i++ ) { var oWeightMapElem = aWeightMapMasters[i]; //возвращаем только настощие master if ( oWeightMapElem.master ) { node = aWeightMapMastersNodes[i]; if (oWeightMapElem.area) { bMasterAreaNodesExist = true; oAllMasterAreaNodes[node.nodeId] = node; } else oRes.oMasterNodes[node.nodeId] = node; } } if (bMasterAreaNodesExist) { //заносим все одинарные ячейки для пересчета в CellArea, чтобы определить какие из них лежат внутри area var oCellsForCalculation = {}; for (var i in oRes.oWeightMap) { var elem = oRes.oWeightMap[i]; if (!elem.area && !elem.isDefinedName) { var node = this.wb.dependencyFormulas.nodesId[i]; //если ячейка из oMasterNodes, даже если в ней формула, то она не может иметь master из oWeightMap(иначе она бы перестала быть master) - такие ячейки не добавляем //остальные ячейки имеют master из oWeightMap их надо проверять if (node && oSheetWithArea[node.sheetId] && !oRes.oMasterNodes[node.nodeId]) { var oCellsForCalculationSheet = oCellsForCalculation[node.sheetId]; if (null == oCellsForCalculationSheet) { oCellsForCalculationSheet = new AscCommonExcel.CellArea(null); oCellsForCalculation[node.sheetId] = oCellsForCalculationSheet; } var bbox = node.getBBox(); oCellsForCalculationSheet.add(bbox.r1, bbox.c1, node); } } } //делим oAllMasterAreaNodes на те что можно посчитать сразу и те что имеют внутри себя непосчитанные ячейки. //заполняем oNodeToArea ячейками и ссылками на AreaNode в которых ини лежат for (var i in oAllMasterAreaNodes) { var nodeMaster = oAllMasterAreaNodes[i]; //элемент запоминает сколько node надо посечить прежде чем считать nodeMaster var nodeMasterElement = { node: nodeMaster, cur: 0, max: 0 }; var bRestricted = false; var oCellsForCalculationSheet = oCellsForCalculation[nodeMaster.sheetId]; if (oCellsForCalculationSheet) { var oGetRes = oCellsForCalculationSheet.get(nodeMaster.getBBox()); if (oGetRes.length > 0) { bRestricted = true; for (var j = 0; j < oGetRes.length; ++j) { var node = oGetRes[j].data; var oNodeToAreaElement = oRes.oNodeToArea[node.nodeId]; if (null == oNodeToAreaElement) { oNodeToAreaElement = []; oRes.oNodeToArea[node.nodeId] = oNodeToAreaElement; } nodeMasterElement.max++; oNodeToAreaElement.push(nodeMasterElement); } } } if (bRestricted) oRes.oMasterAreaNodesRestricted[nodeMaster.nodeId] = nodeMasterElement; else oRes.oMasterAreaNodes[nodeMaster.nodeId] = nodeMaster; } } return oRes; }, _getNodeDependence:function ( oRes, oSheetRanges, node ) { var oResMapCycle = null; var bStop = false; var oWeightMapElem = oRes.oWeightMap[node.nodeId]; if ( null == oWeightMapElem ) { if(node.isDefinedName) oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 1, gray: false, bad: false, master: false, area: false }; else oWeightMapElem = { id: oRes.nCounter++, cur: 0, max: 1, gray: false, bad: false, master: false, area: node.isArea }; oRes.oWeightMap[node.nodeId] = oWeightMapElem; } else { oWeightMapElem.max++; //если пришли в gray node, то это цикл if (oWeightMapElem.gray) { bStop = true; oResMapCycle = {}; oResMapCycle[oWeightMapElem.id] = oWeightMapElem; oWeightMapElem.bad = true; oWeightMapElem.max--; } else if (oWeightMapElem.master && oWeightMapElem.max > 1) { bStop = true; //если повторно пришли в master node, то не считаем ее master oWeightMapElem.master = false; oWeightMapElem.max--; } } if (!bStop && 1 == oWeightMapElem.max && !node.isDefinedName ) this._getNodeDependenceNodeToRange( node.sheetId, node.getBBox(), oSheetRanges ); if (!bStop && oWeightMapElem.max <= 1) { oWeightMapElem.gray = true; var aNext = node.getSlaveEdges(); for (var i in aNext) { var oCurMapCycle = this._getNodeDependence(oRes, oSheetRanges, aNext[i], oWeightMapElem); if (null != oCurMapCycle) { oWeightMapElem.bad = true; for (var i in oCurMapCycle) { var oCurElem = oCurMapCycle[i]; if (oWeightMapElem != oCurElem) { if (null == oResMapCycle) oResMapCycle = {}; oResMapCycle[oCurElem.id] = oCurElem; } } } } oWeightMapElem.gray = false; } return oResMapCycle; }, _getNodeDependenceNodeToRange:function ( sheetId, bbox, oSheetRanges ) { var oSheetRange = oSheetRanges[sheetId]; if ( null == oSheetRange ) { oSheetRange = {range:null, changed:false, prevRange:null}; oSheetRanges[sheetId] = oSheetRange; } if ( null == oSheetRange.range || !oSheetRange.range.containsRange( bbox ) ) { if ( null == oSheetRange.range ) oSheetRange.range = bbox.clone(); else { if ( !oSheetRange.changed ) oSheetRange.prevRange = oSheetRange.range.clone(); oSheetRange.range.union2( bbox ); } oSheetRange.changed = true; } }, getAll:function () { return this.nodesId; }, /*Defined Names section*/ getDefNameNode:function ( node ) { var ret = this.defNameList[node]; return ret ? ret : null; }, getDefNameNodeByName:function ( name, sheetId ) { name = name.toLowerCase(); var sheetNodeList, nodeId, oRes = false; if ( !AscCommon.rx_defName.test( name ) ) { return oRes ; } if ( null != sheetId ) { sheetNodeList = this.defNameSheets[sheetId]; if ( sheetNodeList ) { nodeId = getDefNameVertexId( sheetId, name ); oRes = sheetNodeList[nodeId]; if ( oRes && oRes.Ref ) return oRes; } } sheetNodeList = this.defNameSheets["WB"]; if( sheetNodeList ){ nodeId = getDefNameVertexId( null, name ); oRes = sheetNodeList[nodeId]; } if ( oRes && !oRes.Ref ) oRes = false; return oRes; }, getDefNameNodeByRef:function ( ref, sheetId ) { var sheetNodeList; if ( null != sheetId ) { sheetNodeList = this.defNameSheets[sheetId]; for ( var id in sheetNodeList ) { if ( sheetNodeList[id].Ref == ref ) { return sheetNodeList[id].Name; } } } sheetNodeList = this.defNameSheets["WB"]; for ( var id in sheetNodeList ) { if ( sheetNodeList[id].Ref === ref ) { return sheetNodeList[id].Name; } } return false; }, addDefinedNameNode:function ( defName, sheetId, defRef, defHidden, bUndo ) { var ws = this.wb.getWorksheet( sheetId ) ws ? sheetId = ws.getId() : null; var nodeId = getDefNameVertexId( sheetId, defName ), oRes = this.defNameList[nodeId], dfv, defNameSheetsList; if ( null == oRes || ( null == oRes.Ref && null == defRef ) ) { dfv = new DefNameVertex( sheetId, defName, defRef, defHidden, this.wb ); oRes = (this.defNameList[dfv.nodeId] = dfv); defNameSheetsList = this.defNameSheets[dfv.sheetId]; if ( defNameSheetsList == null ) { defNameSheetsList = {}; this.defNameSheets[dfv.sheetId] = defNameSheetsList; } defNameSheetsList[dfv.nodeId] = dfv; } else if( null == oRes.Ref && null != defRef ){ oRes.Ref = defRef; oRes.isTable = undefined; addToArrDefNameRecalc(oRes); } /*поставить зависимость между ячейками и текущим ИД*/ if ( bUndo ) { oRes.Ref = defRef; } if( !oRes.isTable && oRes.Ref != undefined && oRes.Ref != null ){ addToArrDefNameRecalc(oRes); } return oRes; }, removeDefName:function ( sheetId, name ) { var ws = this.wb.getWorksheet( sheetId ); ws ? sheetId = ws.getId() : null; var nodeId = getDefNameVertexId( sheetId, name ), oRes = this.defNameList[nodeId], ret = null; if ( oRes ) { this.defNameList[nodeId].Ref = null; ret = oRes; addToArrDefNameRecalc(oRes); } return ret; }, removeDefNameBySheet:function ( sheetId ) { var nodesList = this.defNameList, retRes = {}, defN, seUndoRedo = [], nSE, wsIndex, ws = this.wb.getWorksheetById(sheetId ), wsName = ws.getName(); for ( var id in nodesList ) { defN = nodesList[id]; if ( defN.isTable && defN.Ref ){ var a = defN.Ref.split("!")[0]; if( a.localeCompare(parserHelp.getEscapeSheetName(wsName)) == 0 ){ History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesDelete, null, null, new UndoRedoData_DefinedNames( defN.Name, defN.Ref, undefined, defN.isTable ) ); defN.Ref = null; } continue; } if ( !defN.isTable && defN.parsedRef && defN.parsedRef.removeSheet( sheetId ) ) { seUndoRedo = []; nSE = defN.getSlaveEdges(); for ( var nseID in nSE ) { seUndoRedo.push( nseID ); } wsIndex = this.wb.getWorksheetById( defN.sheetId ); History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesDelete, null, null, new UndoRedoData_DefinedNames( defN.Name, defN.Ref, wsIndex ? wsIndex.getIndex() : undefined, defN.isTable, seUndoRedo ) ); if ( defN.sheetId == sheetId ) { defN.Ref = null; defN.parsedRef = null; retRes[id] = defN; } else if( defN.Ref ){ defN.Ref = defN.parsedRef.Formula = defN.parsedRef.assemble( true ); retRes[id] = defN; } addToArrDefNameRecalc(defN); } } return retRes; }, changeDefName:function ( oldDefName, newDefName ) { var ws = this.wb.getWorksheet( oldDefName.LocalSheetId ); var sheetId = ws ? ws.getId() : null; var oldN = this.getDefNameNodeByName( oldDefName.Name, sheetId ), sheetNodeList, nodeId, name = oldDefName.Name; sheetNodeList = this.defNameSheets[sheetId || "WB"]; nodeId = getDefNameVertexId( sheetId || "WB", name ); sheetNodeList ? delete sheetNodeList[nodeId] : null; delete this.defNameList[nodeId]; if(!oldN){ return false; } oldN.changeDefName( newDefName ); this.defNameList[oldN.nodeId] = oldN; sheetNodeList[oldN.nodeId] = oldN; if (oldDefName.isTable) { var dataRange = parserHelp.parse3DRef(oldDefName.Ref); if (dataRange) { var sheetDefName = this.wb.getWorksheetByName(dataRange.sheet); if (sheetDefName) { var tableParts = sheetDefName.TableParts; for (var i = 0; i < tableParts.length; i++) { if (tableParts[i].DisplayName == name) { tableParts[i].DisplayName = oldN.Name; } } } } } else { oldN.deleteAllMasterEdges(); addToArrDefNameRecalc(oldN); } return oldN; }, copyDefNameByWorksheet:function( oldSheetId, newSheetId ){ var obj = {}, oldS = this.defNameSheets[oldSheetId], defNamNode, oldWS = this.wb.getWorksheetById(oldSheetId ), newWS = this.wb.getWorksheetById(newSheetId); for( var id in oldS ){ defNamNode = oldS[id].clone(); defNamNode.changeScope(newSheetId); defNamNode.changeRefToNewSheet(oldWS.getName(),newWS.getName()); obj[defNamNode.nodeId] = defNamNode; this.defNameList[defNamNode.nodeId] = defNamNode; } this.defNameSheets[newSheetId] = obj; }, relinkDefNameByWorksheet:function (oName, nName){ var oldS = this.defNameList, dN; for( var id in oldS ){ dN = oldS[id]; if(dN.isTable ){ if(dN.Ref) dN.Ref = dN.Ref.replace(oName,nName); } else{ if( dN.Ref ){ dN.relinkRef(oName, nName); } } } }, saveDefName:function () { var list = [], defN; for ( var id in this.defNameList ) { defN = this.defNameList[id]; if ( defN.isTable ) { continue; } if ( defN.Ref != null ) { list.push( defN.getAscCDefName() ); } } return list; }, unlockDefName:function(){ var nodesList = this.defNameList; for ( var id in nodesList ) { if ( nodesList[id].isLock ) { delete nodesList[id].isLock; } } }, checkDefNameLock:function(){ var nodesList = this.defNameList, countNodes = 0; for ( var id in nodesList ) { countNodes++; if ( nodesList[id].isLock ) { return true; } } return !countNodes; // return false; }, getNextTableName:function ( ws, Ref ) { this.nTableNameMaxIndex++; var sNewName = this.sTableNamePattern + this.nTableNameMaxIndex, name = getDefNameVertexId( null, sNewName ); while ( this.defNameList[name] ) { this.nTableNameMaxIndex++; sNewName = this.sTableNamePattern + this.nTableNameMaxIndex; name = getDefNameVertexId( null, sNewName ); } this.addTableName( sNewName, ws, Ref ); return sNewName; }, addTableName:function ( sName, ws, Ref ) { var refClone, defNameSheetsList, dfv, nSE, se; if(this.defNameSheets["WB"]){ dfv = this.defNameSheets["WB"][getDefNameVertexId( null, sName )] } refClone = Ref.clone(true ) refClone.r1++; if(!dfv){ dfv = new DefNameVertex( null, sName, parserHelp.get3DRef( ws.getName(), refClone.getAbsName() ), null, this.wb, true ); defNameSheetsList = this.defNameSheets[dfv.sheetId]; this.defNameList[dfv.nodeId] = dfv; if ( defNameSheetsList == null ) { defNameSheetsList = {}; this.defNameSheets[dfv.sheetId] = defNameSheetsList; } defNameSheetsList[dfv.nodeId] = dfv; } else{ dfv.Ref = parserHelp.get3DRef( ws.getName(), refClone.getAbsName() ); nSE = dfv.getSlaveEdges(); for ( var id in nSE ) { se = nSE[id]; addToArrRecalc(se.sheetId, se.cell); this.wb.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.wb.needRecalc.length++; } } addToArrDefNameRecalc(dfv); }, changeTableName:function(tableName, ws, newRef){ var table = this.getDefNameNodeByName( tableName, ws ), newRefClone = newRef.clone(true); newRefClone.r1++; table.Ref = table.Ref.split("!")[0]+"!"+newRefClone.getAbsName(); table.rebuild(); // table.Ref = parserHelp.getEscapeSheetName(ws.getName())+"!"+newRef.getAbsName(); }, changeTableRef:function(tableName, ws, newName){ var table = this.getDefNameNodeByName( tableName, ws ); var newTable = table.clone(); if(table) { //изменяем имя именнованного диапазона newTable.Name = newName; newTable.cellId = newName.toLowerCase(); newTable.nodeId = table.sheetId + table.cellId; this.changeDefName(table, newTable); //изменяем все ссылки на данную таблицу var nameRef = tableName + "[]"; for(var i in this.defNameList) { if(this.defNameList[i] && this.defNameList[i].Ref && this.defNameList[i].Ref === nameRef) { this.defNameList[i].Ref = newName + "[]"; } } } table.rebuild(); }, delTableName:function(name,ws){ var table = this.getDefNameNodeByName( name, ws ); table.Ref = null; var nSE, se; nSE = table.getSlaveEdges(); table.deleteAllMasterEdges(); for ( var id in nSE ) { se = nSE[id]; addToArrRecalc(se.sheetId, se.cell); this.wb.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.wb.needRecalc.length++; } addToArrDefNameRecalc(table); }, rebuildTable:function(tableName){ var table = this.getDefNameNodeByName( tableName, null ), nSE, se, nME, range; nME = table.getMasterEdges(); for ( var id in nME ) { range = this.getInRange( nME[id].sheetId, nME[id].bbox ); for ( var i = 0; i < range.length; i++ ) { nSE = range[i].getSlaveEdges(); for ( var id in nSE ) { se = nSE[id]; se = se.returnCell(); if ( se ) { se.setFormula( se.formulaParsed.assemble() ); } } } } } }; /** @constructor */ function Vertex(sheetId, cellId, wb){ this.sheetId = sheetId; this.cellId = cellId; this.bbox = AscCommonExcel.g_oRangeCache.getAscRange(this.cellId); this.isArea = !this.bbox.isOneCell(); this.valid = true; this.nodeId = getVertexId(this.sheetId, this.cellId); this.wb = wb; this.cell = null; //вершина которую мы прошли и поставили в очередь обхода this.isBlack = false; //вершина которую мы прошли, но не поставили в очередь обхода. нужно для определения петель в графе. this.isGray = false; //если вершина входит в цикличный путь, то она помечается плохой и запоминается в списке плохих вершин. this.isBad = false; //masterEdges содержит ячейки, от которых зависит текущая ячейка this.masterEdges = {}; //slaveEdges содержит ячейки, которые зависят от данной ячейки this.slaveEdges = {}; this.refCount = 0; this.isDefinedName = false; } Vertex.prototype = { constructor: Vertex, getBBox : function() { return this.bbox; }, setFormula : function(sFormula, bAddToHistory, bAddNeedRecalc) { this.wb.dependencyFormulas.deleteMasterNodes2(this.sheetId, this.cellId); var cell = this.returnCell(); if (null != sFormula) cell.setFormula(sFormula, bAddToHistory); addToArrRecalc(this.sheetId, cell); if(bAddNeedRecalc) { this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId ]; this.wb.needRecalc.length++; } }, setRefError : function(wsId, cellId) { var sRes = null; var cell = this.returnCell(); if( cell && cell.formulaParsed ) { cell.formulaParsed.setRefError(wsId, cellId); sRes = cell.formulaParsed.assemble(true); } return sRes; }, moveInner: function (bboxTo) { //удаляем старые ссылки slave и master var slave, master; for (var i in this.slaveEdges) { slave = this.slaveEdges[i]; slave.deleteMasterEdge(this); } for (var i in this.masterEdges) { master = this.masterEdges[i]; master.deleteSlaveEdge(this); } this.bbox = bboxTo; this.cellId = bboxTo.getName(); this.nodeId = getVertexId(this.sheetId, this.cellId); this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId]; this.wb.needRecalc.length++; //добавляем новые slave и master for (var i in this.slaveEdges) { slave = this.slaveEdges[i]; slave.addMasterEdge(this); } for (var i in this.masterEdges) { master = this.masterEdges[i]; master.addSlaveEdge(this); } }, moveOuter: function (from, to, oFormulas) { if ((from.r1 == to.r1 && from.c1 == to.c1) || (from.r2 == to.r2 && from.c2 == to.c2)) { /*вставляем/удаляем по вертикали/горизонтали внутри диапазона*/ var _sn = this.getSlaveEdges(), slave, cell; for (var _id in _sn) { slave = _sn[_id]; if( slave instanceof DefNameVertex ){ if ( false == this.wb.bUndoChanges && (false == this.wb.bRedoChanges || true == this.wb.bCollaborativeChanges )){ History.LocalChange = true; var oN = slave.getAscCDefName(), nN; slave.parsedRef.stretchArea(this, from, to); nN = slave.getAscCDefName(); nN.Ref = slave.parsedRef.assemble(); this.wb.editDefinesNames( oN, nN ); History.LocalChange = false; } continue; } cell = slave.returnCell(); if (cell && cell.formulaParsed) { cell.formulaParsed.stretchArea(this, from, to); var formula = cell.formulaParsed.assemble(); if (null != formula) { if (oFormulas) oFormulas[slave.nodeId] = { node: slave, formula: formula }; else slave.setFormula(formula, true, false); } } } } else { /*вставляем.удаляем левее/выше вне диапазона*/ if (oFormulas) { if (null == oFormulas[this.nodeId]) oFormulas[this.nodeId] = { node: this, formula: null }; } else { var cell = this.returnCell(); if (cell && cell.formulaParsed) { this.wb.dependencyFormulas.deleteMasterNodes2(this.sheetId, this.cellId); addToArrRecalc(this.sheetId, cell); } } var _sn = this.getSlaveEdges(), slave, cell; for (var _id in _sn) { slave = _sn[_id] if( slave instanceof DefNameVertex ){ /*slave.parsedRef.shiftCells(this, from, to); slave.relinkRef();*/ if ( false == this.wb.bUndoChanges && (false == this.wb.bRedoChanges || true == this.wb.bCollaborativeChanges )){ History.LocalChange = true; var oN = slave.getAscCDefName(), nN; slave.parsedRef.shiftCells(this, from, to); nN = slave.getAscCDefName(); nN.Ref = slave.parsedRef.assemble(); this.wb.editDefinesNames( oN, nN ); History.LocalChange = false; } continue; } cell = slave.returnCell(); if (cell && cell.formulaParsed) { cell.formulaParsed.shiftCells(this, from, to); var formula = cell.formulaParsed.assemble(); if (null != formula) { if (oFormulas) oFormulas[slave.nodeId] = { node: slave, formula: formula }; else slave.setFormula(formula, true, false); } } } } }, //добавляем ведущую ячейку. addMasterEdge : function(node){ if( !this.masterEdges ){ this.masterEdges = {}; } if( !this.masterEdges[node.nodeId] ){ this.masterEdges[node.nodeId] = node; this.refCount ++; } }, //добавляем зависимую(ведомую) ячейку. addSlaveEdge : function(node){ if( !this.slaveEdges ){ this.slaveEdges = {}; } if( !this.slaveEdges[node.nodeId] ){ this.slaveEdges[node.nodeId] = node; this.refCount ++; } }, getMasterEdges : function(){ return this.masterEdges; }, getSlaveEdges : function(){ return this.slaveEdges; }, getSlaveEdges2 : function(){ var ret = {}, count = 0; for(var id in this.slaveEdges){ ret[id] = this.slaveEdges[id]; count++; } if ( count > 0 ) return ret; else return null; }, //удаляем ребро между конкретной ведущей ячейки. deleteMasterEdge: function (node) { if (this.masterEdges) { delete this.masterEdges[node.nodeId]; this.refCount--; } }, //удаляем ребро между конкретной зависимой(ведомой) ячейки. deleteSlaveEdge: function (node) { if (this.slaveEdges) { delete this.slaveEdges[node.nodeId]; this.refCount--; } }, //очищаем все ребра по ведущим ячейкам. deleteAllMasterEdges : function(){ var ret = {}; for( var id in this.masterEdges ){ var masterEdge = this.masterEdges[id]; masterEdge.deleteSlaveEdge(this); delete this.masterEdges[id]; this.refCount--; ret[id] = masterEdge; } this.masterEdges = {}; return ret; }, //очищаем все ребра по ведомым ячейкам. deleteAllSlaveEdges : function(){ var ret = {}; for( var id in this.slaveEdges ){ var slaveEdge = this.slaveEdges[id]; slaveEdge.deleteMasterEdge(this); delete this.slaveEdges[id]; this.refCount--; ret[id] = slaveEdge; } this.slaveEdges = {}; return ret; }, returnCell : function(){ //todo if(null == this.cell && this.wb && !this.isArea) { var ws = this.wb.getWorksheetById(this.sheetId); if(ws) this.cell = ws._getCell(this.bbox.r1, this.bbox.c1); // this.cell = ws._getCellNoEmpty(this.bbox.r1, this.bbox.c1); } return this.cell; } }; function DefNameVertex( scope, defName, defRef, defHidden, wb, isTable ) { this.sheetId = scope === null || scope === undefined ? "WB" : scope; this.cellId = defName.toLowerCase(); this.Ref = defRef; this.Name = defName; this.Hidden = defHidden; this.isTable = isTable; this.nodeId = getDefNameVertexId( this.sheetId, defName ); this.wb = wb; //вершина которую мы прошли и поставили в очередь обхода this.isBlack = false; //вершина которую мы прошли, но не поставили в очередь обхода. нужно для определения петель в графе. this.isGray = false; //если вершина входит в цикличный путь, то она помечается плохой и запоминается в списке плохих вершин. this.isBad = false; //masterEdges содержит ячейки, от которых зависит текущая ячейка this.masterEdges = {}; //slaveEdges содержит ячейки, которые зависят от данной ячейки this.slaveEdges = {}; this.refCount = 0; this.isDefinedName = true; } DefNameVertex.prototype = { constructor:Vertex, clone:function(){ var dN = new DefNameVertex( this.sheetId, this.cellId, this.Ref, this.Hidden, this.wb, this.isTable ); dN.parsedRef = new parserFormula( dN.Ref, "", this.wb.getWorksheet(0) ); if( dN.Ref ){ dN.parsedRef.parse(); // dN.parsedRef.buildDependencies(); } return dN; }, changeScope:function( newScope ){ this.sheetId = newScope === null || newScope === undefined ? "WB" : newScope; this.nodeId = getDefNameVertexId( this.sheetId, this.Name ); }, changeRefToNewSheet:function( lastName, newName ){ if( !this.isTable && this.parsedRef.isParsed ){ this.parsedRef = this.parsedRef.changeSheet( lastName, newName ); this.Ref = this.parsedRef.assemble(); } }, moveInner:function ( bboxTo ) { //удаляем старые ссылки slave и master for ( var i in this.slaveEdges ) { var slave = this.slaveEdges[i]; slave.deleteMasterEdge( this ); } for ( var i in this.masterEdges ) { var master = this.masterEdges[i]; master.deleteSlaveEdge( this ); } var sOldNodeId = this.nodeId; this.bbox = bboxTo; this.cellId = bboxTo.getName(); this.nodeId = getVertexId( this.sheetId, this.cellId ); this.wb.needRecalc.nodes[this.nodeId] = [this.sheetId, this.cellId ]; this.wb.needRecalc.length++; //добавляем новые slave и master for ( var i in this.slaveEdges ) { var slave = this.slaveEdges[i]; slave.addMasterEdge( this ); } for ( var i in this.masterEdges ) { var master = this.masterEdges[i]; master.addSlaveEdge( this ); } }, moveOuter:function ( from, to, oFormulas ) { if ( (from.r1 == to.r1 && from.c1 == to.c1) || (from.r2 == to.r2 && from.c2 == to.c2) ) { var _sn = this.getSlaveEdges(); for ( var _id in _sn ) { var slave = _sn[_id]; var cell = slave.returnCell(); if ( cell && cell.formulaParsed ) { cell.formulaParsed.stretchArea( this, from, to ); var formula = cell.formulaParsed.assemble(); if ( null != formula ) { if ( oFormulas ) oFormulas[slave.nodeId] = { node:slave, formula:formula }; else slave.setFormula( formula, true, false ); } } } } else { if ( oFormulas ) { if ( null == oFormulas[this.nodeId] ) oFormulas[this.nodeId] = { node:this, formula:null }; } else { var cell = this.returnCell(); if ( cell && cell.formulaParsed ) { this.wb.dependencyFormulas.deleteMasterNodes2( this.sheetId, this.cellId ); addToArrRecalc( this.sheetId, cell ); } } var _sn = this.getSlaveEdges(); for ( var _id in _sn ) { var slave = _sn[_id] var cell = slave.returnCell(); if ( cell && cell.formulaParsed ) { cell.formulaParsed.shiftCells( this, from, to ); var formula = cell.formulaParsed.assemble(); if ( null != formula ) { if ( oFormulas ) oFormulas[slave.nodeId] = { node:slave, formula:formula }; else slave.setFormula( formula, true, false ); } } } } }, //добавляем ведущую ячейку. addMasterEdge:function ( node ) { if ( !this.masterEdges ) { this.masterEdges = {}; } if ( !this.masterEdges[node.nodeId] ) { this.masterEdges[node.nodeId] = node; this.refCount++; } }, //добавляем зависимую(ведомую) ячейку. addSlaveEdge:function ( node ) { if ( !this.slaveEdges ) { this.slaveEdges = {}; } if ( !this.slaveEdges[node.nodeId] ) { this.slaveEdges[node.nodeId] = node; this.refCount++; } }, getMasterEdges:function () { return this.masterEdges; }, getSlaveEdges:function () { return this.slaveEdges; }, getSlaveEdges2:function () { var ret = {}, count = 0; for ( var id in this.slaveEdges ) { ret[id] = this.slaveEdges[id]; count++; } if ( count > 0 ) return ret; else return null; }, //удаляем ребро между конкретной ведущей ячейки. deleteMasterEdge:function ( node ) { if ( this.masterEdges ) { delete this.masterEdges[node.nodeId]; this.refCount--; } }, //удаляем ребро между конкретной зависимой(ведомой) ячейки. deleteSlaveEdge:function ( node ) { if ( this.slaveEdges ) { delete this.slaveEdges[node.nodeId]; this.refCount--; } }, //очищаем все ребра по ведущим ячейкам. deleteAllMasterEdges:function () { var ret = {}; for ( var id in this.masterEdges ) { var masterEdge = this.masterEdges[id]; masterEdge.deleteSlaveEdge( this ); this.masterEdges[id] = null; delete this.masterEdges[id]; this.refCount--; ret[id] = masterEdge; } this.masterEdges = {}; return ret; }, //очищаем все ребра по ведомым ячейкам. deleteAllSlaveEdges:function () { var ret = {}; for ( var id in this.slaveEdges ) { var slaveEdge = this.slaveEdges[id]; slaveEdge.deleteMasterEdge( this ); this.slaveEdges[id] = null; delete this.slaveEdges[id]; this.refCount--; ret[id] = slaveEdge; } this.slaveEdges = {}; return ret; }, returnCell:function () { //todo return false; // if ( null == this.cell && this.wb && !this.isArea && this.Ref !== null && this.Ref !== undefined ) { // var ws = this.wb.getWorksheetById( this.sheetId ); // if ( ws ) // this.cell = ws._getCellNoEmpty( this.bbox.r1, this.bbox.c1 ); // } // return this.cell; }, getAscCDefName:function () { var a = this.wb.getWorksheetById( this.sheetId ); return new Asc.asc_CDefName( this.Name, this.Ref, this.sheetId == "WB" ? null : a ? a.getIndex() : null, this.isTable, this.Hidden, this.isLock ); }, changeDefName:function ( newName ) { this.cellId = newName.Name.toLowerCase(); this.Ref = newName.Ref; this.Name = newName.Name; this.nodeId = getDefNameVertexId( this.sheetId, newName.Name ); }, relinkRef:function(oName, nName){ if( this.parsedRef && this.parsedRef.isParsed ){ this.Ref = this.parsedRef.assemble(); } }, renameDefNameToCollaborate:function(name){ var lastname = this.Name; //из-за особенностей реализации формул, сначала делаем parse со старым именем, потом преименовываем, потом assemble var aFormulas = []; //переименование для отправки изменений for(var i = 0, length = this.wb.aCollaborativeActions.length; i < length; ++i) { var aPointActions = this.wb.aCollaborativeActions[i]; for (var j = 0, length2 = aPointActions.length; j < length2; ++j) { var action = aPointActions[j]; if (AscCommonExcel.g_oUndoRedoWorkbook == action.oClass) { if (AscCH.historyitem_Workbook_DefinedNamesAdd == action.nActionType) { if (lastname == action.oData.newName.Name) action.oData.newName.Name = name; } } else if (AscCommonExcel.g_oUndoRedoCell == action.oClass) { if (action.oData instanceof UndoRedoData_CellSimpleData) { if (action.oData.oNewVal instanceof UndoRedoData_CellValueData) { var oNewVal = action.oData.oNewVal; if (null != oNewVal.formula && -1 != oNewVal.formula.indexOf(lastname)) { var oParser = new parserFormula(oNewVal.formula, "A1", this.wb.getWorksheet(0)); oParser.parse(); aFormulas.push({ formula: oParser, value: oNewVal }); } } } } } } var clone = this.clone(); clone.Name = name; this.wb.editDefinesNames( this.getAscCDefName(), clone.getAscCDefName() ); for(var i = 0, length = aFormulas.length; i < length; ++i) { var item = aFormulas[i]; item.value.formula = item.formula.assemble(); } }, rebuild:function(){ if(this.Ref){ this.deleteAllMasterEdges(); this.parsedRef = new parserFormula(this.Ref, "", this.wb.getWorksheet(0)); this.parsedRef.parse(); this.parsedRef.buildDependencies(null,this); } } }; function getVertexId(sheetId, cellId){ return sheetId + AscCommon.g_cCharDelimiter + cellId; } function getDefNameVertexId(scope, name){ return ( scope === null || scope === undefined ? "WB" : scope ) + AscCommon.g_cCharDelimiter + name.toLowerCase(); } function addToArrRecalc(sheetId, cell){ var temp = arrRecalc[sheetId]; if( !temp ) { temp = []; arrRecalc[sheetId] = temp; } temp.push(cell); } function addToArrDefNameRecalc(name){ arrDefNameRecalc[name.nodeId] = name; } function buildDefNameAfterRenameWorksheet() { var dN; for(var id in arrDefNameRecalc ){ dN = arrDefNameRecalc[id]; if( !dN.parsedRef && dN.Ref ){ dN.parsedRef = new parserFormula(dN.Ref, "", ws.workbook.getWorksheet(0)); dN.parsedRef.parse(); } } } function angleFormatToInterface(val) { var nRes = 0; if(0 <= val && val <= 180) nRes = val <= 90 ? val : 90 - val; return nRes; } function angleFormatToInterface2(val) { if(g_nVerticalTextAngle == val) return val; else return angleFormatToInterface(val); } function angleInterfaceToFormat(val) { var nRes = val; if(-90 <= val && val <= 90) { if(val < 0) nRes = 90 - val; } else if(g_nVerticalTextAngle != val) nRes = 0; return nRes; } function getUniqueKeys(array) { var i, o = {}; for (i = 0; i < array.length; ++i) { o[array[i]] = !o.hasOwnProperty(array[i]); } return o; } //------------------------------------------------------------------------------------------------- /** * @constructor */ function Workbook(eventsHandlers, oApi){ this.oApi = oApi; this.handlers = eventsHandlers; this.needRecalc = {nodes: {}, length:0}; this.dependencyFormulas = new DependencyGraph(this); this.nActive = 0; this.theme = null; this.clrSchemeMap = null; this.DefinedNames = {}; this.oRealDefinedNames = {}; // this.oNameGenerator = new NameGenerator(this); this.CellStyles = new AscCommonExcel.CCellStyles(); this.TableStyles = new Asc.CTableStyles(); this.oStyleManager = new AscCommonExcel.StyleManager(); this.calcChain = []; this.aComments = []; // Комментарии к документу this.aCommentsCoords = []; this.aWorksheets = []; this.aWorksheetsById = {}; this.cwf = {}; this.aCollaborativeActions = []; this.bCollaborativeChanges = false; this.bUndoChanges = false; this.bRedoChanges = false; this.aCollaborativeChangeElements = []; this.wsHandlers = null; this.openErrors = []; this.lockCounter = 0; } Workbook.prototype.init=function(bNoBuildDep){ if(this.nActive < 0) this.nActive = 0; if(this.nActive >= this.aWorksheets.length) this.nActive = this.aWorksheets.length - 1; var self = this; this.wsHandlers = new AscCommonExcel.asc_CHandlersList( /*handlers*/{ "changeRefTablePart" : function ( displayName, ref ) { self.dependencyFormulas.changeTableName( displayName, null, ref ); }, "changeColumnTablePart": function ( tableName ) { self.dependencyFormulas.rebuildTable( tableName ); }, "delTable" : function ( name, ws ) { self.dependencyFormulas.delTableName( name, ws ); } } ); //charts for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var ws = this.aWorksheets[i]; ws.initPostOpen(this.wsHandlers); } if(!bNoBuildDep){ /* buildDependency необходимо запускать для построения графа зависимостей между ячейками. Сортировка графа производится при необходимости пересчета формул: при открытии документа если есть ячейки помеченные как пересчитываемые или есть ячейки без значения. */ this.buildDependency(); this.sortDependency(); } }; Workbook.prototype.rebuildColors=function(){ AscCommonExcel.g_oColorManager.rebuildColors(); for(var i = 0 , length = this.aWorksheets.length; i < length; ++i) this.aWorksheets[i].rebuildColors(); }; Workbook.prototype.getDefaultFont=function(){ return g_oDefaultFormat.Font.fn; }; Workbook.prototype.getDefaultSize=function(){ return g_oDefaultFormat.Font.fs; }; Workbook.prototype.getActive=function(){ return this.nActive; }; Workbook.prototype.getActiveWs = function () { return this.getWorksheet(this.nActive); }; Workbook.prototype.setActive=function(index){ if(index >= 0 && index < this.aWorksheets.length){ this.nActive = index; return true; } return false; }; Workbook.prototype.getWorksheet=function(index){ //index 0-based if(index >= 0 && index < this.aWorksheets.length){ return this.aWorksheets[index]; } return null; }; Workbook.prototype.getWorksheetById=function(id){ return this.aWorksheetsById[id]; }; Workbook.prototype.getWorksheetByName=function(name){ for(var i = 0; i < this.aWorksheets.length; i++) if(this.aWorksheets[i].getName() == name){ return this.aWorksheets[i]; } return null; }; Workbook.prototype.getWorksheetIndexByName=function(name){ for(var i = 0; i < this.aWorksheets.length; i++) if(this.aWorksheets[i].getName() == name){ return i; } return null; }; Workbook.prototype.getWorksheetCount=function(){ return this.aWorksheets.length; }; Workbook.prototype.createWorksheet=function(indexBefore, sName, sId){ History.Create_NewPoint(); History.TurnOff(); var wsActive = this.getActiveWs(); var oNewWorksheet = new Woorksheet(this, this.aWorksheets.length, sId); if (this.checkValidSheetName(sName)) oNewWorksheet.sName = sName; oNewWorksheet.initPostOpen(this.wsHandlers); if(null != indexBefore && indexBefore >= 0 && indexBefore < this.aWorksheets.length) this.aWorksheets.splice(indexBefore, 0, oNewWorksheet); else { indexBefore = this.aWorksheets.length; this.aWorksheets.push(oNewWorksheet); } this.aWorksheetsById[oNewWorksheet.getId()] = oNewWorksheet; this._updateWorksheetIndexes(wsActive); History.TurnOn(); this._insertWorksheetFormula(oNewWorksheet.index); History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(indexBefore, oNewWorksheet.getName(), null, oNewWorksheet.getId())); History.SetSheetUndo(wsActive.getId()); History.SetSheetRedo(oNewWorksheet.getId()); return oNewWorksheet.index; }; Workbook.prototype.copyWorksheet=function(index, insertBefore, sName, sId, bFromRedo){ //insertBefore - optional if(index >= 0 && index < this.aWorksheets.length){ History.TurnOff(); var wsActive = this.getActiveWs(); var wsFrom = this.aWorksheets[index]; var newSheet = wsFrom.clone(sId, sName); newSheet.initPostOpen(this.wsHandlers); if(null != insertBefore && insertBefore >= 0 && insertBefore < this.aWorksheets.length){ //помещаем новый sheet перед insertBefore this.aWorksheets.splice(insertBefore, 0, newSheet); } else{ //помещаем новый sheet в конец this.aWorksheets.push(newSheet); } this.aWorksheetsById[newSheet.getId()] = newSheet; this._updateWorksheetIndexes(wsActive); History.TurnOn(); this._insertWorksheetFormula(insertBefore); this.dependencyFormulas.copyDefNameByWorksheet( wsFrom.getId(), newSheet.getId() ); //для формул. создаем копию this.cwf[this.Id] для нового листа. if ( this.cwf[wsFrom.getId()] ){ var cwf = { cells:{} }; var newSheetId = newSheet.getId(); var cwfFrom = this.cwf[wsFrom.getId()]; this.cwf[newSheetId] = cwf; for( var id in cwfFrom.cells ){ cwf.cells[id] = cwfFrom.cells[id]; this.needRecalc.nodes[getVertexId(newSheetId, id)] = [newSheetId, id]; this.needRecalc.length++; } newSheet._BuildDependencies(cwf.cells); } History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetAdd, null, null, new UndoRedoData_SheetAdd(insertBefore, newSheet.getName(), wsFrom.getId(), newSheet.getId())); History.SetSheetUndo(wsActive.getId()); History.SetSheetRedo(newSheet.getId()); if(!(bFromRedo === true)) { wsFrom.copyDrawingObjects(newSheet, wsFrom); } this.sortDependency(); } }; Workbook.prototype.insertWorksheet = function (index, sheet, cwf) { var wsActive = this.getActiveWs(); if(null != index && index >= 0 && index < this.aWorksheets.length){ //помещаем новый sheet перед insertBefore this.aWorksheets.splice(index, 0, sheet); } else{ //помещаем новый sheet в конец this.aWorksheets.push(sheet); } this.aWorksheetsById[sheet.getId()] = sheet; this._updateWorksheetIndexes(wsActive); this._insertWorksheetFormula(index); this._insertTablePartsName(sheet); //восстанавливаем список ячеек с формулами для sheet this.cwf[sheet.getId()] = cwf; sheet._BuildDependencies(cwf.cells); this.sortDependency(); }; Workbook.prototype._insertTablePartsName = function (sheet) { if(sheet && sheet.TableParts && sheet.TableParts.length) { for(var i = 0; i < sheet.TableParts.length; i++) { var oNewTable = sheet.TableParts[i]; this.dependencyFormulas.addTableName(oNewTable.DisplayName, sheet, oNewTable.Ref); } } }; Workbook.prototype._insertWorksheetFormula=function(index){ if( index > 0 && index < this.aWorksheets.length - 1 ){ var oWsTo = this.aWorksheets[index - 1]; var nodesSheetTo = this.dependencyFormulas.getNodeBySheetId(oWsTo.getId()); for( var i = 0; i < nodesSheetTo.length; i++ ){ var se = nodesSheetTo[i].getSlaveEdges(); if(se) { for( var id in se ){ var slave = se[id]; if(slave.isDefinedName){ continue; } var cell = slave.returnCell(); if( cell && cell.formulaParsed && cell.formulaParsed.is3D ) { if(cell.formulaParsed.insertSheet(index)) slave.setFormula(null, false, true); } } } } } }; Workbook.prototype.replaceWorksheet=function(indexFrom, indexTo){ if(indexFrom >= 0 && indexFrom < this.aWorksheets.length && indexTo >= 0 && indexTo < this.aWorksheets.length){ History.Create_NewPoint(); History.TurnOff(); var wsActive = this.getActiveWs(); var oWsFrom = this.aWorksheets[indexFrom]; var oWsTo = this.aWorksheets[indexTo]; var tempW = { wFN: oWsFrom.getName(), wFI: indexFrom, wFId: oWsFrom.getId(), wTN: oWsTo.getName(), wTI: indexTo, wTId: oWsTo.getId() }; //переводим обратно в индекс sheet перед которым надо вставить if(tempW.wFI < tempW.wTI) tempW.wTI++; /* Формулы: перестройка графа для трехмерных формул вида Sheet1:Sheet3!A1:A3, Sheet1:Sheet3!A1. пересчет трехмерных формул, перестройка формул при изменении положения листа: Sheet1, Sheet2, Sheet3, Sheet4 - Sheet1:Sheet4!A1 -> Sheet4, Sheet1, Sheet2, Sheet3 - Sheet1:Sheet3!A1; */ this.lockDraw(); var a = this.dependencyFormulas.getNodeBySheetId(tempW.wFId); for(var i=0;i<a.length;i++){ var se = a[i].getSlaveEdges(); if(se){ for(var id in se){ var slave = se[id]; if( slave.isDefinedName ) continue; var cell = slave.returnCell(); if( cell && cell.formulaParsed && cell.formulaParsed.is3D ) { var nMoveRes = cell.formulaParsed.moveSheet(tempW, true); if(2 == nMoveRes) slave.setFormula(cell.formulaParsed.assemble(), true, true); else if(1 == nMoveRes) slave.setFormula(null, false, true); } } } } History.TurnOn(); var movedSheet = this.aWorksheets.splice(indexFrom, 1); this.aWorksheets.splice(indexTo, 0, movedSheet[0]); this._updateWorksheetIndexes(wsActive); this._insertWorksheetFormula(tempW.wTI); History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetMove, null, null, new UndoRedoData_FromTo(indexFrom, indexTo), true); this.unLockDraw(); this.buildRecalc(); } }; Workbook.prototype.findSheetNoHidden = function (nIndex) { var i, ws, oRes = null, bFound = false, countWorksheets = this.getWorksheetCount(); for (i = nIndex; i < countWorksheets; ++i) { ws = this.getWorksheet(i); if (false === ws.getHidden()) { oRes = ws; bFound = true; break; } } // Не нашли справа, ищем слева от текущего if (!bFound) { for (i = nIndex - 1; i >= 0; --i) { ws = this.getWorksheet(i); if (false === ws.getHidden()) { oRes = ws; break; } } } return oRes; }; Workbook.prototype.removeWorksheet=function(nIndex, outputParams){ //проверяем останется ли хоть один нескрытый sheet var bEmpty = true; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var worksheet = this.aWorksheets[i]; if(false == worksheet.getHidden() && i != nIndex) { bEmpty = false; break; } } if(bEmpty) return -1; var removedSheet = this.getWorksheet(nIndex); if(removedSheet) { History.Create_NewPoint(); var removedSheetId = removedSheet.getId(); this.lockDraw(); var retRes = this.dependencyFormulas.removeDefNameBySheet( removedSheetId ), nSE, se, seUndoRedo = []; var a = this.dependencyFormulas.getNodeBySheetId(removedSheetId); for(var i = 0; i < a.length; i++) { var node = a[i]; var se = node.getSlaveEdges(); if(se){ for(var id in se){ var slave = se[id]; var cell = slave.returnCell(); if( cell && cell.formulaParsed && cell.formulaParsed.is3D ) { if(cell.formulaParsed.removeSheet(removedSheetId)) slave.setFormula(cell.formulaParsed.assemble(true), true, true); } } } } //по всем удаленным листам пробегаемся и удаляем из workbook.cwf (cwf - cells with forluma) элементы с названием соответствующего листа. this.dependencyFormulas.removeNodeBySheetId(removedSheetId); var _cwf = this.cwf[removedSheetId]; delete this.cwf[removedSheetId]; if ( retRes ) { /* * #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка. * для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон. * #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку; * удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу. * */ for( var defNameID in retRes ){ nSE = retRes[defNameID].getSlaveEdges(); retRes[defNameID].deleteAllMasterEdges(); for ( var id in nSE ) { // seUndoRedo.push( id ); se = nSE[id]; se.deleteMasterEdge( retRes[defNameID] ); this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.needRecalc.length++; se = se.returnCell(); se ? function () { se.setFormula( se.formulaParsed.assemble() ); se.formulaParsed.isParsed = false; se.formulaParsed.parse(); se.formulaParsed.buildDependencies(); }() : null; } } } var wsActive = this.getActiveWs(); var oVisibleWs = null; this.aWorksheets.splice(nIndex, 1); delete this.aWorksheetsById[removedSheetId]; if (nIndex == this.getActive()) { oVisibleWs = this.findSheetNoHidden(nIndex); if (null != oVisibleWs) wsActive = oVisibleWs; } History.Add(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetRemove, null, null, new AscCommonExcel.UndoRedoData_SheetRemove(nIndex, removedSheetId, removedSheet, _cwf)); if (null != oVisibleWs) { History.SetSheetUndo(removedSheetId); History.SetSheetRedo(wsActive.getId()); } if(null != outputParams) { outputParams.sheet = removedSheet; outputParams.cwf = _cwf; } this._updateWorksheetIndexes(wsActive); this.unLockDraw(); this.buildRecalc(); return wsActive.getIndex(); } return -1; }; Workbook.prototype._updateWorksheetIndexes = function (wsActive) { for(var i = 0, length = this.aWorksheets.length; i < length; ++i) this.aWorksheets[i]._setIndex(i); if (null != wsActive) this.setActive(wsActive.getIndex()); }; Workbook.prototype.checkUniqueSheetName=function(name){ var workbookSheetCount = this.getWorksheetCount(); for (var i = 0; i < workbookSheetCount; i++){ if (this.getWorksheet(i).getName() == name) return i; } return -1; }; Workbook.prototype.checkValidSheetName=function(name){ return (name && name.length < g_nSheetNameMaxLength); }; Workbook.prototype.getUniqueSheetNameFrom=function(name, bCopy){ var nIndex = 1; var sNewName = ""; var fGetPostfix = null; if(bCopy) { var result = /^(.*)\((\d)\)$/.exec(name); if(result) { fGetPostfix = function(nIndex){return "(" + nIndex +")";}; name = result[1]; } else { fGetPostfix = function(nIndex){return " (" + nIndex +")";}; name = name; } } else { fGetPostfix = function(nIndex){return nIndex.toString();}; } var workbookSheetCount = this.getWorksheetCount(); while(nIndex < 10000) { var sPosfix = fGetPostfix(nIndex); sNewName = name + sPosfix; if(sNewName.length > g_nSheetNameMaxLength) { name = name.substring(0, g_nSheetNameMaxLength - sPosfix.length); sNewName = name + sPosfix; } var bUniqueName = true; for (var i = 0; i < workbookSheetCount; i++){ if (this.getWorksheet(i).getName() == sNewName) { bUniqueName = false; break; } } if(bUniqueName) break; nIndex++; } return sNewName; }; Workbook.prototype._generateFontMap=function(){ var oFontMap = { "Arial" : 1 }; if(null != g_oDefaultFormat.Font.fn) oFontMap[g_oDefaultFormat.Font.fn] = 1; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) this.aWorksheets[i].generateFontMap(oFontMap); this.CellStyles.generateFontMap(oFontMap); return oFontMap; }; Workbook.prototype.generateFontMap=function(){ var oFontMap = this._generateFontMap(); var aRes = []; for(var i in oFontMap) aRes.push(i); return aRes; }; Workbook.prototype.generateFontMap2=function(){ var oFontMap = this._generateFontMap(); var aRes = []; for(var i in oFontMap) aRes.push(new AscFonts.CFont(i, 0, "", 0)); return aRes; }; Workbook.prototype.recalcWB = function(isRecalcWB){ //todo if ( this.dependencyFormulas.getNodesLength() > 0 ) { var aNodes = isRecalcWB ? this.dependencyFormulas.getAll() : this.dependencyFormulas.getNodeBySheetIdAll(this.getWorksheet(this.getActive()).getId()); var nR = this.needRecalc; for ( var i in aNodes ) { var node = aNodes[i]; if ( !node.isArea ) { nR.nodes[node.nodeId] = [node.sheetId, node.cellId]; nR.length++; } } this.sortDependency(); } }; Workbook.prototype.checkDefName = function ( checkName, scope ) { var rxTest = AscCommon.rx_defName.test( checkName ), res = new Asc.asc_CCheckDefName(); if ( !rxTest ) { res.status = false; res.reason = c_oAscDefinedNameReason.WrongName; return res; } if( scope !== null ){ scope = this.getWorksheet(scope).getId(); } var defName = this.dependencyFormulas.getDefNameNode(getDefNameVertexId(scope, checkName)); if(defName){ defName = defName.getAscCDefName(); res.status = false; if(defName.isLock){ res.reason = c_oAscDefinedNameReason.IsLocked; } else if( defName.Ref == null ){ res.reason = c_oAscDefinedNameReason.NameReserved; } else{ res.reason = c_oAscDefinedNameReason.Existed; } } else{ res.status = true; res.reason = c_oAscDefinedNameReason.OK; } return res; }; Workbook.prototype.isDefinedNamesExists = function ( name, sheetId ) { var n = name.toLowerCase(); return !!this.dependencyFormulas.defNameList[getDefNameVertexId(sheetId, n)]; }; Workbook.prototype.getDefinedNamesWB = function (defNameListId) { var names = [], name, thas = this, activeWS; /*c_oAscGetDefinedNamesList. Worksheet : 0, WorksheetWorkbook : 1, All*/ function getNames(id,arr){ var listDN = thas.dependencyFormulas.defNameSheets[id], name; for ( var id in listDN ) { name = listDN[id] if ( name.Ref && !name.Hidden && name.Name.indexOf("_xlnm") < 0 ) { if( name.isTable || name.parsedRef && name.parsedRef.isParsed && name.parsedRef.countRef == 1 && name.parsedRef.outStack.length == 1 && name.parsedRef.calculate().errorType !== AscCommonExcel.cErrorType.bad_reference ){ arr.push( name.getAscCDefName() ); } } } } function sort(a,b){ if (a.Name > b.Name) return 1; if (a.Name < b.Name) return -1; } switch(defNameListId){ case c_oAscGetDefinedNamesList.Worksheet: case c_oAscGetDefinedNamesList.WorksheetWorkbook: activeWS = this.getActiveWs(); getNames(activeWS.getId(),names); if( c_oAscGetDefinedNamesList.WorksheetWorkbook ){ getNames("WB",names); } break; case c_oAscGetDefinedNamesList.All: default: for ( var id in this.dependencyFormulas.defNameList ) { name = this.dependencyFormulas.defNameList[id].getAscCDefName() if ( name.Ref && !name.Hidden && name.Name.indexOf("_xlnm") < 0 ) { names.push( name ); } } break; } return names.sort(sort); }; Workbook.prototype.getDefinesNames = function ( name, sheetId ) { return this.dependencyFormulas.getDefNameNodeByName( name, sheetId ); }; Workbook.prototype.getDefinedName = function ( name ) { var ws = this.getWorksheet( name.LocalSheetId ), sheetId = null; ws ? sheetId = ws.getId() : null; return this.dependencyFormulas.getDefNameNodeByName( name.Name, sheetId ); }; Workbook.prototype.delDefinesNames = function ( defName, bUndo ) { History.Create_NewPoint(); var retRes = false; retRes = this.dependencyFormulas.removeDefName( defName.LocalSheetId, defName.Name ); if ( retRes ) { /* * #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка. * для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон. * #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку; * удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу. * */ var nSE, se, seUndoRedo = []; nSE = retRes.getSlaveEdges(); retRes.deleteAllMasterEdges(); for ( var id in nSE ) { seUndoRedo.push( id ); se = nSE[id]; addToArrRecalc(se.sheetId, se.cell); this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.needRecalc.length++; } if(!bUndo) this.buildRecalc(); History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesDelete, null, null, new UndoRedoData_DefinedNames( defName.Name, defName.Ref, defName.LocalSheetId, defName.isTable, seUndoRedo ) ); } return retRes; }; Workbook.prototype.editDefinesNames = function ( oldName, newName, bUndo ) { var newN = newName.Name.toLowerCase(), retRes = null, rename = false, nSE, se; if ( !AscCommon.rx_defName.test( newN ) || !newName.Ref || newName.Ref.length == 0 ) { return retRes; } if ( oldName ) { this.buildRecalc(true, true); retRes = this.dependencyFormulas.changeDefName( oldName, newName ); rename = true; } else { retRes = this.dependencyFormulas.addDefinedNameNode( newName.Name, newName.LocalSheetId, newName.Ref, newName.Hidden, bUndo ); } if ( retRes ) { History.Create_NewPoint(); /* #1. поменяли название - перестроили формулу. нужно вызвать пересборку формул в ячейках, в которыйх есть эта именованная ссылка. для этого пробегаемся по всем slave, и вызываем пересборку. в результате должна получиться новая формула, где используется новый диапазон. #2. поменяли диапазон. нужно перестроить граф зависимосте и пересчитать формулу. находим диапазон; меняем в нем ссылку; разбираем ссылку; удаляем старые master и добавляем новые, которые получились в результате разбора новой ссылки; пересчитываем формулу.*/ if( !rename ){ retRes = this.dependencyFormulas.getDefNameNodeByName(newName.Name) } if(retRes){ nSE = retRes.getSlaveEdges(); } for ( var id in nSE ) { se = nSE[id]; se.deleteMasterEdge( retRes ); this.needRecalc.nodes[se.nodeId] = [se.sheetId, se.cellId ]; this.needRecalc.length++; addToArrRecalc(se.sheetId, se.cell); se = se.returnCell(); if ( se ) { se.setFormula( se.formulaParsed.assemble() ); if ( !rename ) { se.formulaParsed.setFormula(se.sFormula); } } } if ( rename ) { History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesChange, null, null, new UndoRedoData_DefinedNamesChange( oldName, newName ) ); } else { History.Add( AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_DefinedNamesAdd, null, null, new UndoRedoData_DefinedNamesChange( oldName, newName ) ); } /*if(retRes){ retRes = retRes.getAscCDefName(); }*/ } if(!bUndo) this.buildRecalc(); return retRes; }; Workbook.prototype.findDefinesNames = function ( ref, sheetId ) { return this.dependencyFormulas.getDefNameNodeByRef( ref, sheetId ); }; Workbook.prototype.unlockDefName = function(){ this.dependencyFormulas.unlockDefName(); }; Workbook.prototype.checkDefNameLock = function(){ return this.dependencyFormulas.checkDefNameLock(); }; Workbook.prototype.getUniqueDefinedNameFrom=function(name, bCopy){ var nIndex = 1, dnNewName = "", fGetPostfix = null, name = name.Name, sheetId = name.sheetId; if(bCopy) { var result = /^(.*)(\d)$/.exec(name); if(result) { fGetPostfix = function(nIndex){return "" + nIndex;}; name = result[1]; } else { fGetPostfix = function(nIndex){return "_" + nIndex;}; name = name; } } else { fGetPostfix = function(nIndex){return nIndex.toString();}; } while(nIndex < 10000) { var sPosfix = fGetPostfix(nIndex); dnNewName = name + sPosfix; var bUniqueName = false; if(!this.isDefinedNamesExists( dnNewName, sheetId )){ bUniqueName = true; break; } if(bUniqueName) break; nIndex++; } return dnNewName; }; Workbook.prototype.buildDependency = function(){ this.dependencyFormulas.clear(); // this.dependencyFormulas = null; // this.dependencyFormulas = new DependencyGraph(this); for(var i in this.cwf){ this.getWorksheetById(i)._BuildDependencies(this.cwf[i].cells); } }; Workbook.prototype.recalcDependency = function(f,bad,notRecalc){ if(f.length > 0){ var sr = {}; for(var i = 0; i < f.length; i++){ var sheetID = f[i].sheetId, cellID = f[i].cellId, selectedSheet; if( cellID.indexOf(":") > -1 ) continue; var l = new CellAddress(cellID); var lRow = l.getRow(), lCol = l.getCol(); if( !(sheetID in sr) ){ sr[sheetID] = {max:new CellAddress(cellID),min:new CellAddress(cellID)} } selectedSheet = sr[sheetID]; if ( selectedSheet.min.getRow() > lRow ) selectedSheet.min = new CellAddress( lRow, selectedSheet.min.getCol() ); if ( selectedSheet.min.getCol() > lCol ) selectedSheet.min = new CellAddress( selectedSheet.min.getRow(), lCol ); if ( selectedSheet.max.getRow() < lRow ) selectedSheet.max = new CellAddress( lRow, selectedSheet.max.getCol() ); if ( selectedSheet.max.getCol() < lCol ) selectedSheet.max = new CellAddress( selectedSheet.max.getRow(), lCol ); if( !notRecalc ) this.getWorksheetById( sheetID )._RecalculatedFunctions( cellID, bad ); } return sr; } }; Workbook.prototype._SerializeHistoryBase64 = function (oMemory, item, aPointChangesBase64) { if (!item.LocalChange) { var nPosStart = oMemory.GetCurPosition(); item.Serialize(oMemory, this.oApi.collaborativeEditing); var nPosEnd = oMemory.GetCurPosition(); var nLen = nPosEnd - nPosStart; if (nLen > 0) aPointChangesBase64.push(nLen + ";" + oMemory.GetBase64Memory2(nPosStart, nLen)); } }; Workbook.prototype.SerializeHistory = function(){ var aRes = []; //соединяем изменения, которые были до приема данных с теми, что получились после. var worksheets = this.aWorksheets, t, j, length2; for(t = 0; t < worksheets.length; ++t) { worksheets[t] && worksheets[t].refreshContentChanges(); } var aActions = this.aCollaborativeActions.concat(History.GetSerializeArray()); if(aActions.length > 0) { var oMemory = new AscCommon.CMemory(); var bChangeSheetPlace = false; for(var i = 0, length = aActions.length; i < length; ++i) { var aPointChanges = aActions[i]; bChangeSheetPlace = false; for (j = 0, length2 = aPointChanges.length; j < length2; ++j) { var item = aPointChanges[j]; if (AscCommonExcel.g_oUndoRedoWorkbook == item.oClass) { if (AscCH.historyitem_Workbook_SheetAdd == item.nActionType || AscCH.historyitem_Workbook_SheetRemove == item.nActionType || AscCH.historyitem_Workbook_SheetMove == item.nActionType) bChangeSheetPlace = true; } else if (AscCommonExcel.g_oUndoRedoWorksheet === item.oClass && AscCH.historyitem_Worksheet_Hide === item.nActionType) { bChangeSheetPlace = true; } this._SerializeHistoryBase64(oMemory, item, aRes); } var oUndoRedoData_SheetPositions; if (bChangeSheetPlace) { //создаем еще один элемент в undo/redo - взаимное расположение Sheet, чтобы не запутываться в add, move событиях //добавляем не после конца aActions, чтобы можно было делать undo/redo и просто удалять хвост изменений. var oSheetPlaceData = []; for (j = 0, length2 = this.aWorksheets.length; j < length2; ++j) oSheetPlaceData.push(this.aWorksheets[j].getId()); oUndoRedoData_SheetPositions = new UndoRedoData_SheetPositions(oSheetPlaceData); } else oUndoRedoData_SheetPositions = new UndoRedoData_SheetPositions(); this._SerializeHistoryBase64(oMemory, new UndoRedoItemSerializable(AscCommonExcel.g_oUndoRedoWorkbook, AscCH.historyitem_Workbook_SheetPositions, null, null, oUndoRedoData_SheetPositions), aRes); } this.aCollaborativeActions = []; } return aRes; }; Workbook.prototype.DeserializeHistory = function(aChanges, fCallback){ var oThis = this; //сохраняем те изменения, которые были до приема данных, потому что дальше undo/redo будет очищено this.aCollaborativeActions = this.aCollaborativeActions.concat(History.GetSerializeArray()); if(aChanges.length > 0) { this.bCollaborativeChanges = true; //собираем общую длину var dstLen = 0; var aIndexes = [], i, length = aChanges.length, sChange; for(i = 0; i < length; ++i) { sChange = aChanges[i]; var nIndex = sChange.indexOf(";"); if (-1 != nIndex) { dstLen += parseInt(sChange.substring(0, nIndex)); nIndex++; } aIndexes.push(nIndex); } var pointer = g_memory.Alloc(dstLen); var stream = new AscCommon.FT_Stream2(pointer.data, dstLen); stream.obj = pointer.obj; var nCurOffset = 0; //пробегаемся первый раз чтобы заполнить oFontMap var oFontMap = {};//собираем все шрифтры со всех изменений var aUndoRedoElems = []; for (i = 0; i < length; ++i) { sChange = aChanges[i]; var oBinaryFileReader = new AscCommonExcel.BinaryFileReader(); nCurOffset = oBinaryFileReader.getbase64DecodedData2(sChange, aIndexes[i], stream, nCurOffset); var item = new UndoRedoItemSerializable(); item.Deserialize(stream); if (AscCommonExcel.g_oUndoRedoWorkbook == item.oClass && AscCH.historyitem_Workbook_AddFont == item.nActionType) { for (var k = 0, length3 = item.oData.elem.length; k < length3; ++k) oFontMap[item.oData.elem[k]] = 1; } aUndoRedoElems.push(item); } window["Asc"]["editor"]._loadFonts(oFontMap, function(){ var wsViews = window["Asc"]["editor"].wb.wsViews; if(oThis.oApi.collaborativeEditing.getFast()){ AscCommon.CollaborativeEditing.Clear_DocumentPositions(); } for(var i in wsViews) { if(isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) && isRealObject(wsViews[i].objectRender.controller)) { if ( wsViews[i].isChartAreaEditMode ) { wsViews[i].isChartAreaEditMode = false; wsViews[i].arrActiveChartsRanges = []; } if(oThis.oApi.collaborativeEditing.getFast()){ var oState = wsViews[i].objectRender.saveStateBeforeLoadChanges(); if(oState){ if (oState.Pos) AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.Pos); if (oState.StartPos) AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.StartPos); if (oState.EndPos) AscCommon.CollaborativeEditing.Add_DocumentPosition(oState.EndPos); } } wsViews[i].objectRender.controller.resetSelection(); } } oFormulaLocaleInfo.Parse = false; oFormulaLocaleInfo.DigitSep = false; History.Clear(); History.Create_NewPoint(); History.SetSelection(null); History.SetSelectionRedo(null); var oRedoObjectParam = new AscCommonExcel.RedoObjectParam(); History.UndoRedoPrepare(oRedoObjectParam, false); for (var i = 0, length = aUndoRedoElems.length; i < length; ++i) { var item = aUndoRedoElems[i]; if ((null != item.oClass || (item.oData && typeof item.oData.sChangedObjectId === "string")) && null != item.nActionType) { if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"]) { if (!window["native"]["CheckNextChange"]()) break; } // TODO if(g_oUndoRedoGraphicObjects == item.oClass && item.oData.drawingData) // item.oData.drawingData.bCollaborativeChanges = true; History.RedoAdd(oRedoObjectParam, item.oClass, item.nActionType, item.nSheetId, item.oRange, item.oData); } } if(oThis.oApi.collaborativeEditing.getFast()){ for(var i in wsViews){ if(isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) && isRealObject(wsViews[i].objectRender.controller)){ var oState = wsViews[i].objectRender.getStateBeforeLoadChanges(); if(oState){ if (oState.Pos) AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.Pos); if (oState.StartPos) AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.StartPos); if (oState.EndPos) AscCommon.CollaborativeEditing.Update_DocumentPosition(oState.EndPos); } wsViews[i].objectRender.loadStateAfterLoadChanges(); } } } oFormulaLocaleInfo.Parse = true; oFormulaLocaleInfo.DigitSep = true; History.UndoRedoEnd(null, oRedoObjectParam, false); oThis.bCollaborativeChanges = false; History.Clear(); if(null != fCallback) fCallback(); }); } }; Workbook.prototype.DeserializeHistoryNative = function(oRedoObjectParam, data, isFull){ if(null != data) { this.bCollaborativeChanges = true; if(null == oRedoObjectParam) { var wsViews = window["Asc"]["editor"].wb.wsViews; for(var i in wsViews) { if(isRealObject(wsViews[i]) && isRealObject(wsViews[i].objectRender) && isRealObject(wsViews[i].objectRender.controller)) { if ( wsViews[i].isChartAreaEditMode ) { wsViews[i].isChartAreaEditMode = false; wsViews[i].arrActiveChartsRanges = []; } wsViews[i].objectRender.controller.resetSelection(); } } History.Clear(); History.Create_NewPoint(); History.SetSelection(null); History.SetSelectionRedo(null); oRedoObjectParam = new AscCommonExcel.RedoObjectParam(); History.UndoRedoPrepare(oRedoObjectParam, false); } var stream = new AscCommon.FT_Stream2(data, data.length); stream.obj = null; // Применяем изменения, пока они есть var _count = stream.GetLong(); var _pos = 4; for (var i = 0; i < _count; i++) { if (window["NATIVE_EDITOR_ENJINE"] === true && window["native"]["CheckNextChange"]) { if (!window["native"]["CheckNextChange"]()) break; } var _len = stream.GetLong(); _pos += 4; stream.size = _pos + _len; stream.Seek(_pos); stream.Seek2(_pos); var item = new UndoRedoItemSerializable(); item.Deserialize(stream); if ((null != item.oClass || (item.oData && typeof item.oData.sChangedObjectId === "string")) && null != item.nActionType) History.RedoAdd(oRedoObjectParam, item.oClass, item.nActionType, item.nSheetId, item.oRange, item.oData); _pos += _len; stream.Seek2(_pos); stream.size = data.length; } if(isFull){ History.UndoRedoEnd(null, oRedoObjectParam, false); History.Clear(); oRedoObjectParam = null; } this.bCollaborativeChanges = false; } return oRedoObjectParam; }; Workbook.prototype.getTableRangeForFormula = function(name, objectParam){ var res = null; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var ws = this.aWorksheets[i]; res = ws.getTableRangeForFormula(name, objectParam); if(res !== null){ res = {wsID:ws.getId(),range:res}; break; } } return res; }; Workbook.prototype.getTableIndexColumnByName = function(tableName, columnName){ var res = null; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var ws = this.aWorksheets[i]; res = ws.getTableIndexColumnByName(tableName, columnName); if(res !== null){ res = {wsID:ws.getId(), index: res}; break; } } return res; }; Workbook.prototype.getTableNameColumnByIndex = function(tableName, columnIndex){ var res = null; for(var i = 0, length = this.aWorksheets.length; i < length; ++i) { var ws = this.aWorksheets[i]; res = ws.getTableNameColumnByIndex(tableName, columnIndex); if(res !== null){ res = {wsID:ws.getId(), columnName: res}; break; } } return res; }; Workbook.prototype.updateSparklineCache = function(sheet, ranges) { for (var i = 0; i < this.aWorksheets.length; ++i) { this.aWorksheets[i].updateSparklineCache(sheet, ranges); } }; Workbook.prototype.lockDraw = function() { ++this.lockCounter; }; Workbook.prototype.unLockDraw = function() { if (0 < this.lockCounter) { --this.lockCounter; } }; Workbook.prototype.buildRecalc = function(notrec, bForce) { var ws; if (this.lockCounter > 0 && !bForce) { return; } if (!bForce) { for (var id in arrDefNameRecalc) { arrDefNameRecalc[id].rebuild(); } arrDefNameRecalc = {}; } for (var id in arrRecalc) { ws = this.getWorksheetById(id); if (ws) { var temp = arrRecalc[id]; var _rec = {}; for (var i = 0, length = temp.length; i < length; ++i) { var cell = temp[i]; var cellId = g_oCellAddressUtils.getCellId(cell.nRow, cell.nCol); _rec[cellId] = cellId; this.needRecalc.nodes[getVertexId(id, cellId)] = [id, cellId]; this.needRecalc.length++; } ws._BuildDependencies(_rec); } } arrRecalc = {}; if (!notrec) { this.sortDependency(); } }; Workbook.prototype.sortDependency = function(setCellFormat) { this.buildRecalc(true); var i; var nR = this.needRecalc; if (nR && (nR.length > 0)) { var oCleanCellCacheArea = {}; var oNodeDependence = this.dependencyFormulas.getNodeDependence(nR.nodes); for (i in oNodeDependence.oMasterNodes) this._sortDependency(oNodeDependence.oMasterNodes[i], oNodeDependence, oNodeDependence.oMasterAreaNodes, false, oCleanCellCacheArea, setCellFormat); //те AreaNodes var oCurMasterAreaNodes = oNodeDependence.oMasterAreaNodes; while (true) { var bEmpty = true; var oNewMasterAreaNodes = {}; for (i in oCurMasterAreaNodes) { bEmpty = false; this._sortDependency(oCurMasterAreaNodes[i], oNodeDependence, oNewMasterAreaNodes, false, oCleanCellCacheArea, setCellFormat); } oCurMasterAreaNodes = oNewMasterAreaNodes; if (bEmpty) { //все оставшиеся считаем как bad //todo сделать как в Excel, которой определяет циклические ссылки на момент подсчета(пример A1=VLOOKUP(1,B1:D2,2),B2 = 1, D1=A1 - это не циклическая ссылка) for (i in oNodeDependence.oMasterAreaNodesRestricted) { this._sortDependency(oNodeDependence.oMasterAreaNodesRestricted[i].node, oNodeDependence, null, true, oCleanCellCacheArea, setCellFormat); } break; } } for (i in oCleanCellCacheArea) this.handlers.trigger("cleanCellCache", i, oCleanCellCacheArea[i], AscCommonExcel.c_oAscCanChangeColWidth.numbers); AscCommonExcel.g_oVLOOKUPCache.clean(); AscCommonExcel.g_oHLOOKUPCache.clean(); } this.needRecalc = {nodes: {}, length: 0}; }; Workbook.prototype._sortDependency = function(node, oNodeDependence, oNewMasterAreaNodes, bBad, oCleanCellCacheArea, setCellFormat) { if (node) { var oWeightMapElem = oNodeDependence.oWeightMap[node.nodeId]; if (oWeightMapElem) { oWeightMapElem.cur++; if (oWeightMapElem.cur == oWeightMapElem.max && !oWeightMapElem.gray) { if (null != oNewMasterAreaNodes) { var oNodeToAreaElement = oNodeDependence.oNodeToArea[node.nodeId]; if (oNodeToAreaElement) { for (var i = 0, length = oNodeToAreaElement.length; i < length; ++i) { var elem = oNodeToAreaElement[i]; elem.cur++; if (elem.cur == elem.max) { oNewMasterAreaNodes[elem.node.nodeId] = elem.node; delete oNodeDependence.oMasterAreaNodesRestricted[elem.node.nodeId]; } } } } var bCurBad = oWeightMapElem.bad || bBad; if (node.isDefinedName) { //todo //Обрабатываем тут все, что было сделано с именованной ссылкой: переименована; //перемещен диапазон; сдвиг/удаление ячеек, приведшие к сдвигу ячеек; удаление именованного диапазона. // // var ws = this.getWorksheetById( node.sheetId ); // ws._ReBuildFormulas // ws._RecalculatedFunctions(node.cellId, bCurBad, setCellFormat); } else { //пересчитываем функцию var ws = this.getWorksheetById(node.sheetId); ws._RecalculatedFunctions(node.cellId, bCurBad, setCellFormat); //запоминаем области для удаления cache var sheetArea = oCleanCellCacheArea[node.sheetId]; if (null == sheetArea) { sheetArea = {}; oCleanCellCacheArea[node.sheetId] = sheetArea; } if (!node.isArea) { sheetArea[node.cellId] = node.getBBox(); } } //обрабатываем child oWeightMapElem.gray = true; var oSlaveNodes = node.getSlaveEdges(); if (oSlaveNodes) { for (var i in oSlaveNodes) this._sortDependency(oSlaveNodes[i], oNodeDependence, oNewMasterAreaNodes, bBad, oCleanCellCacheArea); } oWeightMapElem.gray = false; } } } }; //------------------------------------------------------------------------------------------------- /** * @constructor */ function Woorksheet(wb, _index, sId){ this.workbook = wb; this.DefinedNames = {}; this.sName = this.workbook.getUniqueSheetNameFrom(g_sNewSheetNamePattern, false); this.bHidden = false; this.oSheetFormatPr = new AscCommonExcel.SheetFormatPr(); this.index = _index; this.Id = null != sId ? sId : AscCommon.g_oIdCounter.Get_NewId(); this.nRowsCount = 0; this.nColsCount = 0; this.aGCells = {};// 0 based this.aCols = [];// 0 based this.Drawings = []; this.TableParts = []; this.AutoFilter = null; this.oAllCol = null; this.aComments = []; this.aCommentsCoords = []; var oThis = this; this.mergeManager = new RangeDataManager(function(data, from, to) { if (History.Is_On() && (null != from || null != to)) { if (null != from) { from = from.clone(); } if (null != to) to = to.clone(); var oHistoryRange = from; if (null == oHistoryRange) oHistoryRange = to; History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ChangeMerge, oThis.getId(), oHistoryRange, new UndoRedoData_FromTo(new UndoRedoData_BBox(from), new UndoRedoData_BBox(to))); } //расширяем границы if (null != to) { if (to.r2 >= oThis.nRowsCount) oThis.nRowsCount = to.r2 + 1; if (to.c2 >= oThis.nColsCount) oThis.nColsCount = to.c2 + 1; } }); this.hyperlinkManager = new RangeDataManager(function(data, from, to, oChangeParam) { if (History.Is_On() && (null != from || null != to)) { if (null != from) from = from.clone(); if (null != to) to = to.clone(); var oHistoryRange = from; if (null == oHistoryRange) oHistoryRange = to; var oHistoryData = null; if (null == from || null == to) oHistoryData = data.clone(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ChangeHyperlink, oThis.getId(), oHistoryRange, new AscCommonExcel.UndoRedoData_FromToHyperlink(from, to, oHistoryData)); } if (null != to) data.Ref = oThis.getRange3(to.r1, to.c1, to.r2, to.c2); else if (oChangeParam && oChangeParam.removeStyle && null != data.Ref) data.Ref.cleanFormat(); //расширяем границы if (null != to) { if (to.r2 >= oThis.nRowsCount) oThis.nRowsCount = to.r2 + 1; if (to.c2 >= oThis.nColsCount) oThis.nColsCount = to.c2 + 1; } }); this.hyperlinkManager.setDependenceManager(this.mergeManager); this.DrawingDocument = new AscCommon.CDrawingDocument(); this.sheetViews = []; this.aConditionalFormatting = []; this.sheetPr = null; this.aFormulaExt = null; this.autoFilters = AscCommonExcel.AutoFilters !== undefined ? new AscCommonExcel.AutoFilters(this) : null; this.sparklineGroups = new sparklineGroups(); this.oDrawingOjectsManager = new DrawingObjectsManager(this); this.contentChanges = new AscCommon.CContentChanges(); this.sparklineGroups = new AscCommonExcel.sparklineGroups(); /*handlers*/ this.handlers = null; } Woorksheet.prototype.addContentChanges = function(changes) { this.contentChanges.Add(changes); }; Woorksheet.prototype.refreshContentChanges = function() { this.contentChanges.Refresh(); this.contentChanges.Clear(); }; Woorksheet.prototype.rebuildColors=function(){ this._forEachCell(function(cell){ cell.cleanCache(); }); this.rebuildTabColor(); }; Woorksheet.prototype.generateFontMap=function(oFontMap){ //пробегаемся по Drawing for(var i = 0, length = this.Drawings.length; i < length; ++i) { var drawing = this.Drawings[i]; if(drawing) drawing.getAllFonts(oFontMap); } if(null != this.workbook.theme) AscFormat.checkThemeFonts(oFontMap, this.workbook.theme.themeElements.fontScheme); //пробегаемся по колонкам for(var i in this.aCols) { var col = this.aCols[i]; if(null != col && null != col.xfs && null != col.xfs.font && null != col.xfs.font.fn) oFontMap[col.xfs.font.fn] = 1; } if(null != this.oAllCol && null != this.oAllCol.xfs && null != this.oAllCol.xfs.font && null != this.oAllCol.xfs.font.fn) oFontMap[this.oAllCol.xfs.font.fn] = 1; //пробегаемся строкам for(var i in this.aGCells) { var row = this.aGCells[i]; if(null != row && null != row.xfs && null != row.xfs.font && null != row.xfs.font.fn) oFontMap[row.xfs.font.fn] = 1; //пробегаемся по ячейкам for(var j in row.c) { var cell = row.c[j]; if(null != cell) { if(null != cell.xfs && null != cell.xfs.font && null != cell.xfs.font.fn) oFontMap[cell.xfs.font.fn] = 1; //смотрим в комплексных строках if(null != cell.oValue && null != cell.oValue.multiText) { for(var k = 0, length3 = cell.oValue.multiText.length; k < length3; ++k) { var part = cell.oValue.multiText[k]; if(null != part.format && null != part.format.fn) oFontMap[part.format.fn] = 1; } } } } } }; Woorksheet.prototype.clone=function(sNewId, sName){ var i, elem, range; var oNewWs = new Woorksheet(this.workbook, this.workbook.aWorksheets.length, sNewId); oNewWs.sName = this.workbook.checkValidSheetName(sName) ? sName : this.workbook.getUniqueSheetNameFrom(this.sName, true); oNewWs.bHidden = this.bHidden; oNewWs.oSheetFormatPr = this.oSheetFormatPr.clone(); oNewWs.index = this.index; oNewWs.nRowsCount = this.nRowsCount; oNewWs.nColsCount = this.nColsCount; for (i = 0; i < this.TableParts.length; ++i) oNewWs.TableParts.push(this.TableParts[i].clone(oNewWs)); if(this.AutoFilter) oNewWs.AutoFilter = this.AutoFilter.clone(); for (i in this.aCols) { var col = this.aCols[i]; if(null != col) oNewWs.aCols[i] = col.clone(oNewWs); } if(null != this.oAllCol) oNewWs.oAllCol = this.oAllCol.clone(oNewWs); for(i in this.aGCells) oNewWs.aGCells[i] = this.aGCells[i].clone(oNewWs); var aMerged = this.mergeManager.getAll(); for(i in aMerged) { elem = aMerged[i]; range = oNewWs.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2); range.mergeOpen(); } var aHyperlinks = this.hyperlinkManager.getAll(); for(i in aHyperlinks) { elem = aHyperlinks[i]; range = oNewWs.getRange3(elem.bbox.r1, elem.bbox.c1, elem.bbox.r2, elem.bbox.c2); range.setHyperlinkOpen(elem.data); } if(null != this.aComments) { for (i = 0; i < this.aComments.length; i++) { var comment = new Asc.asc_CCommentData(this.aComments[i]); comment.wsId = oNewWs.getId(); comment.nId = "sheet" + comment.wsId + "_" + (i + 1); oNewWs.aComments.push(comment); } } for (i = 0; i < this.sheetViews.length; ++i) { oNewWs.sheetViews.push(this.sheetViews[i].clone()); } for (i = 0; i < this.aConditionalFormatting.length; ++i) { oNewWs.aConditionalFormatting.push(this.aConditionalFormatting[i].clone()); } if (this.sheetPr) oNewWs.sheetPr = this.sheetPr.clone(); return oNewWs; }; Woorksheet.prototype.copyDrawingObjects=function(oNewWs, wsFrom) { if(null != this.Drawings && this.Drawings.length > 0) { var drawingObjects = new AscFormat.DrawingObjects(); oNewWs.Drawings = []; AscFormat.NEW_WORKSHEET_DRAWING_DOCUMENT = oNewWs.DrawingDocument; for(var i = 0; i < this.Drawings.length; ++i) { var drawingObject = drawingObjects.cloneDrawingObject(this.Drawings[i]); drawingObject.graphicObject = this.Drawings[i].graphicObject.copy(); drawingObject.graphicObject.setWorksheet(oNewWs); drawingObject.graphicObject.addToDrawingObjects(); var drawingBase = this.Drawings[i]; drawingObject.graphicObject.setDrawingBaseCoords(drawingBase.from.col, drawingBase.from.colOff, drawingBase.from.row, drawingBase.from.rowOff, drawingBase.to.col, drawingBase.to.colOff, drawingBase.to.row, drawingBase.to.rowOff, drawingBase.Pos.X, drawingBase.Pos.Y, drawingBase.ext.cx, drawingBase.ext.cy); oNewWs.Drawings[oNewWs.Drawings.length - 1] = drawingObject; } AscFormat.NEW_WORKSHEET_DRAWING_DOCUMENT = null; drawingObjects.pushToAObjects(oNewWs.Drawings); drawingObjects.updateChartReferences2(parserHelp.getEscapeSheetName(wsFrom.sName), parserHelp.getEscapeSheetName(oNewWs.sName)); } }; Woorksheet.prototype.initPostOpen = function(handlers){ this.workbook.cwf[this.Id]={ cells:{} }; if(this.aFormulaExt){ var formulaShared = {}; for(var i = 0; i < this.aFormulaExt.length; ++i){ var elem = this.aFormulaExt[i]; var oCell = elem.cell; var sCellId = g_oCellAddressUtils.getCellId(oCell.nRow, oCell.nCol); var oFormulaExt = elem.ext; if (oFormulaExt.t == Asc.ECellFormulaType.cellformulatypeShared) { if(null != oFormulaExt.si){ if(null != oFormulaExt.ref){ if (oFormulaExt.v.length <= AscCommon.c_oAscMaxFormulaLength) { formulaShared[oFormulaExt.si] = { fVal: new parserFormula(oFormulaExt.v, "", this), fRef: function(t) { var r = t.getRange2(oFormulaExt.ref); return { c: r, first: r.first }; }(this) }; formulaShared[oFormulaExt.si].fVal.parse(); } } else{ if( formulaShared[oFormulaExt.si] ){ var fr = formulaShared[oFormulaExt.si].fRef; if( fr.c.containCell2(oCell) ){ if( formulaShared[oFormulaExt.si].fVal.isParsed ){ var off = oCell.getOffset3(fr.first); formulaShared[oFormulaExt.si].fVal.changeOffset(off); oFormulaExt.v = formulaShared[oFormulaExt.si].fVal.assemble(); off.offsetCol *=-1; off.offsetRow *=-1; formulaShared[oFormulaExt.si].fVal.changeOffset(off); } this.workbook.cwf[this.Id].cells[sCellId] = sCellId; } } } } } if(oFormulaExt.v) { if (oFormulaExt.v.length <= AscCommon.c_oAscMaxFormulaLength) { oCell.setFormula(oFormulaExt.v); if(oFormulaExt.ca) { oCell.sFormulaCA = true; } } else { this.workbook.openErrors.push(oCell.getName()); } } /* Если ячейка содержит в себе формулу, то добавляем ее в список ячеек с формулами. */ if(oCell.sFormula){ this.workbook.cwf[this.Id].cells[sCellId] = sCellId; } /* Строится список ячеек, которые необходимо пересчитать при открытии. Это ячейки имеющие атрибут f.ca или значение в которых неопределено. */ if(oCell.sFormula && (oFormulaExt.ca || !oCell.oValue.getValueWithoutFormat()) ){ this.workbook.needRecalc.nodes[ getVertexId( this.Id, sCellId ) ] = [this.Id, sCellId]; this.workbook.needRecalc.length++; } } this.aFormulaExt = null; } if (!this.PagePrintOptions) { // Даже если не было, создадим this.PagePrintOptions = new Asc.asc_CPageOptions(); } this.PagePrintOptions.init(); // Sheet Views if (0 === this.sheetViews.length) { // Даже если не было, создадим this.sheetViews.push(new AscCommonExcel.asc_CSheetViewSettings()); } if (window['IS_NATIVE_EDITOR']) { for (var j = this.sheetViews.length - 1; j >= 0; --j) { this.sheetViews[j].pane = null; } } this._updateConditionalFormatting(null); this.handlers = handlers; this._setHandlersTablePart(); }; Woorksheet.prototype._getValuesForConditionalFormatting = function(sqref) { var aValues = [], aCells = []; var tmp; this.getRange3(sqref.r1, sqref.c1, sqref.r2, sqref.c2)._setPropertyNoEmpty(null, null, function(c) { if (!c.isEmptyTextString()) { aCells.push(c); aValues.push(c.getValueWithoutFormat()); } }); return {c: aCells, v: aValues}; }; Woorksheet.prototype._updateConditionalFormatting = function(range) { var oGradient = null; var aCFs = this.aConditionalFormatting; var aRules, oRule; var oRuleElement = null; var o; var i, j, cell, sqref, values, tmp, min, max, dxf; for (i = 0; i < aCFs.length; ++i) { sqref = aCFs[i].sqref; // ToDo убрать null === sqref когда научимся мультиселект обрабатывать (\\192.168.5.2\source\DOCUMENTS\XLSX\Matematika Quantum Sedekah.xlsx) if (null === sqref) { continue; } if (!range || range.isIntersect(sqref)) { aRules = aCFs[i].aRules; for (j = 0; j < aRules.length; ++j) { oRule = aRules[j]; // ToDo aboveAverage, beginsWith, cellIs, containsBlanks, containsErrors, // ToDo containsText, dataBar, duplicateValues, endsWith, expression, iconSet, notContainsBlanks, // ToDo notContainsErrors, notContainsText, timePeriod, top10, uniqueValues (page 2679) switch (oRule.type) { case Asc.ECfType.colorScale: if (1 !== oRule.aRuleElements.length) { break; } oRuleElement = oRule.aRuleElements[0]; if (!(oRuleElement instanceof AscCommonExcel.CColorScale)) { break; } min = Number.MAX_VALUE; max = -Number.MAX_VALUE; values = this._getValuesForConditionalFormatting(sqref); for (cell = 0; cell < values.v.length; ++cell) { if (CellValueType.Number === values.c[cell].getType() && !isNaN(tmp = parseFloat(values.v[cell]))) { values.v[cell] = tmp; min = Math.min(min, tmp); max = Math.max(max, tmp); } else { values.v[cell] = null; } } // ToDo CFVO Type (formula, max, min, num, percent, percentile) (page 2681) // ToDo support 3 colors in rule if (0 < values.c.length && 2 === oRuleElement.aColors.length) { oGradient = new AscCommonExcel.CGradient(oRuleElement.aColors[0], oRuleElement.aColors[1]); oGradient.init(min, max); for (cell = 0; cell < values.c.length; ++cell) { dxf = null; if (null !== values.v[cell]) { dxf = new AscCommonExcel.CellXfs(); dxf.fill = new AscCommonExcel.Fill({bg: oGradient.calculateColor(values.v[cell])}); } values.c[cell].setConditionalFormattingStyle(dxf); } } break; case Asc.ECfType.uniqueValues: o = getUniqueKeys(values.v); break; } } } } }; Woorksheet.prototype._forEachCell=function(fAction){ for(var rowInd in this.aGCells){ var row = this.aGCells[rowInd]; if(row){ for(var cellInd in row.c){ var cell = row.c[cellInd]; if(cell){ fAction(cell); } } } } }; Woorksheet.prototype.getId=function(){ return this.Id; }; Woorksheet.prototype.getIndex=function(){ return this.index; }; Woorksheet.prototype.getName=function(){ return this.sName !== undefined && this.sName.length > 0 ? this.sName : ""; }; Woorksheet.prototype.setName=function(name, bFromUndoRedo){ if(name.length <= g_nSheetNameMaxLength) { var lastName = this.sName; this.sName = name; History.Create_NewPoint(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Rename, this.getId(), null, new UndoRedoData_FromTo(lastName, name)); //перестраиваем формулы, если у них были ссылки на лист со старым именем. for(var id in this.workbook.cwf) { this.workbook.getWorksheetById(id)._ReBuildFormulas(this.workbook.cwf[id].cells,lastName,this.sName); } this.workbook.dependencyFormulas.relinkDefNameByWorksheet(lastName, name); if(!bFromUndoRedo) { var _lastName = parserHelp.getEscapeSheetName(lastName); var _newName = parserHelp.getEscapeSheetName(this.sName); for (var key in this.workbook.aWorksheets) { var wsModel = this.workbook.aWorksheets[key]; if ( wsModel ) wsModel.oDrawingOjectsManager.updateChartReferencesWidthHistory(_lastName, _newName, true); } } } }; Woorksheet.prototype.getTabColor=function(){ return this.sheetPr && this.sheetPr.TabColor ? Asc.colorObjToAscColor(this.sheetPr.TabColor) : null; }; Woorksheet.prototype.setTabColor=function(color){ if (!this.sheetPr) this.sheetPr = new AscCommonExcel.asc_CSheetPr(); History.Create_NewPoint(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_SetTabColor, this.getId(), null, new UndoRedoData_FromTo(this.sheetPr.TabColor ? this.sheetPr.TabColor.clone() : null, color ? color.clone() : null)); this.sheetPr.TabColor = color; if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges) this.workbook.handlers.trigger("asc_onUpdateTabColor", this.getIndex()); }; Woorksheet.prototype.rebuildTabColor = function() { if (this.sheetPr && this.sheetPr.TabColor) { this.workbook.handlers.trigger("asc_onUpdateTabColor", this.getIndex()); } }; Woorksheet.prototype.renameWsToCollaborate=function(name){ var lastname = this.getName(); //из-за особенностей реализации формул, сначала делаем parse со старым именем, потом преименовываем, потом assemble var aFormulas = []; //переименование для отправки изменений for(var i = 0, length = this.workbook.aCollaborativeActions.length; i < length; ++i) { var aPointActions = this.workbook.aCollaborativeActions[i]; for (var j = 0, length2 = aPointActions.length; j < length2; ++j) { var action = aPointActions[j]; if (AscCommonExcel.g_oUndoRedoWorkbook == action.oClass) { if (AscCH.historyitem_Workbook_SheetAdd == action.nActionType) { if (lastname == action.oData.name) action.oData.name = name; } } else if (AscCommonExcel.g_oUndoRedoWorksheet == action.oClass) { if (AscCH.historyitem_Worksheet_Rename == action.nActionType) { if (lastname == action.oData.to) action.oData.to = name; } } else if (AscCommonExcel.g_oUndoRedoCell == action.oClass) { if (action.oData instanceof UndoRedoData_CellSimpleData) { if (action.oData.oNewVal instanceof UndoRedoData_CellValueData) { var oNewVal = action.oData.oNewVal; if (null != oNewVal.formula && -1 != oNewVal.formula.indexOf(lastname)) { var oParser = new parserFormula(oNewVal.formula, "A1", this); oParser.parse(); aFormulas.push({ formula: oParser, value: oNewVal }); } } } } } } //переименование для локальной версии this.setName(name); for(var i = 0, length = aFormulas.length; i < length; ++i) { var item = aFormulas[i]; item.value.formula = item.formula.assemble(); } }; Woorksheet.prototype.getHidden=function(){ if(null != this.bHidden) return false != this.bHidden; return false; }; Woorksheet.prototype.setHidden = function (hidden) { var bOldHidden = this.bHidden, wb = this.workbook, wsActive = wb.getActiveWs(), oVisibleWs = null; this.bHidden = hidden; if (true == this.bHidden && this.getIndex() == wsActive.getIndex()) { oVisibleWs = wb.findSheetNoHidden(this.getIndex()); if (null != oVisibleWs) { var nNewIndex = oVisibleWs.getIndex(); wb.setActive(nNewIndex); if (!wb.bUndoChanges && !wb.bRedoChanges) wb.handlers.trigger("undoRedoHideSheet", nNewIndex); } } if (bOldHidden != hidden) { History.Create_NewPoint(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Hide, this.getId(), null, new UndoRedoData_FromTo(bOldHidden, hidden)); if (null != oVisibleWs) { History.SetSheetUndo(wsActive.getId()); History.SetSheetRedo(oVisibleWs.getId()); } } }; Woorksheet.prototype.getSheetViewSettings = function () { return this.sheetViews[0].clone(); }; Woorksheet.prototype.setSheetViewSettings = function (options) { var current = this.getSheetViewSettings(); if (current.isEqual(options)) return; History.Create_NewPoint(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_SetViewSettings, this.getId(), null, new UndoRedoData_FromTo(current, options.clone())); this.sheetViews[0].setSettings(options); if (!this.workbook.bUndoChanges && !this.workbook.bRedoChanges) this.workbook.handlers.trigger("asc_onUpdateSheetViewSettings"); }; Woorksheet.prototype.getRowsCount=function(){ var result = this.nRowsCount; var pane = this.sheetViews[0].pane; if (null !== pane && null !== pane.topLeftFrozenCell) result = Math.max(result, pane.topLeftFrozenCell.getRow0()); return result; }; Woorksheet.prototype.removeRows=function(start, stop){ var oRange = this.getRange(new CellAddress(start, 0, 0), new CellAddress(stop, gc_nMaxCol0, 0)); oRange.deleteCellsShiftUp(); }; Woorksheet.prototype._removeRows=function(start, stop){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.lockDraw(); History.Create_NewPoint(); //start, stop 0 based var nDif = -(stop - start + 1); var oActualRange = {r1: start, c1: 0, r2: stop, c2: gc_nMaxCol0}; this.renameDependencyNodes({offsetRow:nDif,offsetCol:0}, oActualRange); var i, j, length, nIndex, aIndexes = []; for(i in this.aGCells) { nIndex = i - 0; if(nIndex >= start) aIndexes.push(nIndex); } //По возрастанию aIndexes.sort(fSortAscending); var oDefRowPr = new AscCommonExcel.UndoRedoData_RowProp(); for(i = 0, length = aIndexes.length; i < length; ++i) { nIndex = aIndexes[i]; var row = this.aGCells[nIndex]; if(nIndex > stop) { if(false == row.isEmpty()) { var oTargetRow = this._getRow(nIndex + nDif); oTargetRow.copyProperty(row); } for(j in row.c) this._moveCellVer(nIndex, j - 0, nDif); } else { var oOldProps = row.getHeightProp(); if (false === oOldProps.isEqual(oDefRowPr)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, this.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(nIndex, true, oOldProps, oDefRowPr)); row.setStyle(null); for(j in row.c) { var nColIndex = j - 0; //удаляем ячейку this._removeCell(nIndex, nColIndex); } } delete this.aGCells[nIndex]; } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveRows, this.getId(), new Asc.Range(0, start, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, start, stop)); this.autoFilters.insertRows( "delCell", new Asc.Range(0, start, gc_nMaxCol0, stop), c_oAscDeleteOptions.DeleteRows ); this.workbook.unLockDraw(); this.workbook.buildRecalc(); return true; }; Woorksheet.prototype.insertRowsBefore=function(index, count){ var oRange = this.getRange(new CellAddress(index, 0, 0), new CellAddress(index + count - 1, gc_nMaxCol0, 0)); oRange.addCellsShiftBottom(); }; Woorksheet.prototype._insertRowsBefore=function(index, count){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.lockDraw(); var oActualRange = {r1: index, c1: 0, r2: index + count - 1, c2: gc_nMaxCol0}; History.Create_NewPoint(); this.renameDependencyNodes({offsetRow:count,offsetCol:0},oActualRange); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_AddRows, this.getId(), new Asc.Range(0, index, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(true, index, index + count - 1)); //index 0 based var aIndexes = []; for(var i in this.aGCells) { var nIndex = i - 0; if(nIndex >= index) aIndexes.push(nIndex); } var oPrevRow = null; if(index > 0) oPrevRow = this.aGCells[index - 1]; //По убыванию aIndexes.sort(fSortDescending); for(var i = 0, length = aIndexes.length; i < length; ++i) { var nIndex = aIndexes[i]; var row = this.aGCells[nIndex]; if(false == row.isEmpty()) { var oTargetRow = this._getRow(nIndex + count); oTargetRow.copyProperty(row); } for(var j in row.c) this._moveCellVer(nIndex, j - 0, count); delete this.aGCells[nIndex]; } if (null != oPrevRow && false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges)) { History.LocalChange = true; for(var i = 0; i < count; ++i) { var row = this._getRow(index + i); row.copyProperty(oPrevRow); row.flags &= ~AscCommonExcel.g_nRowFlag_hd; } History.LocalChange = false; } this.autoFilters.insertRows( "insCell", new Asc.Range(0, index, gc_nMaxCol0, index + count - 1), c_oAscInsertOptions.InsertColumns ); this.workbook.unLockDraw(); this.workbook.buildRecalc(); this.nRowsCount += count; return true; }; Woorksheet.prototype.insertRowsAfter=function(index, count){ //index 0 based return this.insertRowsBefore(index + 1, count); }; Woorksheet.prototype.getColsCount=function(){ var result = this.nColsCount; var pane = this.sheetViews[0].pane; if (null !== pane && null !== pane.topLeftFrozenCell) result = Math.max(result, pane.topLeftFrozenCell.getCol0()); return result; }; Woorksheet.prototype.removeCols=function(start, stop){ var oRange = this.getRange(new CellAddress(0, start, 0), new CellAddress(gc_nMaxRow0, stop, 0)); oRange.deleteCellsShiftLeft(); }; Woorksheet.prototype._removeCols=function(start, stop){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.lockDraw(); History.Create_NewPoint(); //start, stop 0 based var nDif = -(stop - start + 1), i, j, length, nIndex; var oActualRange = { r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop }; this.renameDependencyNodes({ offsetRow: 0, offsetCol: nDif }, oActualRange); for(i in this.aGCells) { var nRowIndex = i - 0; var row = this.aGCells[i]; var aIndexes = []; for(j in row.c) { nIndex = j - 0; if(nIndex >= start) aIndexes.push(nIndex); } //сортируем по возрастанию aIndexes.sort(fSortAscending); for(j = 0, length = aIndexes.length; j < length; ++j) { nIndex = aIndexes[j]; if(nIndex > stop) { this._moveCellHor(nRowIndex, nIndex, nDif, {r1: 0, c1: start, r2: gc_nMaxRow0, c2: stop}); } else { //удаляем ячейку this._removeCell(nRowIndex, nIndex); } } } var oDefColPr = new AscCommonExcel.UndoRedoData_ColProp(); for(i = start; i <= stop; ++i) { var col = this.aCols[i]; if(null != col) { var oOldProps = col.getWidthProp(); if(false === oOldProps.isEqual(oDefColPr)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, this.getId(), new Asc.Range(i, 0, i, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(i, false, oOldProps, oDefColPr)); col.setStyle(null); } } this.aCols.splice(start, stop - start + 1); for(i = start, length = this.aCols.length; i < length; ++i) { var elem = this.aCols[i]; if(null != elem) elem.moveHor(nDif); } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveCols, this.getId(), new Asc.Range(start, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, start, stop)); this.autoFilters.insertColumn( "delCell", new Asc.Range(start, 0, stop, gc_nMaxRow0), c_oAscInsertOptions.InsertColumns ); this.workbook.unLockDraw(); this.workbook.buildRecalc(); return true; }; Woorksheet.prototype.insertColsBefore=function(index, count){ var oRange = this.getRange3(0, index, gc_nMaxRow0, index + count - 1); oRange.addCellsShiftRight(); }; Woorksheet.prototype._insertColsBefore=function(index, count){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.lockDraw(); var oActualRange = {r1: 0, c1: index, r2: gc_nMaxRow0, c2: index + count - 1}; History.Create_NewPoint(); this.renameDependencyNodes({offsetRow:0,offsetCol:count},oActualRange); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_AddCols, this.getId(), new Asc.Range(index, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromToRowCol(false, index, index + count - 1)); //index 0 based for(var i in this.aGCells) { var nRowIndex = i - 0; var row = this.aGCells[i]; var aIndexes = []; for(var j in row.c) { var nIndex = j - 0; if(nIndex >= index) aIndexes.push(nIndex); } //сортируем по убыванию aIndexes.sort(fSortDescending); for(var j = 0, length2 = aIndexes.length; j < length2; ++j) { var nIndex = aIndexes[j]; this._moveCellHor(nRowIndex, nIndex, count, oActualRange); } } this.autoFilters.insertColumn( "insCells", new Asc.Range(index, 0, index + count - 1, gc_nMaxRow0), c_oAscInsertOptions.InsertColumns ); this.workbook.unLockDraw(); this.workbook.buildRecalc(); var oPrevCol = null; if(index > 0) oPrevCol = this.aCols[index - 1]; if(null == oPrevCol && null != this.oAllCol) oPrevCol = this.oAllCol; for(var i = 0; i < count; ++i) { var oNewCol = null; if (null != oPrevCol && false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges)) { History.LocalChange = true; oNewCol = oPrevCol.clone(); oNewCol.hd = null; oNewCol.BestFit = null; oNewCol.index = index + i; History.LocalChange = false; } this.aCols.splice(index, 0, oNewCol); } for(var i = index + count, length = this.aCols.length; i < length; ++i) { var elem = this.aCols[i]; if(null != elem) elem.moveHor(count); } this.nColsCount += count; return true; }; Woorksheet.prototype.insertColsAfter=function(index, count){ //index 0 based return this.insertColsBefore(index + 1, count); }; Woorksheet.prototype.getDefaultWidth=function(){ return this.oSheetFormatPr.dDefaultColWidth; }; Woorksheet.prototype.getDefaultFontName=function(){ return this.workbook.getDefaultFont(); }; Woorksheet.prototype.getDefaultFontSize=function(){ return this.workbook.getDefaultSize(); }; Woorksheet.prototype.getColWidth=function(index){ //index 0 based //Результат в пунктах var col = this._getColNoEmptyWithAll(index); if(null != col && null != col.width) return col.width; var dResult = this.oSheetFormatPr.dDefaultColWidth; if(dResult === undefined || dResult === null || dResult == 0) //dResult = (8) + 5;//(EMCA-376.page 1857.)defaultColWidth = baseColumnWidth + {margin padding (2 pixels on each side, totalling 4 pixels)} + {gridline (1pixel)} dResult = -1; // calc default width at presentation level return dResult; }; Woorksheet.prototype.setColWidth=function(width, start, stop){ if(0 == width) return this.setColHidden(true, start, stop); //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(start, 0, stop, gc_nMaxRow0); oSelection.type = Asc.c_oAscSelectionType.RangeCol; History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } var oThis = this; var fProcessCol = function(col){ if(col.width != width) { var oOldProps = col.getWidthProp(); col.width = width; col.CustomWidth = true; col.BestFit = null; col.hd = null; var oNewProps = col.getWidthProp(); if(false == oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(), col._getUpdateRange(), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps)); } }; if(0 == start && gc_nMaxCol0 == stop) { var col = this.getAllCol(); fProcessCol(col); for(var i in this.aCols){ var col = this.aCols[i]; if (null != col) fProcessCol(col); } } else { for(var i = start; i <= stop; i++){ var col = this._getCol(i); fProcessCol(col); } } }; Woorksheet.prototype.getColHidden=function(index){ var col = this._getColNoEmptyWithAll(index); return col ? col.hd : false; }; Woorksheet.prototype.setColHidden=function(bHidden, start, stop){ //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this; var fProcessCol = function(col){ if(col.hd != bHidden) { var oOldProps = col.getWidthProp(); if(bHidden) { col.hd = bHidden; if(null == col.width || true != col.CustomWidth) col.width = 0; col.CustomWidth = true; col.BestFit = null; } else { col.hd = null; if(0 == col.width) col.width = null; } var oNewProps = col.getWidthProp(); if(false == oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(), col._getUpdateRange(), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps)); } }; if(0 != start && gc_nMaxCol0 == stop) { var col = null; if(false == bHidden) col = this.oAllCol; else col = this.getAllCol(); if(null != col) fProcessCol(col); for(var i in this.aCols){ var col = this.aCols[i]; if (null != col) fProcessCol(col); } } else { for(var i = start; i <= stop; i++){ var col = null; if(false == bHidden) col = this._getColNoEmpty(i); else col = this._getCol(i); if(null != col) fProcessCol(col); } } }; Woorksheet.prototype.setColBestFit=function(bBestFit, width, start, stop){ //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this; var fProcessCol = function(col){ var oOldProps = col.getWidthProp(); if(bBestFit) { col.BestFit = bBestFit; col.hd = null; } else col.BestFit = null; col.width = width; var oNewProps = col.getWidthProp(); if(false == oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, oThis.getId(), col._getUpdateRange(), new UndoRedoData_IndexSimpleProp(col.index, false, oOldProps, oNewProps)); }; if(0 != start && gc_nMaxCol0 == stop) { var col = null; if(bBestFit && oDefaultMetrics.ColWidthChars == width) col = this.oAllCol; else col = this.getAllCol(); if(null != col) fProcessCol(col); for(var i in this.aCols){ var col = this.aCols[i]; if (null != col) fProcessCol(col); } } else { for(var i = start; i <= stop; i++){ var col = null; if(bBestFit && oDefaultMetrics.ColWidthChars == width) col = this._getColNoEmpty(i); else col = this._getCol(i); if(null != col) fProcessCol(col); } } }; Woorksheet.prototype.isDefaultHeightHidden=function(){ return null != this.oSheetFormatPr.oAllRow && 0 != (AscCommonExcel.g_nRowFlag_hd & this.oSheetFormatPr.oAllRow.flags); }; Woorksheet.prototype.isDefaultWidthHidden=function(){ return null != this.oAllCol && this.oAllCol.hd; }; Woorksheet.prototype.getDefaultHeight=function(){ // ToDo http://bugzserver/show_bug.cgi?id=19666 (флага CustomHeight нет) var dRes = null; // Нужно возвращать выставленную, только если флаг CustomHeight = true if(null != this.oSheetFormatPr.oAllRow && 0 != (AscCommonExcel.g_nRowFlag_CustomHeight & this.oSheetFormatPr.oAllRow.flags)) dRes = this.oSheetFormatPr.oAllRow.h; return dRes; }; Woorksheet.prototype.getRowHeight=function(index){ //index 0 based var row = this.aGCells[index]; if(null != row && null != row.h) return row.h; else return -1; }; Woorksheet.prototype.setRowHeight=function(height, start, stop, isCustom){ if(0 == height) return this.setRowHidden(true, start, stop); //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this, i; var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(0, start, gc_nMaxCol0, stop); oSelection.type = Asc.c_oAscSelectionType.RangeRow; History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } var fProcessRow = function(row){ if(row) { var oOldProps = row.getHeightProp(); row.h = height; if (isCustom) { row.flags |= AscCommonExcel.g_nRowFlag_CustomHeight; } row.flags &= ~AscCommonExcel.g_nRowFlag_hd; var oNewProps = row.getHeightProp(); if(false === oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, oThis.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(row.index, true, oOldProps, oNewProps)); } }; if(0 == start && gc_nMaxRow0 == stop) { fProcessRow(this.getAllRow()); for(i in this.aGCells){ fProcessRow(this.aGCells[i]); } } else { for(i = start; i <= stop; ++i){ fProcessRow(this._getRow(i)); } } }; Woorksheet.prototype.getRowHidden=function(index){ var row = this._getRowNoEmptyWithAll(index); return row ? 0 != (AscCommonExcel.g_nRowFlag_hd & row.flags) : false; }; Woorksheet.prototype.setRowHidden=function(bHidden, start, stop){ //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this, i; var startIndex = null, endIndex = null, updateRange; var fProcessRow = function(row){ if(row && bHidden != (0 != (AscCommonExcel.g_nRowFlag_hd & row.flags))) { if(bHidden) row.flags |= AscCommonExcel.g_nRowFlag_hd; else row.flags &= ~AscCommonExcel.g_nRowFlag_hd; if(row.index === endIndex + 1 && startIndex !== null) endIndex++; else { if(startIndex !== null) { updateRange = new Asc.Range(0, startIndex, gc_nMaxCol0, endIndex); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowHide, oThis.getId(), updateRange, new UndoRedoData_FromToRowCol(bHidden, startIndex, endIndex)); } startIndex = row.index; endIndex = row.index; } } }; if(0 == start && gc_nMaxRow0 == stop) { // ToDo реализовать скрытие всех строк! } else { for(i = start; i <= stop; ++i) fProcessRow(false == bHidden ? this._getRowNoEmpty(i) : this._getRow(i)); if(startIndex !== null)//заносим последние строки { updateRange = new Asc.Range(0, startIndex, gc_nMaxCol0, endIndex); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowHide, oThis.getId(),updateRange, new UndoRedoData_FromToRowCol(bHidden, startIndex, endIndex)); } } }; Woorksheet.prototype.setRowBestFit=function(bBestFit, height, start, stop){ //start, stop 0 based if(null == start) return; if(null == stop) stop = start; History.Create_NewPoint(); var oThis = this, i; var isDefaultProp = (true == bBestFit && oDefaultMetrics.RowHeight == height); var fProcessRow = function(row){ if(row) { var oOldProps = row.getHeightProp(); if(true == bBestFit) row.flags &= ~AscCommonExcel.g_nRowFlag_CustomHeight; else row.flags |= AscCommonExcel.g_nRowFlag_CustomHeight; row.h = height; var oNewProps = row.getHeightProp(); if(false == oOldProps.isEqual(oNewProps)) History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, oThis.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(row.index, true, oOldProps, oNewProps)); } }; if(0 == start && gc_nMaxRow0 == stop) { fProcessRow(isDefaultProp ? this.oSheetFormatPr.oAllRow : this.getAllRow()); for(i in this.aGCells) fProcessRow(this.aGCells[i]); } for(i = start; i <= stop; ++i) fProcessRow(isDefaultProp ? this._getRowNoEmpty(i) : this._getRow(i)); }; Woorksheet.prototype.getCell=function(oCellAdd){ return this.getRange(oCellAdd, oCellAdd); }; Woorksheet.prototype.getCell2=function(sCellAdd){ if( sCellAdd.indexOf("$") > -1) sCellAdd = sCellAdd.replace(/\$/g,""); return this.getRange2(sCellAdd); }; Woorksheet.prototype.getCell3=function(r1, c1){ return this.getRange3(r1, c1, r1, c1); }; Woorksheet.prototype.getRange=function(cellAdd1, cellAdd2){ //Если range находится за границами ячеек расширяем их var nRow1 = cellAdd1.getRow0(); var nCol1 = cellAdd1.getCol0(); var nRow2 = cellAdd2.getRow0(); var nCol2 = cellAdd2.getCol0(); return this.getRange3(nRow1, nCol1, nRow2, nCol2); }; Woorksheet.prototype.getRange2=function(sRange){ var bbox = AscCommonExcel.g_oRangeCache.getAscRange(sRange); if(null != bbox) return Range.prototype.createFromBBox(this, bbox); return null; }; Woorksheet.prototype.getRange3=function(r1, c1, r2, c2){ var nRowMin = r1; var nRowMax = r2; var nColMin = c1; var nColMax = c2; if(r1 > r2){ nRowMax = r1; nRowMin = r2; } if(c1 > c2){ nColMax = c1; nColMin = c2; } return new Range(this, nRowMin, nColMin, nRowMax, nColMax); }; Woorksheet.prototype._getRows=function(){ return this.aGCells; }; Woorksheet.prototype._getCols=function(){ return this.aCols; }; Woorksheet.prototype._removeCell=function(nRow, nCol, cell){ if(null != cell) { nRow = cell.nRow; nCol = cell.nCol; } var row = this.aGCells[nRow]; if(null != row) { var cell = row.c[nCol]; if(null != cell) { var sheetId = this.getId(); var cellId = cell.getName(); if(cell.formulaParsed) this.workbook.dependencyFormulas.deleteMasterNodes2(sheetId, cellId); this.workbook.needRecalc.nodes[getVertexId(sheetId, cellId)] = [sheetId, cellId]; this.workbook.needRecalc.length++; if (null != cell.getConditionalFormattingStyle() || null != cell.getTableStyle()) { cell.setValue(""); cell.setStyle(null); } else { if (false == cell.isEmpty()) { var oUndoRedoData_CellData = new AscCommonExcel.UndoRedoData_CellData(cell.getValueData(), null); if (null != cell.xfs) oUndoRedoData_CellData.style = cell.xfs.clone(); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveCell, sheetId, new Asc.Range(nCol, nRow, nCol, nRow), new UndoRedoData_CellSimpleData(nRow, nCol, oUndoRedoData_CellData, null)); } delete row.c[nCol]; if (row.isEmpty()) delete this.aGCells[nRow]; } } } }; Woorksheet.prototype._getCell=function(row, col){ //0-based var oCurRow = this._getRow(row); var oCurCell = oCurRow.c[col]; if(null == oCurCell){ oCurCell = new Cell(this); var oRow = this._getRowNoEmpty(row); var oCol = this._getColNoEmptyWithAll(col); var xfs = null; if(null != oRow && null != oRow.xfs) xfs = oRow.xfs.clone(); else if(null != oCol && null != oCol.xfs) xfs = oCol.xfs.clone(); oCurCell.create(xfs, row, col); oCurRow.c[col] = oCurCell; if(row >= this.nRowsCount) this.nRowsCount = row + 1; if(col >= this.nColsCount) this.nColsCount = col + 1; //History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateCell, this.getId(), null, new UndoRedoData_CellSimpleData(row, col, null, null)); } return oCurCell; }; Woorksheet.prototype._getCellNoEmpty=function(row, col){ //0-based var oCurRow = this.aGCells[row]; if(oCurRow) { var cell = oCurRow.c[col]; return cell ? cell : null; } return null; }; Woorksheet.prototype._getRowNoEmpty=function(row){ //0-based var oCurRow = this.aGCells[row]; if(oCurRow) return oCurRow; return null; }; Woorksheet.prototype._getRowNoEmptyWithAll=function(row){ var oRes = this._getRowNoEmpty(row); if(null == oRes) oRes = this.oSheetFormatPr.oAllRow; return oRes; }; Woorksheet.prototype._getColNoEmpty=function(col){ //0-based var oCurCol = this.aCols[col]; if(oCurCol) return oCurCol; return null; }; Woorksheet.prototype._getColNoEmptyWithAll=function(col){ var oRes = this._getColNoEmpty(col); if(null == oRes) oRes = this.oAllCol; return oRes; }; Woorksheet.prototype._getRow=function(row){ //0-based var oCurRow = null; if (g_nAllRowIndex == row) oCurRow = this.getAllRow(); else { oCurRow = this.aGCells[row]; if (!oCurRow) { if (null != this.oSheetFormatPr.oAllRow) oCurRow = this.oSheetFormatPr.oAllRow.clone(this); else oCurRow = new AscCommonExcel.Row(this); oCurRow.create(row + 1); this.aGCells[row] = oCurRow; this.nRowsCount = row >= this.nRowsCount ? row + 1 : this.nRowsCount; //History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateRow, this.getId(), null, new UndoRedoData_SingleProperty(row)); } } return oCurRow; }; Woorksheet.prototype._removeRow=function(index){ delete this.aGCells[index]; }; Woorksheet.prototype._getCol=function(index){ //0-based var oCurCol; if (g_nAllColIndex == index) oCurCol = this.getAllCol(); else { oCurCol = this.aCols[index]; if(null == oCurCol) { if(null != this.oAllCol) { oCurCol = this.oAllCol.clone(); oCurCol.index = index; } else oCurCol = new AscCommonExcel.Col(this, index); this.aCols[index] = oCurCol; this.nColsCount = index >= this.nColsCount ? index + 1 : this.nColsCount; //History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_CreateCol, this.getId(), null, new UndoRedoData_SingleProperty(index)); } } return oCurCol; }; Woorksheet.prototype._removeCol=function(index){ //0-based delete this.aCols[index]; }; Woorksheet.prototype._moveCellHor=function(nRow, nCol, dif){ var cell = this._getCellNoEmpty(nRow, nCol); if(cell) { cell.moveHor(dif); var row = this._getRow(nRow); row.c[nCol + dif] = cell; delete row.c[nCol]; } }; Woorksheet.prototype._moveCellVer=function(nRow, nCol, dif){ var cell = this._getCellNoEmpty(nRow, nCol); if(cell) { cell.moveVer(dif); var oCurRow = this._getRow(nRow); var oTargetRow = this._getRow(nRow + dif); delete oCurRow.c[nCol]; oTargetRow.c[nCol] = cell; if(oCurRow.isEmpty()) delete this.aGCells[nRow]; } }; Woorksheet.prototype._prepareMoveRangeGetCleanRanges=function(oBBoxFrom, oBBoxTo){ var intersection = oBBoxFrom.intersectionSimple(oBBoxTo); var aRangesToCheck = []; if(null != intersection) { var oThis = this; var fAddToRangesToCheck = function(aRangesToCheck, r1, c1, r2, c2) { if(r1 <= r2 && c1 <= c2) aRangesToCheck.push(oThis.getRange3(r1, c1, r2, c2)); }; if(intersection.r1 == oBBoxTo.r1 && intersection.c1 == oBBoxTo.c1) { fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, intersection.c2 + 1, intersection.r2, oBBoxTo.c2); fAddToRangesToCheck(aRangesToCheck, intersection.r2 + 1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2); } else if(intersection.r2 == oBBoxTo.r2 && intersection.c1 == oBBoxTo.c1) { fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r1 - 1, oBBoxTo.c2); fAddToRangesToCheck(aRangesToCheck, intersection.r1, intersection.c2 + 1, oBBoxTo.r2, oBBoxTo.c2); } else if(intersection.r1 == oBBoxTo.r1 && intersection.c2 == oBBoxTo.c2) { fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r2, intersection.c1 - 1); fAddToRangesToCheck(aRangesToCheck, intersection.r2 + 1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2); } else if(intersection.r2 == oBBoxTo.r2 && intersection.c2 == oBBoxTo.c2) { fAddToRangesToCheck(aRangesToCheck, oBBoxTo.r1, oBBoxTo.c1, intersection.r1 - 1, oBBoxTo.c2); fAddToRangesToCheck(aRangesToCheck, intersection.r1, oBBoxTo.c1, oBBoxTo.r2, intersection.c1 - 1); } } else aRangesToCheck.push(this.getRange3(oBBoxTo.r1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2)); return aRangesToCheck; }; Woorksheet.prototype._prepareMoveRange=function(oBBoxFrom, oBBoxTo){ var res = 0; if(oBBoxFrom.isEqual(oBBoxTo)) return res; var range = this.getRange3(oBBoxTo.r1, oBBoxTo.c1, oBBoxTo.r2, oBBoxTo.c2); var aMerged = this.mergeManager.get(range.getBBox0()); if(aMerged.outer.length > 0) return -2; var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo); for(var i = 0, length = aRangesToCheck.length; i < length; i++) { range = aRangesToCheck[i]; range._foreachNoEmpty( function(cell){ if(!cell.isEmptyTextString()) { res = -1; return res; } }); if(0 != res) return res; } return res; }; Woorksheet.prototype._moveRange=function(oBBoxFrom, oBBoxTo, copyRange){ if(oBBoxFrom.isEqual(oBBoxTo)) return; var oThis = this; History.Create_NewPoint(); History.StartTransaction(); var offset = { offsetRow : oBBoxTo.r1 - oBBoxFrom.r1, offsetCol : oBBoxTo.c1 - oBBoxFrom.c1 }; var intersection = oBBoxFrom.intersectionSimple(oBBoxTo); var oRangeIntersection = null; if(null != intersection) oRangeIntersection = this.getRange3(intersection.r1, intersection.c1, intersection.r2, intersection.c2 ); //запоминаем то что нужно переместить var aTempObj = {cells: {}, merged: null, hyperlinks: null}; for(var i = oBBoxFrom.r1; i <= oBBoxFrom.r2; i++) { var row = this._getRowNoEmpty(i); if(null != row) { var oTempRow = {}; aTempObj.cells[i + offset.offsetRow] = oTempRow; for(var j = oBBoxFrom.c1; j <= oBBoxFrom.c2; j++) { var cell = row.c[j]; if(null != cell){ if(copyRange) oTempRow[j + offset.offsetCol] = cell.clone(); else oTempRow[j + offset.offsetCol] = cell; } } } } if(false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges)) { History.LocalChange = true; var aMerged = this.mergeManager.get(oBBoxFrom); if(aMerged.inner.length > 0) aTempObj.merged = aMerged.inner; var aHyperlinks = this.hyperlinkManager.get(oBBoxFrom); if(aHyperlinks.inner.length > 0) aTempObj.hyperlinks = aHyperlinks.inner; var aMergedToRemove = null; if(!copyRange){ aMergedToRemove = aTempObj.merged; } else if(null != intersection){ var aMergedIntersection = this.mergeManager.get(intersection); if(aMergedIntersection.all.length > 0) aMergedToRemove = aMergedIntersection.all; } if(null != aMergedToRemove){ for(var i = 0, length = aMergedToRemove.length; i < length; i++) { var elem = aMergedToRemove[i]; this.mergeManager.removeElement(elem); } } if(!copyRange){ if(null != aTempObj.hyperlinks) { for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++) { var elem = aTempObj.hyperlinks[i]; this.hyperlinkManager.removeElement(elem); } } } History.LocalChange = false; } //удаляем to через историю, для undo var aRangesToCheck = this._prepareMoveRangeGetCleanRanges(oBBoxFrom, oBBoxTo); for (var i = 0, length = aRangesToCheck.length; i < length; i++) { var range = aRangesToCheck[i]; range.cleanAll(); //выставляем для slave refError if (!copyRange) this.workbook.dependencyFormulas.deleteNodes(this.getId(), range.getBBox0()); } //удаляем from без истории, потому что эти данные не терются а перемещаются if(!copyRange || (copyRange && this.workbook.bUndoChanges)){ var oRangeFrom = this.getRange3(oBBoxFrom.r1, oBBoxFrom.c1, oBBoxFrom.r2, oBBoxFrom.c2 ); oRangeFrom._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){ var row = oThis._getRowNoEmpty(nRow0); if(null != row) delete row.c[nCol0]; }); } else{ //в случае копирования удаляем пересечение, чтобы затирались значения, если мы копируем пустые ячейки(все что не входит в пересечение удалилось выше через историю) if(null != intersection){ oRangeIntersection._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){ var row = oThis._getRowNoEmpty(nRow0); if(null != row) delete row.c[nCol0]; }); } } if(!copyRange){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); this.workbook.dependencyFormulas.helper(oBBoxFrom, oBBoxTo,this.Id); } for ( var i in aTempObj.cells ) { var oTempRow = aTempObj.cells[i]; var row = this._getRow( i - 0 ); for ( var j in oTempRow ) { var oTempCell = oTempRow[j]; if ( null != oTempCell ) { oTempCell.moveHor( offset.offsetCol ); oTempCell.moveVer( offset.offsetRow ); row.c[j] = oTempCell; if ( oTempCell.sFormula ) { if(copyRange){ oTempCell.formulaParsed = new parserFormula( oTempCell.sFormula, g_oCellAddressUtils.getCellId(oTempCell.nRow, oTempCell.nCol), this ); oTempCell.formulaParsed.parse(); oTempCell.formulaParsed = oTempCell.formulaParsed.changeOffset(offset); oTempCell.sFormula = oTempCell.formulaParsed.assemble(); addToArrRecalc(this.getId(), oTempCell); } } } } } if(false == this.workbook.bUndoChanges && false == this.workbook.bRedoChanges) this.autoFilters._moveAutoFilters( oBBoxTo, oBBoxFrom, null, copyRange, true, oBBoxFrom ); if(false == this.workbook.bUndoChanges && (false == this.workbook.bRedoChanges || true == this.workbook.bCollaborativeChanges)) { History.LocalChange = true; if(null != aTempObj.merged) { for(var i = 0, length = aTempObj.merged.length; i < length; i++) { var elem = aTempObj.merged[i]; var oNewBBox; var oNewData = elem.data; if(copyRange) oNewBBox = elem.bbox.clone(); else oNewBBox = elem.bbox; oNewBBox.setOffset(offset); this.mergeManager.add(oNewBBox, oNewData); } } //todo сделать для пересечения if(null != aTempObj.hyperlinks && (!copyRange || null == intersection)) { for(var i = 0, length = aTempObj.hyperlinks.length; i < length; i++) { var elem = aTempObj.hyperlinks[i]; var oNewBBox; var oNewData; if(copyRange){ oNewBBox = elem.bbox.clone(); oNewData = elem.data.clone(); } else{ oNewBBox = elem.bbox; oNewData = elem.data; } oNewBBox.setOffset(offset); this.hyperlinkManager.add(oNewBBox, oNewData); } } History.LocalChange = false; } //расширяем границы if(oBBoxFrom.r2 >= this.nRowsCount) this.nRowsCount = oBBoxFrom.r2 + 1; if(oBBoxFrom.c2 >= this.nColsCount) this.nColsCount = oBBoxFrom.c2 + 1; if(oBBoxTo.r2 >= this.nRowsCount) this.nRowsCount = oBBoxTo.r2 + 1; if(oBBoxTo.c2 >= this.nColsCount) this.nColsCount = oBBoxTo.c2 + 1; if(!copyRange){ var sBBoxFromName = oBBoxFrom.getName(); this.workbook.needRecalc.nodes[getVertexId(this.getId(), sBBoxFromName)] = [this.getId(), sBBoxFromName]; this.workbook.needRecalc.length++; } var sBBoxToName = oBBoxTo.getName(); this.workbook.needRecalc.nodes[getVertexId(this.getId(), sBBoxToName)] = [this.getId(), sBBoxToName]; this.workbook.needRecalc.length++; if (!this.workbook.lockCounter){ /* Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!". */ this.workbook.sortDependency(); } if(true == this.workbook.bUndoChanges || true == this.workbook.bRedoChanges) { this.autoFilters.unmergeTablesAfterMove( oBBoxTo ); } // ToDo возможно нужно уменьшить диапазон обновления History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_MoveRange, this.getId(), new Asc.Range(0, 0, gc_nMaxCol0, gc_nMaxRow0), new UndoRedoData_FromTo(new UndoRedoData_BBox(oBBoxFrom), new UndoRedoData_BBox(oBBoxTo), copyRange)); History.EndTransaction(); return true; }; Woorksheet.prototype._shiftCellsLeft=function(oBBox){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); //todo удаление когда есть замерженые ячейки var nLeft = oBBox.c1; var nRight = oBBox.c2; var dif = nLeft - nRight - 1; this.renameDependencyNodes( {offsetRow:0,offsetCol:dif}, oBBox ); for(var i = oBBox.r1; i <= oBBox.r2; i++){ var row = this.aGCells[i]; if(row){ var aIndexes = []; for(var cellInd in row.c) { var nIndex = cellInd - 0; if(nIndex >= nLeft) aIndexes.push(nIndex); } //По возрастанию aIndexes.sort(fSortAscending); for(var j = 0, length2 = aIndexes.length; j < length2; ++j){ var nCellInd = aIndexes[j]; if(nCellInd <= nRight){ //Удаляем ячейки this._removeCell(i, nCellInd); } else{ //Сдвигаем ячейки this._moveCellHor(i, nCellInd, dif, oBBox); } } } } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsLeft, this.getId(), new Asc.Range(nLeft, oBBox.r1, gc_nMaxCol0, oBBox.r2), new UndoRedoData_BBox(oBBox)); this.autoFilters.insertColumn( "delCell", oBBox, c_oAscDeleteOptions.DeleteCellsAndShiftLeft ); //todo проверить не уменьшились ли границы таблицы }; Woorksheet.prototype._shiftCellsUp=function(oBBox){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); var nTop = oBBox.r1; var nBottom = oBBox.r2; var dif = nTop - nBottom - 1; this.renameDependencyNodes({offsetRow:dif,offsetCol:0}, oBBox ); var aIndexes = []; for(var i in this.aGCells) { var rowInd = i - 0; if(rowInd >= nTop) aIndexes.push(rowInd); } //по возрастанию aIndexes.sort(fSortAscending); for(var i = 0, length = aIndexes.length; i < length; ++i){ var rowInd = aIndexes[i]; var row = this.aGCells[rowInd]; if(row){ if(rowInd <= nBottom){ //Удаляем ячейки for(var j = oBBox.c1; j <= oBBox.c2; j++){ this._removeCell(rowInd, j); } } else{ var nIndex = rowInd + dif; var rowTop = this._getRow(nIndex); //Сдвигаем ячейки for(var j = oBBox.c1; j <= oBBox.c2; j++){ this._moveCellVer(rowInd, j, dif); } } } } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsTop, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, gc_nMaxRow0), new UndoRedoData_BBox(oBBox)); this.autoFilters.insertRows( "delCell", oBBox, c_oAscDeleteOptions.DeleteCellsAndShiftTop ); //todo проверить не уменьшились ли границы таблицы }; Woorksheet.prototype._shiftCellsRight=function(oBBox, displayNameFormatTable){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); var nLeft = oBBox.c1; var nRight = oBBox.c2; var dif = nRight - nLeft + 1; this.renameDependencyNodes({offsetRow:0,offsetCol:dif}, oBBox); for(var i = oBBox.r1; i <= oBBox.r2; i++){ var row = this.aGCells[i]; if(row){ var aIndexes = []; for(var cellInd in row.c) { var nIndex = cellInd - 0; if(nIndex >= nLeft) aIndexes.push(nIndex); } //по убыванию aIndexes.sort(fSortDescending); for(var j = 0, length2 = aIndexes.length; j < length2; ++j){ var nCellInd = aIndexes[j]; //Сдвигаем ячейки var cell = row.c[nCellInd]; if(cell){ if(nCellInd + dif > this.nColsCount) this.nColsCount = nCellInd + dif; this._moveCellHor(/*row*/i, /*col*/nCellInd, dif, oBBox); } } } } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsRight, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, gc_nMaxCol0, oBBox.r2), new UndoRedoData_BBox(oBBox)); this.autoFilters.insertColumn( "insCells", oBBox, c_oAscInsertOptions.InsertCellsAndShiftRight, displayNameFormatTable ); }; Woorksheet.prototype._shiftCellsBottom=function(oBBox, displayNameFormatTable){ //до перемещения ячеек, перед функцией, в которой используются nodesSheetArea/nodesSheetCell move/shift нужно обязательно вызвать force buildRecalc //чтобы формулы, которые копим попали в струкруры nodesSheet, иначе формулы не сдвинутся //например принимаем изменения: добавление формул, сдвиг с помощью _removeRows. результат формулы указывают на теже ячейки, что и до _removeRows this.workbook.buildRecalc(true, true); var nTop = oBBox.r1; var nBottom = oBBox.r2; var dif = nBottom - nTop + 1; var aIndexes = []; this.renameDependencyNodes({offsetRow:dif,offsetCol:0}, oBBox); for(var i in this.aGCells){ var rowInd = i - 0; if(rowInd >= nTop) aIndexes.push(rowInd); } //по убыванию aIndexes.sort(fSortDescending); for(var i = 0, length = aIndexes.length; i < length; ++i){ rowInd = aIndexes[i]; var row = this.aGCells[rowInd]; if(row){ var nIndex = rowInd + dif; if(nIndex + dif > this.nRowsCount) this.nRowsCount = nIndex + dif; var rowTop = this._getRow(nIndex); //Сдвигаем ячейки for(var j = oBBox.c1; j <= oBBox.c2; j++){ this._moveCellVer(rowInd, j, dif); } } } History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ShiftCellsBottom, this.getId(), new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, gc_nMaxRow0), new UndoRedoData_BBox(oBBox)); this.autoFilters.insertRows( "insCell", oBBox, c_oAscInsertOptions.InsertCellsAndShiftDown, displayNameFormatTable ); }; Woorksheet.prototype._setIndex=function(ind){ this.index = ind; }; Woorksheet.prototype._BuildDependencies=function(cellRange){ /* Построение графа зависимостей. */ var c, ca, oLengthCache = {}; for(var i in cellRange){ ca = g_oCellAddressUtils.getCellAddress(i); c = this._getCellNoEmpty(ca.getRow0(),ca.getCol0()); if( c && c.sFormula ){ var elem = oLengthCache[c.sFormula.length]; if(null == elem) { elem = []; oLengthCache[c.sFormula.length] = elem; } elem.push(c); } } for(var i in oLengthCache) { var temp = oLengthCache[i]; var aCache = []; for(var j = 0, length2 = temp.length; j < length2; j++) { var c = temp[j], cellId = g_oCellAddressUtils.getCellId(c.nRow, c.nCol ), aRefs = [], cache = inCache(aCache, c.sFormula, aRefs ), bInCache = false; if(cache) { bInCache = true; var oNewFormula = cache.formulaParsed.clone(c.sFormula, cellId, this); var RefPos = cache.formulaParsed.RefPos; for(var k = 0, length3 = RefPos.length; k < length3; k++) { var pos = RefPos[k]; var elem = oNewFormula.outStack[pos.index]; if(elem) { //todo случай ,если ref число или именованный диапазон var ref = aRefs[k]; var range = AscCommonExcel.g_oRangeCache.getAscRange(ref); if(null != range) { var oNewElem; if(range.isOneCell()) { if(elem instanceof cRef3D) oNewElem = new cRef3D(ref, elem.ws.getName(), elem._wb); else if(elem instanceof cArea3D) { var wsFrom = elem._wb.getWorksheetById( elem.wsFrom ).getName(); var wsTo = elem._wb.getWorksheetById( elem.wsTo ).getName(); oNewElem = new cArea3D(ref, wsFrom, wsTo, elem._wb); } else if(-1 != ref.indexOf(":"))//случай "A1:A1" oNewElem = new AscCommonExcel.cArea(ref, elem.ws); else oNewElem = new AscCommonExcel.cRef(ref, elem.ws); } else { if(elem instanceof cRef3D) oNewElem = new cArea3D(ref, elem.ws.getName(), elem.ws.getName(), elem._wb); else if(elem instanceof cArea3D) { var wsFrom = elem._wb.getWorksheetById( elem.wsFrom ).getName(); var wsTo = elem._wb.getWorksheetById( elem.wsTo ).getName(); oNewElem = new cArea3D(ref, wsFrom, wsTo, elem._wb); } else oNewElem = new AscCommonExcel.cArea(ref, elem.ws); } if ( ref.indexOf( "$" ) > -1 ) oNewElem.isAbsolute = true; // ToDo - пересмотреть этот параметр (есть в Range информация о абсолютной ссылке) oNewFormula.outStack[pos.index] = oNewElem; } else bInCache = false; } } if(bInCache) { c.formulaParsed = oNewFormula; c.formulaParsed.buildDependencies(); } } if(!bInCache) { c.formulaParsed = new parserFormula( c.sFormula, cellId, this ); c.formulaParsed.parse(); c.formulaParsed.buildDependencies(); //error не добавляем в кеш у них не распознались RefPos, их бессмысленно сравнивать.Это только добавит торозов if(0 == c.formulaParsed.error.length) aCache.push(c); } } } }; Woorksheet.prototype._setHandlersTablePart = function(){ if(!this.TableParts) return; for(var i = 0; i < this.TableParts.length; i++) { this.TableParts[i].setHandlers(this.handlers); } }; Woorksheet.prototype.getTableRangeForFormula = function(name, objectParam){ var res = null; if(!this.TableParts) return res; for(var i = 0; i < this.TableParts.length; i++) { if(this.TableParts[i].DisplayName === name) { res = this.TableParts[i].getTableRangeForFormula(objectParam); break; } } return res; }; Woorksheet.prototype.getTableIndexColumnByName = function(tableName, columnName){ var res = null; if(!this.TableParts) return res; for(var i = 0; i < this.TableParts.length; i++) { if(this.TableParts[i].DisplayName === tableName) { res = this.TableParts[i].getTableIndexColumnByName(columnName); break; } } return res; }; Woorksheet.prototype.getTableNameColumnByIndex = function(tableName, columnIndex){ var res = null; if(!this.TableParts) return res; for(var i = 0; i < this.TableParts.length; i++) { if(this.TableParts[i].DisplayName === tableName) { res = this.TableParts[i].getTableNameColumnByIndex(columnIndex); break; } } return res; }; function inCache(aCache, sFormula, aRefs) { var oRes = null; for(var i = 0, length = aCache.length; i < length; i++) { var cache = aCache[i]; var sCurFormula = cache.sFormula; if(null != cache.formulaParsed){ var RefPos = cache.formulaParsed.RefPos; //todo свое сравнение для error if(0 == cache.formulaParsed.error.length && inCacheStrcmp(sCurFormula, sFormula, RefPos, aRefs)){ oRes = cache; break; } } } return oRes; } function inCacheStrcmp(str1, str2, RefPos, aRefs) { var bRes = true; var nStartIndex = 0; for(var i = 0, length = RefPos.length; i < length; i++) { var mask = RefPos[i]; for(var j = nStartIndex; j < mask.start; j++) { if(str1[j] != str2[j]) { bRes = false; break; } } nStartIndex = mask.end; } if(bRes) { for(var i = nStartIndex; i < str1.length; i++) { if(str1[i] != str2[i]) { bRes = false; break; } } } if(bRes) { for(var i = 0, length = RefPos.length; i < length; i++) { var mask = RefPos[i]; aRefs.push(str2.substring(mask.start, mask.end)); } } return bRes; } Woorksheet.prototype._RecalculatedFunctions=function(cell,bad,setCellFormat){ function adjustCellFormat( c ) { // ищет в формуле первый рэндж и устанавливает формат ячейки как формат первой ячейки в рэндже var elem = null; if ( c.formulaParsed && c.formulaParsed.outStack ) { for ( var i = 0, length = c.formulaParsed.outStack.length; i < length; i++ ) { elem = c.formulaParsed.outStack[i]; if ( elem instanceof AscCommonExcel.cRef || elem instanceof cRef3D || elem instanceof AscCommonExcel.cArea || elem instanceof cArea3D ) { var r = elem.getRange(); if ( elem instanceof cArea3D && r.length > 0 ) r = r[0]; if ( r && r.getNumFormatStr ) { var sCurFormat = c.getNumFormatStr(); if ( g_oDefaultFormat.Num.getFormat() == sCurFormat ) { var sNewFormat = r.getNumFormatStr(); if ( sCurFormat != sNewFormat ) c.setNumFormat( sNewFormat ); } } break; } } } } if( cell.indexOf(":")>-1 ) return; var celladd = this.getRange2(cell).getFirst(), __cell = this._getCellNoEmpty( celladd.getRow0(),celladd.getCol0() ), res; if( !__cell || !__cell.sFormula ) return; /* bad - флаг, показывающий, что ячейка находится в списке плохих ячеек (имеются циклические ссылки на ячейку), после сортировки графа зависимостей. */ if(!bad){ res = __cell.formulaParsed.calculate(); } else { res = new AscCommonExcel.cError( AscCommonExcel.cErrorType.bad_reference ) } if(res){ if( res.type == cElementType.cell){ var nF = res.numFormat; res = res.getValue(); res.numFormat = nF; } else if( res.type == cElementType.array ){ var nF = res.numFormat; res = res.getElement(0); res.numFormat = nF; } else if( res.type == cElementType.cellsRange || res.type == cElementType.cellsRange3D ){ var nF = res.numFormat; res = res.cross( new CellAddress(cell), this.Id ); // res = res.getElementByCell(new CellAddress(cell)); res.numFormat = nF; } __cell.oValue.clean(); switch (res.type){ case cElementType.number: __cell.oValue.type = CellValueType.Number; __cell.oValue.number = res.getValue(); break; case cElementType.bool: __cell.oValue.type = CellValueType.Bool; __cell.oValue.number = res.value ? 1 : 0; break; case cElementType.error: __cell.oValue.type = CellValueType.Error; __cell.oValue.text = res.getValue().toString(); break; case cElementType.name: __cell.oValue.type = CellValueType.Error; __cell.oValue.text = res.getValue().toString(); break; default: __cell.oValue.type = CellValueType.String; __cell.oValue.text = res.getValue().toString(); } AscCommonExcel.g_oVLOOKUPCache.remove(__cell); AscCommonExcel.g_oHLOOKUPCache.remove(__cell); __cell.setFormulaCA(res.ca); if(setCellFormat){ if( res.numFormat !== undefined && res.numFormat >= 0){ if( aStandartNumFormatsId[__cell.getNumFormatStr()] == 0 ) __cell.setNumFormat(aStandartNumFormats[res.numFormat]) } else if( res.numFormat !== undefined && res.numFormat == -1 ){ adjustCellFormat(__cell,__cell.sFormula); } } } }; Woorksheet.prototype._ReBuildFormulas=function(cellRange){ /* Если существуют трехмерные ссылки на ячейки, то у них необходимо поменять имя листа на новое после переименования листа. */ var c, ca; for(var i in cellRange){ ca = new CellAddress(i); c = this._getCellNoEmpty(ca.getRow0(),ca.getCol0()); if( c && c.formulaParsed && c.formulaParsed.is3D ){ c.setFormula(c.formulaParsed.assemble()); } } }; Woorksheet.prototype.renameDependencyNodes = function(offset, oBBox, rec, noDelete){ this.workbook.dependencyFormulas.checkOffset(oBBox, offset, this.Id, noDelete); }; Woorksheet.prototype.getAllCol = function(){ if(null == this.oAllCol) this.oAllCol = new AscCommonExcel.Col(this, g_nAllColIndex); return this.oAllCol; }; Woorksheet.prototype.getAllRow = function(){ if (null == this.oSheetFormatPr.oAllRow) { this.oSheetFormatPr.oAllRow = new AscCommonExcel.Row(this); this.oSheetFormatPr.oAllRow.create(g_nAllRowIndex + 1); } return this.oSheetFormatPr.oAllRow; }; Woorksheet.prototype.getHyperlinkByCell = function(row, col){ var oHyperlink = this.hyperlinkManager.getByCell(row, col); return oHyperlink ? oHyperlink.data : null; }; Woorksheet.prototype.getMergedByCell = function(row, col){ var oMergeInfo = this.mergeManager.getByCell(row, col); return oMergeInfo ? oMergeInfo.bbox : null; }; Woorksheet.prototype.getMergedByRange = function(bbox){ return this.mergeManager.get(bbox); }; Woorksheet.prototype._expandRangeByMergedAddToOuter = function(aOuter, range, aMerged){ for(var i = 0, length = aMerged.all.length; i < length; i++) { var elem = aMerged.all[i]; if(!range.containsRange(elem.bbox)) aOuter.push(elem); } }; Woorksheet.prototype._expandRangeByMergedGetOuter = function(range){ var aOuter = []; //смотрим только границы this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c1, r2: range.r2, c2: range.c1})); if(range.c1 != range.c2) { this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c2, r2: range.r2, c2: range.c2})); if(range.c2 - range.c1 > 1) { this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r1, c1: range.c1 + 1, r2: range.r1, c2: range.c2 - 1})); if(range.r1 != range.r2) this._expandRangeByMergedAddToOuter(aOuter, range, this.mergeManager.get({r1: range.r2, c1: range.c1 + 1, r2: range.r2, c2: range.c2 - 1})); } } return aOuter; }; Woorksheet.prototype.expandRangeByMerged = function(range){ if(null != range) { var aOuter = this._expandRangeByMergedGetOuter(range); if(aOuter.length > 0) { range = range.clone(); while(aOuter.length > 0) { for(var i = 0, length = aOuter.length; i < length; i++) range.union2(aOuter[i].bbox); aOuter = this._expandRangeByMergedGetOuter(range); } } } return range; }; Woorksheet.prototype.createTablePart = function(){ return new AscCommonExcel.TablePart(this.handlers); }; Woorksheet.prototype.onUpdateRanges = function(ranges) { this.workbook.updateSparklineCache(this.sName, ranges); this._updateConditionalFormatting(new AscCommonExcel.MultiplyRange(ranges)); }; Woorksheet.prototype.updateSparklineCache = function(sheet, ranges) { for (var i = 0; i < this.sparklineGroups.arrSparklineGroup.length; ++i) { this.sparklineGroups.arrSparklineGroup[i].updateCache(sheet, ranges); } }; //------------------------------------------------------------------------------------------------- /** * @constructor */ function Cell(worksheet){ this.ws = worksheet; this.oValue = new AscCommonExcel.CCellValue(); this.xfs = null; this.tableXfs = null; this.conditionalFormattingXfs = null; this.compiledXfs = null; this.nRow = -1; this.nCol = -1; this.sFormula = null; this.sFormulaCA = null; this.formulaParsed = null; } Cell.prototype.getStyle=function(){ return this.xfs; }; Cell.prototype.getCompiledStyle = function () { if (null == this.compiledXfs && (null != this.xfs || null != this.tableXfs || null != this.conditionalFormattingXfs)) { this.compileXfs(); } return this.compiledXfs; }; Cell.prototype.compileXfs=function(){ this.compiledXfs = null; if(null != this.xfs || null != this.tableXfs || null != this.conditionalFormattingXfs) { if(null != this.tableXfs) this.compiledXfs = this.tableXfs; if(null != this.xfs) { if(null != this.compiledXfs) this.compiledXfs = this.xfs.merge(this.compiledXfs); else this.compiledXfs = this.xfs; } if(null != this.conditionalFormattingXfs) { if(null != this.compiledXfs) this.compiledXfs = this.conditionalFormattingXfs.merge(this.compiledXfs); else this.compiledXfs = this.xfs; } } }; Cell.prototype.clone=function(oNewWs){ if(!oNewWs) oNewWs = this.ws; var oNewCell = new Cell(oNewWs); oNewCell.nRow = this.nRow; oNewCell.nCol = this.nCol; if(null != this.xfs) oNewCell.xfs = this.xfs.clone(); oNewCell.oValue = this.oValue.clone(); if(null != this.sFormula) oNewCell.sFormula = this.sFormula; return oNewCell; }; Cell.prototype.create=function(xfs, nRow, nCol){ this.xfs = xfs; this.nRow = nRow; this.nCol = nCol; }; Cell.prototype.isEmptyText=function(){ if(false == this.oValue.isEmpty()) return false; if(null != this.sFormula) return false; return true; }; Cell.prototype.isEmptyTextString=function(){ return this.oValue.isEmpty(); }; Cell.prototype.isEmpty=function(){ if(false == this.isEmptyText()) return false; if(null != this.xfs) return false; return true; }; Cell.prototype.isFormula=function(){ return this.sFormula ? true : false; }; Cell.prototype.Remove=function(){ this.ws._removeCell(null, null, this); }; Cell.prototype.getName=function(){ return g_oCellAddressUtils.getCellId(this.nRow, this.nCol); }; Cell.prototype.cleanCache=function(){ this.oValue.cleanCache(); }; Cell.prototype.setFormula=function(val, bAddToHistory){ if(bAddToHistory) { History.Add( AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RemoveCellFormula, this.ws.getId(), new Asc.Range( this.nCol, this.nRow, this.nCol, this.nRow ), new UndoRedoData_CellSimpleData( this.nRow, this.nCol, null, null, this.sFormula )); } this.sFormula = val; this.oValue.cleanCache(); }; Cell.prototype.setValue=function(val,callback, isCopyPaste){ var ret = true; var DataOld = null; if(History.Is_On()) DataOld = this.getValueData(); var bIsTextFormat = false; if(!isCopyPaste){ var sNumFormat; if(null != this.xfs && null != this.xfs.num) sNumFormat = this.xfs.num.getFormat(); else sNumFormat = g_oDefaultFormat.Num.getFormat(); var numFormat = oNumFormatCache.get(sNumFormat); bIsTextFormat = numFormat.isTextFormat(); } var wb = this.ws.workbook; var ws = this.ws; if(false == bIsTextFormat) { /* Устанавливаем значение в Range ячеек. При этом происходит проверка значения на формулу. Если значение является формулой, то проверяем содержиться ли в ячейке формула или нет, если "да" - то очищаем в графе зависимостей список, от которых зависит формула(masterNodes), позже будет построен новый. Затем выставляем флаг о необходимости дальнейшего пересчета, и заносим ячейку в список пересчитываемых ячеек. */ if( null != val && val[0] == "=" && val.length > 1){ var oldFP = undefined; if( this.formulaParsed ) oldFP = this.formulaParsed; var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol); this.formulaParsed = new parserFormula(val.substring(1),cellId,this.ws); var formulaLocaleParse = isCopyPaste === true ? false : oFormulaLocaleInfo.Parse; var formulaLocaleDigetSep = isCopyPaste === true ? false : oFormulaLocaleInfo.DigitSep; if( !this.formulaParsed.parse( formulaLocaleParse, formulaLocaleDigetSep ) ){ switch( this.formulaParsed.error[this.formulaParsed.error.length-1] ){ case c_oAscError.ID.FrmlWrongFunctionName: break; case c_oAscError.ID.FrmlParenthesesCorrectCount: this.setValue("="+this.formulaParsed.Formula, callback, isCopyPaste); return; default :{ wb.handlers.trigger("asc_onError",this.formulaParsed.error[this.formulaParsed.error.length-1], c_oAscError.Level.NoCritical); if( callback ) callback(false); if( oldFP !== undefined ){ this.formulaParsed = oldFP; } return; } } } else{ val = "="+this.formulaParsed.assemble(); } } else{ this.formulaParsed = null; } } //удаляем старые значения this.oValue.clean(); var sheetId = this.ws.getId(); var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol); if (this.sFormula) wb.dependencyFormulas.deleteMasterNodes2( ws.Id, cellId ); if( !(null != val && val[0] != "=" || true == bIsTextFormat)) addToArrRecalc(this.ws.getId(), this); wb.needRecalc.nodes[getVertexId(sheetId,cellId)] = [sheetId, cellId]; wb.needRecalc.length++; this.sFormula = null; this.setFormulaCA(false); if(val){ if(false == bIsTextFormat && val[0] == "=" && val.length > 1){ this.setFormula( val.substring(1) ); } else { this.oValue.setValue(this, val); this.formulaParsed = null; } } var DataNew = null; if(History.Is_On()) DataNew = this.getValueData(); if(History.Is_On() && false == DataOld.isEqual(DataNew)) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew)); if (!this.ws.workbook.lockCounter) { /* Если необходим пересчет, то по списку пересчитываемых ячеек сортируем граф зависимостей и пересчиываем в получившемся порядке. Плохим ячейкам с цикличискими ссылками выставляем ошибку "#REF!". */ //sortDependency вызывается ниже History.Add(AscCH.historyitem_Cell_ChangeValue, потому что в ней может быть выставлен формат ячейки(если это текстовый, то принимая изменения формула станет текстом) this.ws.workbook.sortDependency(true); } //todo не должны удаляться ссылки, если сделать merge ее части. if(this.isEmptyTextString()) { var cell = this.ws.getCell3(this.nRow, this.nCol); cell.removeHyperlink(); } return ret; }; Cell.prototype.setValue2=function(array){ var DataOld = null; if(History.Is_On()) DataOld = this.getValueData(); //[{text:"",format:TextFormat},{}...] this.setValueCleanFormula(); this.oValue.clean(); this.oValue.setValue2(this, array); this.ws.workbook.sortDependency(); var DataNew = null; if(History.Is_On()) DataNew = this.getValueData(); if(History.Is_On() && false == DataOld.isEqual(DataNew)) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew)); //todo не должны удаляться ссылки, если сделать merge ее части. if(this.isEmptyTextString()) { var cell = this.ws.getCell3(this.nRow, this.nCol); cell.removeHyperlink(); } }; Cell.prototype.setValueCleanFormula = function (array) { //удаляем сторое значение var ws = this.ws; var wb = this.ws.workbook; var sheetId = this.ws.getId(); var cellId = g_oCellAddressUtils.getCellId(this.nRow, this.nCol); if (this.sFormula) wb.dependencyFormulas.deleteMasterNodes2(ws.Id, cellId); this.sFormula = null; this.formulaParsed = null; this.setFormulaCA(false); wb.needRecalc.nodes[getVertexId(sheetId, cellId)] = [sheetId, cellId]; wb.needRecalc.length++; }; Cell.prototype.setType=function(type){ if(type != this.oValue.type){ var DataOld = this.getValueData(); this.oValue.setValueType(type); var DataNew = this.getValueData(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew)); } return this.oValue.type; }; Cell.prototype.getType=function(){ return this.oValue.type; }; Cell.prototype.setCellStyle=function(val){ var newVal = this.ws.workbook.CellStyles._prepareCellStyle(val); var oRes = this.ws.workbook.oStyleManager.setCellStyle(this, newVal); if(History.Is_On()) { var oldStyleName = this.ws.workbook.CellStyles.getStyleNameByXfId(oRes.oldVal); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Style, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldStyleName, val)); // Выставляем стиль var oStyle = this.ws.workbook.CellStyles.getStyleByXfId(oRes.newVal); if (oStyle.ApplyFont) this.setFont(oStyle.getFont()); if (oStyle.ApplyFill) this.setFill(oStyle.getFill()); if (oStyle.ApplyBorder) this.setBorder(oStyle.getBorder()); if (oStyle.ApplyNumberFormat) this.setNumFormat(oStyle.getNumFormatStr()); } this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setNumFormat=function(val){ var oRes; /*if( val == aStandartNumFormats[0] && this.formulaParsed && this.formulaParsed.value && this.formulaParsed.value.numFormat !== null && this.formulaParsed.value.numFormat !== undefined && aStandartNumFormats[this.formulaParsed.value.numFormat] ) oRes = this.ws.workbook.oStyleManager.setNumFormat(this, aStandartNumFormats[this.formulaParsed.value.numFormat]); else*/ oRes = this.ws.workbook.oStyleManager.setNumFormat(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Numformat, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.shiftNumFormat=function(nShift, dDigitsCount){ var bRes = false; var bGeneral = true; var sNumFormat; if(null != this.xfs && null != this.xfs.num) sNumFormat = this.xfs.num.getFormat(); else sNumFormat = g_oDefaultFormat.Num.getFormat(); if("General" != sNumFormat) { var oCurNumFormat = oNumFormatCache.get(sNumFormat); if(null != oCurNumFormat && false == oCurNumFormat.isGeneralFormat()) { bGeneral = false; var output = {}; bRes = oCurNumFormat.shiftFormat(output, nShift); if(true == bRes) this.setNumFormat(output.format); } } if(bGeneral) { if(CellValueType.Number == this.oValue.type) { var sGeneral = AscCommon.DecodeGeneralFormat(this.oValue.number, this.oValue.type, dDigitsCount); var oGeneral = oNumFormatCache.get(sGeneral); if(null != oGeneral && false == oGeneral.isGeneralFormat()) { var output = {}; bRes = oGeneral.shiftFormat(output, nShift); if(true == bRes) this.setNumFormat(output.format); } } } this.oValue.cleanCache(); return bRes; }; Cell.prototype.setFont=function(val, bModifyValue){ if(false != bModifyValue) { //убираем комплексные строки if(null != this.oValue.multiText) { var oldVal = null; if(History.Is_On()) oldVal = this.getValueData(); this.oValue.makeSimpleText(); if(History.Is_On()) { var newVal = this.getValueData(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal)); } } } var oRes = this.ws.workbook.oStyleManager.setFont(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) { var oldVal = null; if(null != oRes.oldVal) oldVal = oRes.oldVal.clone(); var newVal = null; if(null != oRes.newVal) newVal = oRes.newVal.clone(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetFont, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal)); } this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setFontname=function(val){ var oRes = this.ws.workbook.oStyleManager.setFontname(this, val); this.oValue.setFontname(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontname, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setFontsize=function(val){ var oRes = this.ws.workbook.oStyleManager.setFontsize(this, val); this.oValue.setFontsize(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontsize, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setFontcolor=function(val){ var oRes = this.ws.workbook.oStyleManager.setFontcolor(this, val); this.oValue.setFontcolor(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fontcolor, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setBold=function(val){ var oRes = this.ws.workbook.oStyleManager.setBold(this, val); this.oValue.setBold(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Bold, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setItalic=function(val){ var oRes = this.ws.workbook.oStyleManager.setItalic(this, val); this.oValue.setItalic(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Italic, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setUnderline=function(val){ var oRes = this.ws.workbook.oStyleManager.setUnderline(this, val); this.oValue.setUnderline(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Underline, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setStrikeout=function(val){ var oRes = this.ws.workbook.oStyleManager.setStrikeout(this, val); this.oValue.setStrikeout(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Strikeout, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setFontAlign=function(val){ var oRes = this.ws.workbook.oStyleManager.setFontAlign(this, val); this.oValue.setFontAlign(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_FontAlign, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.setAlignVertical=function(val){ var oRes = this.ws.workbook.oStyleManager.setAlignVertical(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_AlignVertical, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setAlignHorizontal=function(val){ var oRes = this.ws.workbook.oStyleManager.setAlignHorizontal(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_AlignHorizontal, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setFill=function(val){ var oRes = this.ws.workbook.oStyleManager.setFill(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Fill, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setBorder=function(val){ var oRes = this.ws.workbook.oStyleManager.setBorder(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal){ var oldVal = null; if(null != oRes.oldVal) oldVal = oRes.oldVal.clone(); var newVal = null; if(null != oRes.newVal) newVal = oRes.newVal.clone(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Border, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal)); } this.compiledXfs = null; }; Cell.prototype.setShrinkToFit=function(val){ var oRes = this.ws.workbook.oStyleManager.setShrinkToFit(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ShrinkToFit, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setWrap=function(val){ var oRes = this.ws.workbook.oStyleManager.setWrap(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Wrap, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setAngle=function(val){ var oRes = this.ws.workbook.oStyleManager.setAngle(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Angle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setVerticalText=function(val){ var oRes = this.ws.workbook.oStyleManager.setVerticalText(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_Angle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.compiledXfs = null; }; Cell.prototype.setQuotePrefix=function(val){ var oRes = this.ws.workbook.oStyleManager.setQuotePrefix(this, val); if(History.Is_On() && oRes.oldVal != oRes.newVal) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetQuotePrefix, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oRes.oldVal, oRes.newVal)); this.oValue.cleanCache(); }; Cell.prototype.setConditionalFormattingStyle=function(xfs){ this.conditionalFormattingXfs = xfs; this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.getConditionalFormattingStyle = function (xfs) { return this.conditionalFormattingXfs; }; Cell.prototype.setTableStyle=function(xfs){ this.tableXfs = xfs; this.compiledXfs = null; this.oValue.cleanCache(); }; Cell.prototype.getTableStyle=function(){ return this.tableXfs; }; Cell.prototype.setStyle=function(xfs){ var oldVal = this.xfs; var newVal = null; this.xfs = null; if(null != xfs) { this.xfs = xfs.clone(); newVal = this.xfs; } this.compiledXfs = null; this.oValue.cleanCache(); if(History.Is_On() && false == ((null == oldVal && null == newVal) || (null != oldVal && null != newVal && true == oldVal.isEqual(newVal)))) { if(null != oldVal) oldVal = oldVal.clone(); if(null != newVal) newVal = newVal.clone(); History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_SetStyle, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, oldVal, newVal)); } // if(this.isEmpty()) // this.Remove(); }; Cell.prototype.getFormula=function(){ if(null != this.sFormula) return this.sFormula; else return ""; }; Cell.prototype.getValueForEdit=function(numFormat){ return this.oValue.getValueForEdit(this); }; Cell.prototype.getValueForEdit2=function(numFormat){ return this.oValue.getValueForEdit2(this); }; Cell.prototype.getValueWithoutFormat=function(){ return this.oValue.getValueWithoutFormat(); }; Cell.prototype.getValue=function(numFormat, dDigitsCount){ return this.oValue.getValue(this); }; Cell.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){ if(null == fIsFitMeasurer) fIsFitMeasurer = function(aText){return true;}; if(null == dDigitsCount) dDigitsCount = AscCommon.gc_nMaxDigCountView; return this.oValue.getValue2(this, dDigitsCount, fIsFitMeasurer); }; Cell.prototype.getNumFormatStr=function(){ if(null != this.xfs && null != this.xfs.num) return this.xfs.num.getFormat(); return g_oDefaultFormat.Num.getFormat(); }; Cell.prototype.getNumFormat=function(){ return oNumFormatCache.get(this.getNumFormatStr()); }; Cell.prototype.getNumFormatType=function(){ return this.getNumFormat().getType(); }; Cell.prototype.moveHor=function(val){ this.nCol += val; }; Cell.prototype.moveVer=function(val){ this.nRow += val; }; Cell.prototype.getOffset=function(cell){ return {offsetCol:(this.nCol - cell.nCol), offsetRow:(this.nRow - cell.nRow)}; }; Cell.prototype.getOffset2=function(cellId){ var cAddr2 = new CellAddress(cellId); return {offsetCol:(this.nCol - cAddr2.col + 1), offsetRow:(this.nRow - cAddr2.row + 1)}; }; Cell.prototype.getOffset3=function(cellAddr){ var cAddr2 = cellAddr; return {offsetCol:(this.nCol - cAddr2.col + 1), offsetRow:(this.nRow - cAddr2.row + 1)}; }; Cell.prototype.getValueData = function(){ return new UndoRedoData_CellValueData(this.sFormula, this.oValue.clone()); }; Cell.prototype.setValueData = function(Val){ //значения устанавляваются через setValue, чтобы пересчитались формулы if(null != Val.formula) this.setValue("=" + Val.formula); else if(null != Val.value) { var DataOld = null; var DataNew = null; if (History.Is_On()) DataOld = this.getValueData(); this.setValueCleanFormula(); this.oValue = Val.value.clone(this); this.ws.workbook.sortDependency(); if (History.Is_On()) { DataNew = this.getValueData(); if (false == DataOld.isEqual(DataNew)) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, this.ws.getId(), new Asc.Range(this.nCol, this.nRow, this.nCol, this.nRow), new UndoRedoData_CellSimpleData(this.nRow, this.nCol, DataOld, DataNew)); } } else this.setValue(""); }; Cell.prototype.setFormulaCA = function(ca){ if(ca) this.sFormulaCA = true; else if( this.sFormulaCA ) this.sFormulaCA = null; }; //------------------------------------------------------------------------------------------------- /** * @constructor */ function Range(worksheet, r1, c1, r2, c2){ this.worksheet = worksheet; this.bbox = new Asc.Range(c1, r1, c2, r2); //first last устарели, не убраны только для совместимости this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0); this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0); } Range.prototype.createFromBBox=function(worksheet, bbox){ var oRes = new Range(worksheet, bbox.r1, bbox.c1, bbox.r2, bbox.c2); oRes.bbox = bbox.clone(); return oRes; }; Range.prototype.clone=function(oNewWs){ if(!oNewWs) oNewWs = this.worksheet; return new Range(oNewWs, this.bbox.r1, this.bbox.c1, this.bbox.r2, this.bbox.c2); }; Range.prototype.getFirst=function(){ return this.first; }; Range.prototype.getLast=function(){ return this.last; }; Range.prototype._foreach=function(action){ if(null != action) { var oBBox = this.bbox; for(var i = oBBox.r1; i <= oBBox.r2; i++){ for(var j = oBBox.c1; j <= oBBox.c2; j++){ var oCurCell = this.worksheet._getCell(i, j); action(oCurCell, i, j, oBBox.r1, oBBox.c1); } } } }; Range.prototype._foreach2=function(action){ if(null != action) { var oBBox = this.bbox, minC = Math.min( this.worksheet.getColsCount(), oBBox.c2 ), minR = Math.min( this.worksheet.getRowsCount(), oBBox.r2 ); for(var i = oBBox.r1; i <= minR; i++){ for(var j = oBBox.c1; j <= minC; j++){ var oCurCell = this.worksheet._getCellNoEmpty(i, j); var oRes = action(oCurCell, i, j, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } }; Range.prototype._foreachNoEmpty=function(action){ if(null != action) { var oBBox = this.bbox, minC = Math.min( this.worksheet.getColsCount(), oBBox.c2 ), minR = Math.min( this.worksheet.getRowsCount(), oBBox.r2 ); for(var i = oBBox.r1; i <= minR; i++){ for(var j = oBBox.c1; j <= minC; j++){ var oCurCell = this.worksheet._getCellNoEmpty(i, j); if(null != oCurCell) { var oRes = action(oCurCell, i, j, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } }; Range.prototype._foreachRow=function(actionRow, actionCell){ var oBBox = this.bbox; for(var i = oBBox.r1; i <= oBBox.r2; i++){ var row = this.worksheet._getRow(i); if(row) { if(null != actionRow) actionRow(row); if(null != actionCell) { for(var j in row.c){ var oCurCell = row.c[j]; if(null != oCurCell) actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1); } } } } }; Range.prototype._foreachRowNoEmpty=function(actionRow, actionCell){ var oBBox = this.bbox; if(0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2) { var aRows = this.worksheet._getRows(); for(var i in aRows) { var row = aRows[i]; if( null != actionRow ) { var oRes = actionRow(row); if(null != oRes) return oRes; } if( null != actionCell ) for(var j in row.c){ var oCurCell = row.c[j]; if(null != oCurCell) { var oRes = actionCell(oCurCell, i - 0, j - 0, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } else { var minR = Math.min(oBBox.r2,this.worksheet.getRowsCount()); for(var i = oBBox.r1; i <= minR; i++){ var row = this.worksheet._getRowNoEmpty(i); if(row) { if( null != actionRow ) { var oRes = actionRow(row); if(null != oRes) return oRes; } if( null != actionCell ) for(var j in row.c){ var oCurCell = row.c[j]; if(null != oCurCell) { var oRes = actionCell(oCurCell, i, j - 0, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } } }; Range.prototype._foreachCol=function(actionCol, actionCell){ var oBBox = this.bbox; if(null != actionCol) { for(var i = oBBox.c1; i <= oBBox.c2; ++i) { var col = this.worksheet._getCol(i); if(null != col) actionCol(col); } } if(null != actionCell) { var aRows = this.worksheet._getRows(); for(var i in aRows) { var row = aRows[i]; if(row) { if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) { for(var j in row.c) { var oCurCell = row.c[j]; if(null != oCurCell) actionCell(oCurCell, i - 0, j - 0, oBBox.r1, oBBox.c1); } } else { for(var j = oBBox.c1; j <= oBBox.c2; ++j) { var oCurCell = row.c[j]; if(null != oCurCell) actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1); } } } } } }; Range.prototype._foreachColNoEmpty=function(actionCol, actionCell){ var oBBox = this.bbox; var minC = Math.min( oBBox.c2,this.worksheet.getColsCount() ); if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) { if(null != actionCol) { var aCols = this.worksheet._getCols(); for(var i in aCols) { var nIndex = i - 0; if(nIndex >= oBBox.c1 && nIndex <= minC ) { var col = this.worksheet._getColNoEmpty(nIndex); if(null != col) { var oRes = actionCol(col); if(null != oRes) return oRes; } } } } if(null != actionCell) { var aRows = this.worksheet._getRows(); for(var i in aRows) { var row = aRows[i]; if(row) { for(var j in row.c) { var nIndex = j - 0; if(nIndex >= oBBox.c1 && nIndex <= minC) { var oCurCell = row.c[j]; if(null != oCurCell) { var oRes = actionCell(oCurCell, i - 0, nIndex, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } } } } else { if(null != actionCol) { for(var i = oBBox.c1; i <= minC; ++i) { var col = this.worksheet._getColNoEmpty(i); if(null != col) { var oRes = actionCol(col); if(null != oRes) return oRes; } } } if(null != actionCell) { var aRows = this.worksheet._getRows(); for(var i in aRows) { var row = aRows[i]; if(row) { for(var j = oBBox.c1; j <= minC; ++j) { var oCurCell = row.c[j]; if(null != oCurCell) { var oRes = actionCell(oCurCell, i - 0, j, oBBox.r1, oBBox.c1); if(null != oRes) return oRes; } } } } } } }; Range.prototype._foreachIndex=function(action){ var oBBox = this.bbox; for(var i = oBBox.r1; i <= oBBox.r2; i++){ for(var j = oBBox.c1; j <= oBBox.c2; j++){ var res = action(i, j); if(null != res) return res; } } return null; }; Range.prototype._getRangeType=function(oBBox){ if(null == oBBox) oBBox = this.bbox; return getRangeType(oBBox); }; Range.prototype._setProperty=function(actionRow, actionCol, actionCell){ var nRangeType = this._getRangeType(); if(c_oRangeType.Range == nRangeType) this._foreach(actionCell); else if(c_oRangeType.Row == nRangeType) this._foreachRow(actionRow, actionCell); else if(c_oRangeType.Col == nRangeType) this._foreachCol(actionCol, actionCell); else { //сюда не должны заходить вообще // this._foreachRow(actionRow, actionCell); // if(null != actionCol) // this._foreachCol(actionCol, null); } }; Range.prototype._setPropertyNoEmpty=function(actionRow, actionCol, actionCell){ var nRangeType = this._getRangeType(); if(c_oRangeType.Range == nRangeType) return this._foreachNoEmpty(actionCell); else if(c_oRangeType.Row == nRangeType) return this._foreachRowNoEmpty(actionRow, actionCell); else if(c_oRangeType.Col == nRangeType) return this._foreachColNoEmpty(actionCol, actionCell); else { var oRes = this._foreachRowNoEmpty(actionRow, actionCell); if(null != oRes) return oRes; if(null != actionCol) oRes = this._foreachColNoEmpty(actionCol, null); return oRes; } }; Range.prototype.containCell=function(cellId){ var cellAddress = cellId; return cellAddress.getRow0() >= this.bbox.r1 && cellAddress.getCol0() >= this.bbox.c1 && cellAddress.getRow0() <= this.bbox.r2 && cellAddress.getCol0() <= this.bbox.c2; }; Range.prototype.containCell2=function(cell){ return cell.nRow >= this.bbox.r1 && cell.nCol >= this.bbox.c1 && cell.nRow <= this.bbox.r2 && cell.nCol <= this.bbox.c2; }; Range.prototype.cross = function(cellAddress){ if( cellAddress.getRow0() >= this.bbox.r1 && cellAddress.getRow0() <= this.bbox.r2 && this.bbox.c1 == this.bbox.c2) return {r:cellAddress.getRow()}; if( cellAddress.getCol0() >= this.bbox.c1 && cellAddress.getCol0() <= this.bbox.c2 && this.bbox.r1 == this.bbox.r2) return {c:cellAddress.getCol()}; return undefined; }; Range.prototype.getWorksheet=function(){ return this.worksheet; }; Range.prototype.isFormula = function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); return cell.isFormula(); }; Range.prototype.isOneCell=function(){ var oBBox = this.bbox; return oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2; }; Range.prototype.isColumn = function(){ if(this.first.getRow() == 1 && this.last.getRow() == AscCommon.gc_nMaxRow) return true; else return false; }; Range.prototype.isRow = function(){ if(this.first.getCol() == 1 && this.last.getCol() == AscCommon.gc_nMaxCol) return true; else return false; }; Range.prototype.getBBox=function(){ //1 - based return {r1: this.bbox.r1 + 1, r2: this.bbox.r2 + 1, c1: this.bbox.c1 + 1, c2: this.bbox.c2 + 1}; }; Range.prototype.getBBox0=function(){ //0 - based return this.bbox; }; Range.prototype.getName=function(){ return this.bbox.getName(); }; Range.prototype.getCells=function(){ var aResult = []; var oBBox = this.bbox; if(!((0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) || (0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2))) { for(var i = oBBox.r1; i <= oBBox.r2; i++){ for(var j = oBBox.c1; j <= oBBox.c2; j++){ aResult.push(this.worksheet._getCell(i, j)); } } } return aResult; }; Range.prototype.setValue=function(val,callback, isCopyPaste){ History.Create_NewPoint(); History.StartTransaction(); this._foreach(function(cell){ cell.setValue(val,callback, isCopyPaste); // if(cell.isEmpty()) // cell.Remove(); }); History.EndTransaction(); }; Range.prototype.setValue2=function(array){ History.Create_NewPoint(); History.StartTransaction(); //[{"text":"qwe","format":{"b":true, "i":false, "u":Asc.EUnderline.underlineNone, "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript" }},{}...] /* Устанавливаем значение в Range ячеек. В отличае от setValue, сюда мы попадаем только в случае ввода значения отличного от формулы. Таким образом, если в ячейке была формула, то для нее в графе очищается список ячеек от которых зависела. После чего выставляем флаг о необходимости пересчета. */ this._foreach(function(cell){ cell.setValue2(array); // if(cell.isEmpty()) // cell.Remove(); }); History.EndTransaction(); }; Range.prototype.setCellStyle=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setCellStyle(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setCellStyle(val); }, function(col){ col.setCellStyle(val); }, function(cell){ cell.setCellStyle(val); }); }; Range.prototype.setTableStyle=function(val){ this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType || null === val) { //this.worksheet.getAllCol().setCellStyle(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; //row.setCellStyle(val); }, function(col){ //col.setCellStyle(val); }, function(cell){ cell.setTableStyle(val); }); }; Range.prototype.setNumFormat=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setNumFormat(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setNumFormat(val); }, function(col){ col.setNumFormat(val); }, function(cell){ cell.setNumFormat(val); }); }; Range.prototype.shiftNumFormat=function(nShift, aDigitsCount){ History.Create_NewPoint(); var bRes = false; this._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){ bRes |= cell.shiftNumFormat(nShift, aDigitsCount[nCol0 - nColStart] || 8); }); return bRes; }; Range.prototype.setFont=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFont(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFont(val); }, function(col){ col.setFont(val); }, function(cell){ cell.setFont(val); }); }; Range.prototype.setFontname=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFontname(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFontname(val); }, function(col){ col.setFontname(val); }, function(cell){ cell.setFontname(val); }); }; Range.prototype.setFontsize=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFontsize(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFontsize(val); }, function(col){ col.setFontsize(val); }, function(cell){ cell.setFontsize(val); }); }; Range.prototype.setFontcolor=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFontcolor(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFontcolor(val); }, function(col){ col.setFontcolor(val); }, function(cell){ cell.setFontcolor(val); }); }; Range.prototype.setBold=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setBold(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setBold(val); }, function(col){ col.setBold(val); }, function(cell){ cell.setBold(val); }); }; Range.prototype.setItalic=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setItalic(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setItalic(val); }, function(col){ col.setItalic(val); }, function(cell){ cell.setItalic(val); }); }; Range.prototype.setUnderline=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setUnderline(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setUnderline(val); }, function(col){ col.setUnderline(val); }, function(cell){ cell.setUnderline(val); }); }; Range.prototype.setStrikeout=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setStrikeout(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setStrikeout(val); }, function(col){ col.setStrikeout(val); }, function(cell){ cell.setStrikeout(val); }); }; Range.prototype.setFontAlign=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFontAlign(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFontAlign(val); }, function(col){ col.setFontAlign(val); }, function(cell){ cell.setFontAlign(val); }); }; Range.prototype.setAlignVertical=function(val){ History.Create_NewPoint(); if("none" == val) val = null; this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setAlignVertical(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setAlignVertical(val); }, function(col){ col.setAlignVertical(val); }, function(cell){ cell.setAlignVertical(val); }); }; Range.prototype.setAlignHorizontal=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setAlignHorizontal(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setAlignHorizontal(val); }, function(col){ col.setAlignHorizontal(val); }, function(cell){ cell.setAlignHorizontal(val); }); }; Range.prototype.setFill=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setFill(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setFill(val); }, function(col){ col.setFill(val); }, function(cell){ cell.setFill(val); }); }; Range.prototype.setBorderSrc=function(border){ History.Create_NewPoint(); History.StartTransaction(); if (null == border) border = new Border(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setBorder(border.clone()); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setBorder(border.clone()); }, function(col){ col.setBorder(border.clone()); }, function(cell){ cell.setBorder(border.clone()); }); History.EndTransaction(); }; Range.prototype._setBorderMerge=function(bLeft, bTop, bRight, bBottom, oNewBorder, oCurBorder){ var oTargetBorder = new Border(); //не делаем clone для свойств потому у нас нельзя поменять свойство отдельное свойство border можно только применить border целиком if(bLeft) oTargetBorder.l = oNewBorder.l; else oTargetBorder.l = oNewBorder.iv; if(bTop) oTargetBorder.t = oNewBorder.t; else oTargetBorder.t = oNewBorder.ih; if(bRight) oTargetBorder.r = oNewBorder.r; else oTargetBorder.r = oNewBorder.iv; if(bBottom) oTargetBorder.b = oNewBorder.b; else oTargetBorder.b = oNewBorder.ih; oTargetBorder.d = oNewBorder.d; oTargetBorder.dd = oNewBorder.dd; oTargetBorder.du = oNewBorder.du; var oRes = null; if(null != oCurBorder) { oCurBorder.mergeInner(oTargetBorder); oRes = oCurBorder; } else oRes = oTargetBorder; return oRes; }; Range.prototype._setCellBorder=function(bbox, cell, oNewBorder){ if(null == oNewBorder) cell.setBorder(oNewBorder); else { var oCurBorder = null; if(null != cell.xfs && null != cell.xfs.border) oCurBorder = cell.xfs.border.clone(); else oCurBorder = g_oDefaultFormat.Border.clone(); var nRow = cell.nRow; var nCol = cell.nCol; cell.setBorder(this._setBorderMerge(nCol == bbox.c1, nRow == bbox.r1, nCol == bbox.c2, nRow == bbox.r2, oNewBorder, oCurBorder)); } }; Range.prototype._setRowColBorder=function(bbox, rowcol, bRow, oNewBorder){ if(null == oNewBorder) rowcol.setBorder(oNewBorder); else { var oCurBorder = null; if(null != rowcol.xfs && null != rowcol.xfs.border) oCurBorder = rowcol.xfs.border.clone(); var bLeft, bTop, bRight, bBottom = false; if(bRow) { bTop = rowcol.index == bbox.r1; bBottom = rowcol.index == bbox.r2; } else { bLeft = rowcol.index == bbox.c1; bRight = rowcol.index == bbox.c2; } rowcol.setBorder(this._setBorderMerge(bLeft, bTop, bRight, bBottom, oNewBorder, oCurBorder)); } }; Range.prototype._setBorderEdge=function(bbox, oItemWithXfs, nRow, nCol, oNewBorder){ var oCurBorder = null; if(null != oItemWithXfs.xfs && null != oItemWithXfs.xfs.border) oCurBorder = oItemWithXfs.xfs.border; if(null != oCurBorder) { var oCurBorderProp = null; if(nCol == bbox.c1 - 1) oCurBorderProp = oCurBorder.r; else if(nRow == bbox.r1 - 1) oCurBorderProp = oCurBorder.b; else if(nCol == bbox.c2 + 1) oCurBorderProp = oCurBorder.l; else if(nRow == bbox.r2 + 1) oCurBorderProp = oCurBorder.t; var oNewBorderProp = null; if(null == oNewBorder) oNewBorderProp = new AscCommonExcel.BorderProp(); else { if(nCol == bbox.c1 - 1) oNewBorderProp = oNewBorder.l; else if(nRow == bbox.r1 - 1) oNewBorderProp = oNewBorder.t; else if(nCol == bbox.c2 + 1) oNewBorderProp = oNewBorder.r; else if(nRow == bbox.r2 + 1) oNewBorderProp = oNewBorder.b; } if(null != oNewBorderProp && null != oCurBorderProp && c_oAscBorderStyles.None != oCurBorderProp.s && (null == oNewBorder || c_oAscBorderStyles.None != oNewBorderProp.s) && (oNewBorderProp.s != oCurBorderProp.s || oNewBorderProp.getRgbOrNull() != oCurBorderProp.getRgbOrNull())){ var oTargetBorder = oCurBorder.clone(); if(nCol == bbox.c1 - 1) oTargetBorder.r = new AscCommonExcel.BorderProp(); else if(nRow == bbox.r1 - 1) oTargetBorder.b = new AscCommonExcel.BorderProp(); else if(nCol == bbox.c2 + 1) oTargetBorder.l = new AscCommonExcel.BorderProp(); else if(nRow == bbox.r2 + 1) oTargetBorder.t = new AscCommonExcel.BorderProp(); oItemWithXfs.setBorder(oTargetBorder); } } }; Range.prototype.setBorder=function(border){ //border = null очисть border //"ih" - внутренние горизонтальные, "iv" - внутренние вертикальные History.Create_NewPoint(); var _this = this; var oBBox = this.bbox; this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { var oAllCol = this.worksheet.getAllCol(); _this._setRowColBorder(oBBox, oAllCol, false, border); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; _this._setRowColBorder(oBBox, row, true, border); }, function(col){ _this._setRowColBorder(oBBox, col, false, border); }, function(cell){ _this._setCellBorder(oBBox, cell, border); }); //убираем граничные border var aEdgeBorders = []; if(oBBox.c1 > 0 && (null == border || !border.l.isEmpty())) aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1, oBBox.c1 - 1, oBBox.r2, oBBox.c1 - 1)); if(oBBox.r1 > 0 && (null == border || !border.t.isEmpty())) aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1 - 1, oBBox.c1, oBBox.r1 - 1, oBBox.c2)); if(oBBox.c2 < gc_nMaxCol0 && (null == border || !border.r.isEmpty())) aEdgeBorders.push(this.worksheet.getRange3(oBBox.r1, oBBox.c2 + 1, oBBox.r2, oBBox.c2 + 1)); if(oBBox.r2 < gc_nMaxRow0 && (null == border || !border.b.isEmpty())) aEdgeBorders.push(this.worksheet.getRange3(oBBox.r2 + 1, oBBox.c1, oBBox.r2 + 1, oBBox.c2)); for(var i = 0, length = aEdgeBorders.length; i < length; i++) { var range = aEdgeBorders[i]; range._setPropertyNoEmpty(function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; _this._setBorderEdge(oBBox, row, row.index, 0, border); }, function(col){ _this._setBorderEdge(oBBox, col, 0, col.index, border); }, function(cell){ _this._setBorderEdge(oBBox, cell, cell.nRow, cell.nCol, border); }); } }; Range.prototype.setShrinkToFit=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setShrinkToFit(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setShrinkToFit(val); }, function(col){ col.setShrinkToFit(val); }, function(cell){ cell.setShrinkToFit(val); }); }; Range.prototype.setWrap=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setWrap(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setWrap(val); }, function(col){ col.setWrap(val); }, function(cell){ cell.setWrap(val); }); }; Range.prototype.setAngle=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setAngle(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setAngle(val); }, function(col){ col.setAngle(val); }, function(cell){ cell.setAngle(val); }); }; Range.prototype.setVerticalText=function(val){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { this.worksheet.getAllCol().setVerticalText(val); fSetProperty = this._setPropertyNoEmpty; } fSetProperty.call(this, function(row){ if(c_oRangeType.All == nRangeType && null == row.xfs) return; row.setVerticalText(val); }, function(col){ col.setVerticalText(val); }, function(cell){ cell.setVerticalText(val); }); }; Range.prototype.setType=function(type){ History.Create_NewPoint(); this.createCellOnRowColCross(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) fSetProperty = this._setPropertyNoEmpty; fSetProperty.call(this, null, null, function(cell){ cell.setType(type); }); }; Range.prototype.getType=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); if(null != cell) return cell.getType(); else return null; }; Range.prototype.isEmptyText=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); return (null != cell) ? cell.isEmptyText() : true; }; Range.prototype.isEmptyTextString=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); return (null != cell) ? cell.isEmptyTextString() : true; }; Range.prototype.isFormula=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); return (null != cell) ? cell.isFormula() : false; }; Range.prototype.getFormula=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); if(null != cell) return cell.getFormula(); else return ""; }; Range.prototype.getValueForEdit=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); if(null != cell) { var numFormat = this.getNumFormat(); return cell.getValueForEdit(numFormat); } else return ""; }; Range.prototype.getValueForEdit2=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); if(null != cell) { var numFormat = this.getNumFormat(); return cell.getValueForEdit2(numFormat); } else { var oRow = this.worksheet._getRowNoEmpty(this.bbox.r1); var oCol = this.worksheet._getColNoEmptyWithAll(this.bbox.c1); var xfs = null; if(null != oRow && null != oRow.xfs) xfs = oRow.xfs.clone(); else if(null != oCol && null != oCol.xfs) xfs = oCol.xfs.clone(); var oTempCell = new Cell(this.worksheet); oTempCell.create(xfs, this.bbox.r1, this.bbox.c1); return oTempCell.getValueForEdit2(); } }; Range.prototype.getValueWithoutFormat=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1); if(null != cell) return cell.getValueWithoutFormat(); else return ""; }; Range.prototype.getValue=function(){ return this.getValueWithoutFormat(); }; Range.prototype.getValueWithFormat=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1); if(null != cell) return cell.getValue(); else return ""; }; Range.prototype.getValue2=function(dDigitsCount, fIsFitMeasurer){ //[{"text":"qwe","format":{"b":true, "i":false, "u":Asc.EUnderline.underlineNone, "s":false, "fn":"Arial", "fs": 12, "c": 0xff00ff, "va": "subscript" }},{}...] var cell = this.worksheet._getCellNoEmpty(this.bbox.r1, this.bbox.c1); if(null != cell) return cell.getValue2(dDigitsCount, fIsFitMeasurer); else { var oRow = this.worksheet._getRowNoEmpty(this.bbox.r1); var oCol = this.worksheet._getColNoEmptyWithAll(this.bbox.c1); var xfs = null; if(null != oRow && null != oRow.xfs) xfs = oRow.xfs.clone(); else if(null != oCol && null != oCol.xfs) xfs = oCol.xfs.clone(); var oTempCell = new Cell(this.worksheet); oTempCell.create(xfs, this.bbox.r1, this.bbox.c1); return oTempCell.getValue2(dDigitsCount, fIsFitMeasurer); } }; Range.prototype.getXfId=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.XfId) return xfs.XfId; } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.XfId) return row.xfs.XfId; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.XfId) return col.xfs.XfId; } return g_oDefaultFormat.XfId; }; Range.prototype.getStyleName=function(){ var res = this.worksheet.workbook.CellStyles.getStyleNameByXfId(this.getXfId()); // ToDo убрать эту заглушку (нужно делать на открытии) в InitStyleManager return res || this.worksheet.workbook.CellStyles.getStyleNameByXfId(g_oDefaultFormat.XfId); }; Range.prototype.getTableStyle=function(){ var cell = this.worksheet._getCellNoEmpty(this.bbox.r1,this.bbox.c1); return cell ? cell.getTableStyle() : null; }; Range.prototype.getNumFormat=function(){ return oNumFormatCache.get(this.getNumFormatStr()); }; Range.prototype.getNumFormatStr=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.num) return xfs.num.getFormat(); } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.num) return row.xfs.num.getFormat(); var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.num) return col.xfs.num.getFormat(); } return g_oDefaultFormat.Num.getFormat(); }; Range.prototype.getNumFormatType=function(){ return this.getNumFormat().getType(); }; // Узнаем отличается ли шрифт (размер и гарнитура) в ячейке от шрифта в строке Range.prototype.isNotDefaultFont = function () { // Получаем фонт ячейки var cellFont = this.getFont(); var rowFont = g_oDefaultFormat.Font; var row = this.worksheet._getRowNoEmpty(this.bbox.r1); if (null != row && null != row.xfs && null != row.xfs.font) rowFont = row.xfs.font; else if (null != this.oAllCol) rowFont = this.oAllCol; return (cellFont.fn !== rowFont.fn || cellFont.fs !== rowFont.fs); }; Range.prototype.getFont = function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.font) return xfs.font; } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.font) return row.xfs.font; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.font) return col.xfs.font; } return g_oDefaultFormat.Font; }; Range.prototype.getFontname=function(){ return this.getFont().fn; }; Range.prototype.getFontsize=function(){ return this.getFont().fs; }; Range.prototype.getFontcolor=function(){ return this.getFont().c; }; Range.prototype.getBold=function(){ return this.getFont().b; }; Range.prototype.getItalic=function(){ return this.getFont().i; }; Range.prototype.getUnderline=function(){ return this.getFont().u; }; Range.prototype.getStrikeout=function(){ return this.getFont().s; }; Range.prototype.getFontAlign=function(){ return this.getFont().va; }; Range.prototype.getQuotePrefix=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.QuotePrefix) return xfs.QuotePrefix; } return false; }; Range.prototype.getAlignVertical=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return xfs.align.ver; else return g_oDefaultFormat.AlignAbs.ver; } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return row.xfs.align.ver; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return col.xfs.align.ver; } return g_oDefaultFormat.Align.ver; }; Range.prototype.getAlignHorizontal=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return xfs.align.hor; else return g_oDefaultFormat.AlignAbs.hor; } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return row.xfs.align.hor; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return col.xfs.align.hor; } return g_oDefaultFormat.Align.hor; }; Range.prototype.getAlignHorizontalByValue=function(){ //возвращает Align в зависимости от значния в ячейке //values: none, center, justify, left , right, null var align = this.getAlignHorizontal(); if("none" == align){ //пытаемся определить по значению var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(cell){ switch(cell.getType()){ case CellValueType.String:align = "left";break; case CellValueType.Bool: case CellValueType.Error:align = "center";break; default: //Если есть value и не проставлен тип значит это число, у всех остальных типов значение не null if(this.getValueWithoutFormat()) { //смотрим var oNumFmt = this.getNumFormat(); if(true == oNumFmt.isTextFormat()) align = "left"; else align = "right"; } else align = "left"; break; } } if("none" == align) align = "left"; } return align; }; Range.prototype.getFill=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.fill) return xfs.fill.bg; } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.fill) return row.xfs.fill.bg; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.fill) return col.xfs.fill.bg; } return g_oDefaultFormat.Fill.bg; }; Range.prototype.getBorderSrc=function(_cell){ //Возвращает как записано в файле, не проверяя бордеры соседних ячеек //формат //\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false } //"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot //"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell //"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell if(null == _cell) _cell = this.getFirst(); var nRow = _cell.getRow0(); var nCol = _cell.getCol0(); var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs && null != xfs.border) return xfs.border; } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.border) return row.xfs.border; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.border) return col.xfs.border; } return g_oDefaultFormat.Border; }; Range.prototype.getBorder=function(_cell){ //_cell - optional //Возвращает как записано в файле, не проверяя бордеры соседних ячеек //формат //\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false } //"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot //"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell //"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell var oRes = this.getBorderSrc(_cell); if(null != oRes) return oRes; else return g_oDefaultFormat.Border; }; Range.prototype.getBorderFull=function(){ //Возвращает как excel, т.е. проверяет бордеры соседних ячеек // //\{"l": {"s": "solid", "c": 0xff0000}, "t": {} ,"r": {} ,"b": {} ,"d": {},"dd": false ,"du": false } //"s" values: none, thick, thin, medium, dashDot, dashDotDot, dashed, dotted, double, hair, mediumDashDot, mediumDashDotDot, mediumDashed, slantDashDot // //"dd" diagonal line, starting at the top left corner of the cell and moving down to the bottom right corner of the cell //"du" diagonal line, starting at the bottom left corner of the cell and moving up to the top right corner of the cell var borders = this.getBorder(this.getFirst()).clone(); var nRow = this.bbox.r1; var nCol = this.bbox.c1; if(c_oAscBorderStyles.None === borders.l.s){ if(nCol > 1){ var left = this.getBorder(new CellAddress(nRow, nCol - 1, 0)); if(c_oAscBorderStyles.None !== left.r.s) borders.l = left.r; } } if(c_oAscBorderStyles.None === borders.t.s){ if(nRow > 1){ var top = this.getBorder(new CellAddress(nRow - 1, nCol, 0)); if(c_oAscBorderStyles.None !== top.b.s) borders.t = top.b; } } if(c_oAscBorderStyles.None === borders.r.s){ var right = this.getBorder(new CellAddress(nRow, nCol + 1, 0)); if(c_oAscBorderStyles.None !== right.l.s) borders.r = right.l; } if(c_oAscBorderStyles.None === borders.b.s){ var bottom = this.getBorder(new CellAddress(nRow + 1, nCol, 0)); if(c_oAscBorderStyles.None !== bottom.t.s) borders.b = bottom.t; } return borders; }; Range.prototype.getShrinkToFit=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return xfs.align.shrink; else return g_oDefaultFormat.AlignAbs.shrink; } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return row.xfs.align.shrink; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return col.xfs.align.shrink; } return g_oDefaultFormat.Align.shrink; }; Range.prototype.getWrapByAlign = function (align) { // Для justify wrap всегда true return "justify" === align.hor ? true : align.wrap; }; Range.prototype.getWrap=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return this.getWrapByAlign(xfs.align); else return this.getWrapByAlign(g_oDefaultFormat.AlignAbs); } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return this.getWrapByAlign(row.xfs.align); var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return this.getWrapByAlign(col.xfs.align); } return this.getWrapByAlign(g_oDefaultFormat.Align); }; Range.prototype.getAngle=function(){ //угол от -90 до 90 против часовой стрелки от оси OX var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return angleFormatToInterface(xfs.align.angle); else return angleFormatToInterface(g_oDefaultFormat.AlignAbs.angle); } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return angleFormatToInterface(row.xfs.align.angle); var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return angleFormatToInterface(col.xfs.align.angle); } return angleFormatToInterface(g_oDefaultFormat.Align.angle); }; Range.prototype.getVerticalText=function(){ var nRow = this.bbox.r1; var nCol = this.bbox.c1; var cell = this.worksheet._getCellNoEmpty(nRow, nCol); if(null != cell) { var xfs = cell.getCompiledStyle(); if(null != xfs) { if(null != xfs.align) return g_nVerticalTextAngle == xfs.align.angle; else return g_nVerticalTextAngle == g_oDefaultFormat.AlignAbs.angle; } } else { //стили столбов и колонок var row = this.worksheet._getRowNoEmpty(nRow); if(null != row && null != row.xfs && null != row.xfs.align) return g_nVerticalTextAngle == row.xfs.align.angle; var col = this.worksheet._getColNoEmptyWithAll(nCol); if(null != col && null != col.xfs && null != col.xfs.align) return g_nVerticalTextAngle == col.xfs.align.angle; } return g_nVerticalTextAngle == g_oDefaultFormat.Align.angle; }; Range.prototype.hasMerged=function(){ var aMerged = this.worksheet.mergeManager.get(this.bbox); if(aMerged.all.length > 0) return aMerged.all[0].bbox; return null; }; Range.prototype.mergeOpen=function(){ this.worksheet.mergeManager.add(this.bbox, 1); }; Range.prototype.merge=function(type){ if(null == type) type = Asc.c_oAscMergeOptions.Merge; var oBBox = this.bbox; History.Create_NewPoint(); History.StartTransaction(); if(oBBox.r1 == oBBox.r2 && oBBox.c1 == oBBox.c2){ if(type == Asc.c_oAscMergeOptions.MergeCenter) this.setAlignHorizontal("center"); History.EndTransaction(); return; } if(this.hasMerged()) { this.unmerge(); if(type == Asc.c_oAscMergeOptions.MergeCenter) { //сбрасываем AlignHorizontal this.setAlignHorizontal("none"); History.EndTransaction(); return; } } //пробегаемся по границе диапазона, чтобы посмотреть какие границы нужно оставлять var oLeftBorder = null; var oTopBorder = null; var oRightBorder = null; var oBottomBorder = null; var nRangeType = this._getRangeType(oBBox); if(c_oRangeType.Range == nRangeType) { var oThis = this; var fGetBorder = function(bRow, v1, v2, v3, type) { var oRes = null; for(var i = v1; i <= v2; ++i) { var bNeedDelete = true; var oCurCell; if(bRow) oCurCell = oThis.worksheet._getCellNoEmpty(v3, i); else oCurCell = oThis.worksheet._getCellNoEmpty(i, v3); if(null != oCurCell && null != oCurCell.xfs && null != oCurCell.xfs.border) { var border = oCurCell.xfs.border; var oBorderProp; switch(type) { case 1: oBorderProp = border.l;break; case 2: oBorderProp = border.t;break; case 3: oBorderProp = border.r;break; case 4: oBorderProp = border.b;break; } if(false == oBorderProp.isEmpty()) { if(null == oRes) { oRes = oBorderProp; bNeedDelete = false; } else if(true == oRes.isEqual(oBorderProp)) bNeedDelete = false; } } if(bNeedDelete) { oRes = null; break; } } return oRes; }; oLeftBorder = fGetBorder(false, oBBox.r1, oBBox.r2, oBBox.c1, 1); oTopBorder = fGetBorder(true, oBBox.c1, oBBox.c2, oBBox.r1, 2); oRightBorder = fGetBorder(false, oBBox.r1, oBBox.r2, oBBox.c2, 3); oBottomBorder = fGetBorder(true, oBBox.c1, oBBox.c2, oBBox.r2, 4); } else if(c_oRangeType.Row == nRangeType) { var oTopRow = this.worksheet._getRowNoEmpty(oBBox.r1); if(null != oTopRow && null != oTopRow.xfs && null != oTopRow.xfs.border && false == oTopRow.xfs.border.t.isEmpty()) oTopBorder = oTopRow.xfs.border.t; if(oBBox.r1 != oBBox.r2) { var oBottomRow = this.worksheet._getRowNoEmpty(oBBox.r2); if(null != oBottomRow && null != oBottomRow.xfs && null != oBottomRow.xfs.border && false == oBottomRow.xfs.border.b.isEmpty()) oBottomBorder = oBottomRow.xfs.border.b; } } else { var oLeftCol = this.worksheet._getColNoEmptyWithAll(oBBox.c1); if(null != oLeftCol && null != oLeftCol.xfs && null != oLeftCol.xfs.border && false == oLeftCol.xfs.border.l.isEmpty()) oLeftBorder = oLeftCol.xfs.border.l; if(oBBox.c1 != oBBox.c2) { var oRightCol = this.worksheet._getColNoEmptyWithAll(oBBox.c2); if(null != oRightCol && null != oRightCol.xfs && null != oRightCol.xfs.border && false == oRightCol.xfs.border.r.isEmpty()) oRightBorder = oRightCol.xfs.border.r; } } var bFirst = true; var oLeftTopCellStyle = null; var oFirstCellStyle = null; var oFirstCellValue = null; var oFirstCellRow = null; var oFirstCellCol = null; var oFirstCellHyperlink = null; this._setPropertyNoEmpty(null,null, function(cell, nRow0, nCol0, nRowStart, nColStart){ if(bFirst && false == cell.isEmptyText()) { bFirst = false; oFirstCellStyle = cell.getStyle(); oFirstCellValue = cell.getValueData(); oFirstCellRow = cell.nRow; oFirstCellCol = cell.nCol; } if(nRow0 == nRowStart && nCol0 == nColStart) oLeftTopCellStyle = cell.getStyle(); }); //правила работы с гиперссылками во время merge(отличются от Excel в случаем областей, например hyperlink: C3:D3 мержим C2:C3) // 1)оставляем все ссылки, которые не полностью лежат в merge области // 2)оставляем многоклеточные ссылки, top граница которых совпадает с top границей merge области, а высота merge > 1 или совпадает с высотой области merge // 3)оставляем и переносим в первую ячейку одну одноклеточную ссылку, если она находится в первой ячейке с данными var aHyperlinks = this.worksheet.hyperlinkManager.get(oBBox); var aHyperlinksToRestore = []; for(var i = 0, length = aHyperlinks.inner.length; i < length; i++) { var elem = aHyperlinks.inner[i]; if(oFirstCellRow == elem.bbox.r1 && oFirstCellCol == elem.bbox.c1 && elem.bbox.r1 == elem.bbox.r2 && elem.bbox.c1 == elem.bbox.c2) { var oNewHyperlink = elem.data.clone(); oNewHyperlink.Ref.setOffset({offsetCol:oBBox.c1 - oFirstCellCol, offsetRow:oBBox.r1 - oFirstCellRow}); aHyperlinksToRestore.push(oNewHyperlink); } else if( oBBox.r1 == elem.bbox.r1 && (elem.bbox.r1 != elem.bbox.r2 || (elem.bbox.c1 != elem.bbox.c2 && oBBox.r1 == oBBox.r2))) aHyperlinksToRestore.push(elem.data); } this.cleanAll(); //восстанавливаем hyperlink for(var i = 0, length = aHyperlinksToRestore.length; i < length; i++) { var elem = aHyperlinksToRestore[i]; this.worksheet.hyperlinkManager.add(elem.Ref.getBBox0(), elem); } var oTargetStyle = null; if(null != oFirstCellValue && null != oFirstCellRow && null != oFirstCellCol) { if(null != oFirstCellStyle) oTargetStyle = oFirstCellStyle.clone(); var oLeftTopCell = this.worksheet._getCell(oBBox.r1, oBBox.c1); oLeftTopCell.setValueData(oFirstCellValue); if(null != oFirstCellHyperlink) { var oLeftTopRange = this.worksheet.getCell3(oBBox.r1, oBBox.c1); oLeftTopRange.setHyperlink(oFirstCellHyperlink, true); } } else if(null != oLeftTopCellStyle) oTargetStyle = oLeftTopCellStyle.clone(); //убираем бордеры if(null != oTargetStyle) { if(null != oTargetStyle.border) oTargetStyle.border = null; } else if(null != oLeftBorder || null != oTopBorder || null != oRightBorder || null != oBottomBorder) oTargetStyle = new AscCommonExcel.CellXfs(); var fSetProperty = this._setProperty; var nRangeType = this._getRangeType(); if(c_oRangeType.All == nRangeType) { fSetProperty = this._setPropertyNoEmpty; oTargetStyle = null } fSetProperty.call(this, function(row){ if(null == oTargetStyle) row.setStyle(null); else { var oNewStyle = oTargetStyle.clone(); if(row.index == oBBox.r1 && null != oTopBorder) { oNewStyle.border = new Border(); oNewStyle.border.t = oTopBorder.clone(); } else if(row.index == oBBox.r2 && null != oBottomBorder) { oNewStyle.border = new Border(); oNewStyle.border.b = oBottomBorder.clone(); } row.setStyle(oNewStyle); } },function(col){ if(null == oTargetStyle) col.setStyle(null); else { var oNewStyle = oTargetStyle.clone(); if(col.index == oBBox.c1 && null != oLeftBorder) { oNewStyle.border = new Border(); oNewStyle.border.l = oLeftBorder.clone(); } else if(col.index == oBBox.c2 && null != oRightBorder) { oNewStyle.border = new Border(); oNewStyle.border.r = oRightBorder.clone(); } col.setStyle(oNewStyle); } }, function(cell, nRow, nCol, nRowStart, nColStart){ //важно установить именно здесь, чтобы ячейка не удалилась после применения стилей. if(null == oTargetStyle) cell.setStyle(null); else { var oNewStyle = oTargetStyle.clone(); if(oBBox.r1 == nRow && oBBox.c1 == nCol) { if(null != oLeftBorder || null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder) || (oBBox.c1 == oBBox.c2 && null != oRightBorder)) { oNewStyle.border = new Border(); if(null != oLeftBorder) oNewStyle.border.l = oLeftBorder.clone(); if(null != oTopBorder) oNewStyle.border.t = oTopBorder.clone(); if(oBBox.r1 == oBBox.r2 && null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); if(oBBox.c1 == oBBox.c2 && null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); } } else if(oBBox.r1 == nRow && oBBox.c2 == nCol) { if(null != oRightBorder || null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder)) { oNewStyle.border = new Border(); if(null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); if(null != oTopBorder) oNewStyle.border.t = oTopBorder.clone(); if(oBBox.r1 == oBBox.r2 && null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); } } else if(oBBox.r2 == nRow && oBBox.c1 == nCol) { if(null != oLeftBorder || null != oBottomBorder || (oBBox.c1 == oBBox.c2 && null != oRightBorder)) { oNewStyle.border = new Border(); if(null != oLeftBorder) oNewStyle.border.l = oLeftBorder.clone(); if(null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); if(oBBox.c1 == oBBox.c2 && null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); } } else if(oBBox.r2 == nRow && oBBox.c2 == nCol) { if(null != oRightBorder || null != oBottomBorder) { oNewStyle.border = new Border(); if(null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); if(null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); } } else if(oBBox.r1 == nRow) { if(null != oTopBorder || (oBBox.r1 == oBBox.r2 && null != oBottomBorder)) { oNewStyle.border = new Border(); if(null != oTopBorder) oNewStyle.border.t = oTopBorder.clone(); if(oBBox.r1 == oBBox.r2 && null != oBottomBorder) oNewStyle.border.b = oBottomBorder.clone(); } } else if(oBBox.r2 == nRow) { if(null != oBottomBorder) { oNewStyle.border = new Border(); oNewStyle.border.b = oBottomBorder.clone(); } } else if(oBBox.c1 == nCol) { if(null != oLeftBorder || (oBBox.c1 == oBBox.c2 && null != oRightBorder)) { oNewStyle.border = new Border(); if(null != oLeftBorder) oNewStyle.border.l = oLeftBorder.clone(); if(oBBox.c1 == oBBox.c2 && null != oRightBorder) oNewStyle.border.r = oRightBorder.clone(); } } else if(oBBox.c2 == nCol) { if(null != oRightBorder) { oNewStyle.border = new Border(); oNewStyle.border.r = oRightBorder.clone(); } } cell.setStyle(oNewStyle); } }); if(type == Asc.c_oAscMergeOptions.MergeCenter) this.setAlignHorizontal("center"); if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) this.worksheet.mergeManager.add(this.bbox, 1); History.EndTransaction(); }; Range.prototype.unmerge=function(bOnlyInRange){ History.Create_NewPoint(); History.StartTransaction(); if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) this.worksheet.mergeManager.remove(this.bbox); History.EndTransaction(); }; Range.prototype._getHyperlinks=function(){ var nRangeType = this._getRangeType(); var result = []; var oThis = this; if(c_oRangeType.Range == nRangeType) { var oTempRows = {}; var fAddToTempRows = function(oTempRows, bbox, data){ if(null != bbox) { for(var i = bbox.r1; i <= bbox.r2; i++) { var row = oTempRows[i]; if(null == row) { row = {}; oTempRows[i] = row; } for(var j = bbox.c1; j <= bbox.c2; j++) { var cell = row[j]; if(null == cell) row[j] = data; } } } }; //todo возможно надо сделать оптимизацию для скрытых строк var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(var i = 0, length = aHyperlinks.all.length; i < length; i++) { var hyp = aHyperlinks.all[i]; var hypBBox = hyp.bbox.intersectionSimple(this.bbox); fAddToTempRows(oTempRows, hypBBox, hyp.data); //расширяем гиперссылки на merge ячейках var aMerged = this.worksheet.mergeManager.get(hyp.bbox); for(var j = 0, length2 = aMerged.all.length; j < length2; j++) { var merge = aMerged.all[j]; var mergeBBox = merge.bbox.intersectionSimple(this.bbox); fAddToTempRows(oTempRows, mergeBBox, hyp.data); } } //формируем результат for(var i in oTempRows) { var nRowIndex = i - 0; var row = oTempRows[i]; for(var j in row) { var nColIndex = j - 0; var oCurHyp = row[j]; result.push({hyperlink: oCurHyp, col: nColIndex, row: nRowIndex}); } } } return result; }; Range.prototype.getHyperlink=function(){ var aHyperlinks = this._getHyperlinks(); if(null != aHyperlinks && aHyperlinks.length > 0) return aHyperlinks[0].hyperlink; return null; }; Range.prototype.getHyperlinks=function(){ return this._getHyperlinks(); }; Range.prototype.setHyperlinkOpen=function(val){ if(null != val && false == val.isValid()) return; this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val); }; Range.prototype.setHyperlink=function(val, bWithoutStyle){ if(null != val && false == val.isValid()) return; //проверяем, может эта ссылка уже существует var i, length, hyp; var bExist = false; var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(i = 0, length = aHyperlinks.all.length; i < length; i++) { hyp = aHyperlinks.all[i]; if(hyp.data.isEqual(val)) { bExist = true; break; } } if(false == bExist) { History.Create_NewPoint(); History.StartTransaction(); if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) { //удаляем ссылки с тем же адресом for(i = 0, length = aHyperlinks.all.length; i < length; i++) { hyp = aHyperlinks.all[i]; if(hyp.bbox.isEqual(this.bbox)) this.worksheet.hyperlinkManager.removeElement(hyp); } } //todo перейти на CellStyle if(true != bWithoutStyle) { var oHyperlinkFont = new AscCommonExcel.Font(); oHyperlinkFont.fn = this.worksheet.workbook.getDefaultFont(); oHyperlinkFont.fs = this.worksheet.workbook.getDefaultSize(); oHyperlinkFont.u = Asc.EUnderline.underlineSingle; oHyperlinkFont.c = AscCommonExcel.g_oColorManager.getThemeColor(AscCommonExcel.g_nColorHyperlink); this.setFont(oHyperlinkFont); } if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) this.worksheet.hyperlinkManager.add(val.Ref.getBBox0(), val); History.EndTransaction(); } }; Range.prototype.removeHyperlink = function (val, removeStyle) { var bbox = this.bbox; var elem = null; if(null != val) { bbox = val.Ref.getBBox0(); elem = new RangeDataManagerElem(bbox, val); } if(false == this.worksheet.workbook.bUndoChanges && false == this.worksheet.workbook.bRedoChanges) { History.Create_NewPoint(); History.StartTransaction(); var oChangeParam = { removeStyle: removeStyle }; if(null != elem) this.worksheet.hyperlinkManager.removeElement(elem, oChangeParam); else this.worksheet.hyperlinkManager.remove(bbox, !bbox.isOneCell(), oChangeParam); History.EndTransaction(); } }; Range.prototype.deleteCellsShiftUp=function(preDeleteAction){ return this._shiftUpDown(true, preDeleteAction); }; Range.prototype.addCellsShiftBottom=function(displayNameFormatTable){ return this._shiftUpDown(false, null, displayNameFormatTable); }; Range.prototype.addCellsShiftRight=function(displayNameFormatTable){ return this._shiftLeftRight(false, null,displayNameFormatTable); }; Range.prototype.deleteCellsShiftLeft=function(preDeleteAction){ return this._shiftLeftRight(true, preDeleteAction); }; Range.prototype._canShiftLeftRight=function(bLeft){ var aColsToDelete = [], aCellsToDelete = []; var oBBox = this.bbox; var nRangeType = this._getRangeType(oBBox); if(c_oRangeType.Range != nRangeType && c_oRangeType.Col != nRangeType) return null; var nWidth = oBBox.c2 - oBBox.c1 + 1; if(!bLeft && !this.worksheet.workbook.bUndoChanges && !this.worksheet.workbook.bRedoChanges){ var rangeEdge = this.worksheet.getRange3(oBBox.r1, gc_nMaxCol0 - nWidth + 1, oBBox.r2, gc_nMaxCol0); var aMerged = this.worksheet.mergeManager.get(rangeEdge.bbox); if(aMerged.all.length > 0) return null; var aHyperlink = this.worksheet.hyperlinkManager.get(rangeEdge.bbox); if(aHyperlink.all.length > 0) return null; var bError = rangeEdge._setPropertyNoEmpty(null, function(col){ if(null != col){ if(null != col && null != col.xfs && null != col.xfs.fill && null != col.xfs.fill.getRgbOrNull()) return true; aColsToDelete.push(col); } }, function(cell){ if(null != cell){ if(null != cell.xfs && null != cell.xfs.fill && null != cell.xfs.fill.getRgbOrNull()) return true; if(!cell.isEmptyText()) return true; aCellsToDelete.push(cell); } }); if(bError) return null; } return {aColsToDelete: aColsToDelete, aCellsToDelete: aCellsToDelete}; }; Range.prototype._shiftLeftRight=function(bLeft, preDeleteAction, displayNameFormatTable){ var canShiftRes = this._canShiftLeftRight(bLeft); if(null === canShiftRes) return false; if (preDeleteAction) preDeleteAction(); //удаляем крайние колонки и ячейки var i, length, colIndex; for(i = 0, length = canShiftRes.aColsToDelete.length; i < length; ++i){ colIndex = canShiftRes.aColsToDelete[i].index; this.worksheet._removeCols(colIndex, colIndex); } for(i = 0, length = canShiftRes.aCellsToDelete.length; i < length; ++i) this.worksheet._removeCell(null, null, canShiftRes.aCellsToDelete[i]); var oBBox = this.bbox; var nWidth = oBBox.c2 - oBBox.c1 + 1; var nRangeType = this._getRangeType(oBBox); var mergeManager = this.worksheet.mergeManager; this.worksheet.workbook.lockDraw(); //todo вставить предупреждение, что будет unmerge History.Create_NewPoint(); History.StartTransaction(); var oShiftGet = null; if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; oShiftGet = mergeManager.shiftGet(this.bbox, true); var aMerged = oShiftGet.elems; if(null != aMerged.outer && aMerged.outer.length > 0) { var bChanged = false; for(i = 0, length = aMerged.outer.length; i < length; i++) { var elem = aMerged.outer[i]; if(!(elem.bbox.c1 < oShiftGet.bbox.c1 && oShiftGet.bbox.r1 <= elem.bbox.r1 && elem.bbox.r2 <= oShiftGet.bbox.r2)) { mergeManager.removeElement(elem); bChanged = true; } } if(bChanged) oShiftGet = null; } History.LocalChange = false; } //сдвигаем ячейки if(bLeft) { if(c_oRangeType.Range == nRangeType) this.worksheet._shiftCellsLeft(oBBox); else this.worksheet._removeCols(oBBox.c1, oBBox.c2); } else { if(c_oRangeType.Range == nRangeType) this.worksheet._shiftCellsRight(oBBox, displayNameFormatTable); else this.worksheet._insertColsBefore(oBBox.c1, nWidth); } if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; mergeManager.shift(this.bbox, !bLeft, true, oShiftGet); this.worksheet.hyperlinkManager.shift(this.bbox, !bLeft, true); History.LocalChange = false; } History.EndTransaction(); this.worksheet.workbook.unLockDraw(); this.worksheet.workbook.buildRecalc(); return true; }; Range.prototype._canShiftUpDown=function(bUp){ var aRowsToDelete = [], aCellsToDelete = []; var oBBox = this.bbox; var nRangeType = this._getRangeType(oBBox); if(c_oRangeType.Range != nRangeType && c_oRangeType.Row != nRangeType) return null; var nHeight = oBBox.r2 - oBBox.r1 + 1; if(!bUp && !this.worksheet.workbook.bUndoChanges && !this.worksheet.workbook.bRedoChanges){ var rangeEdge = this.worksheet.getRange3(gc_nMaxRow0 - nHeight + 1, oBBox.c1, gc_nMaxRow0, oBBox.c2); var aMerged = this.worksheet.mergeManager.get(rangeEdge.bbox); if(aMerged.all.length > 0) return null; var aHyperlink = this.worksheet.hyperlinkManager.get(rangeEdge.bbox); if(aHyperlink.all.length > 0) return null; var bError = rangeEdge._setPropertyNoEmpty(function(row){ if(null != row){ if(null != row.xfs && null != row.xfs.fill && null != row.xfs.fill.getRgbOrNull()) return true; aRowsToDelete.push(row); } }, null, function(cell){ if(null != cell){ if(null != cell.xfs && null != cell.xfs.fill && null != cell.xfs.fill.getRgbOrNull()) return true; if(!cell.isEmptyText()) return true; aCellsToDelete.push(cell); } }); if(bError) return null; } return {aRowsToDelete: aRowsToDelete, aCellsToDelete: aCellsToDelete}; }; Range.prototype._shiftUpDown = function (bUp, preDeleteAction, displayNameFormatTable) { var canShiftRes = this._canShiftUpDown(bUp); if(null === canShiftRes) return false; if (preDeleteAction) preDeleteAction(); //удаляем крайние колонки и ячейки var i, length, rowIndex; for(i = 0, length = canShiftRes.aRowsToDelete.length; i < length; ++i){ rowIndex = canShiftRes.aRowsToDelete[i].index; this.worksheet._removeRows(rowIndex, rowIndex); } for(i = 0, length = canShiftRes.aCellsToDelete.length; i < length; ++i) this.worksheet._removeCell(null, null, canShiftRes.aCellsToDelete[i]); var oBBox = this.bbox; var nHeight = oBBox.r2 - oBBox.r1 + 1; var nRangeType = this._getRangeType(oBBox); var mergeManager = this.worksheet.mergeManager; this.worksheet.workbook.lockDraw(); //todo вставить предупреждение, что будет unmerge History.Create_NewPoint(); History.StartTransaction(); var oShiftGet = null; if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; oShiftGet = mergeManager.shiftGet(this.bbox, false); var aMerged = oShiftGet.elems; if(null != aMerged.outer && aMerged.outer.length > 0) { var bChanged = false; for(i = 0, length = aMerged.outer.length; i < length; i++) { var elem = aMerged.outer[i]; if(!(elem.bbox.r1 < oShiftGet.bbox.r1 && oShiftGet.bbox.c1 <= elem.bbox.c1 && elem.bbox.c2 <= oShiftGet.bbox.c2)) { mergeManager.removeElement(elem); bChanged = true; } } if(bChanged) oShiftGet = null; } History.LocalChange = false; } //сдвигаем ячейки if(bUp) { if(c_oRangeType.Range == nRangeType) this.worksheet._shiftCellsUp(oBBox); else this.worksheet._removeRows(oBBox.r1, oBBox.r2); } else { if(c_oRangeType.Range == nRangeType) this.worksheet._shiftCellsBottom(oBBox, displayNameFormatTable); else this.worksheet._insertRowsBefore(oBBox.r1, nHeight); } if (false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; mergeManager.shift(this.bbox, !bUp, false, oShiftGet); this.worksheet.hyperlinkManager.shift(this.bbox, !bUp, false); History.LocalChange = false; } History.EndTransaction(); this.worksheet.workbook.unLockDraw(); this.worksheet.workbook.buildRecalc(); return true; }; Range.prototype.setOffset=function(offset){//offset = {offsetCol:intNumber, offsetRow:intNumber} this.bbox.c1 += offset.offsetCol; if( this.bbox.c1 < 0 ) this.bbox.c1 = 0; this.bbox.r1 += offset.offsetRow; if( this.bbox.r1 < 0 ) this.bbox.r1 = 0; this.bbox.c2 += offset.offsetCol; if( this.bbox.c2 < 0 ) this.bbox.c2 = 0; this.bbox.r2 += offset.offsetRow; if( this.bbox.r2 < 0 ) this.bbox.r2 = 0; this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0); this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0); }; Range.prototype.setOffsetFirst=function(offset){//offset = {offsetCol:intNumber, offsetRow:intNumber} this.bbox.c1 += offset.offsetCol; if( this.bbox.c1 < 0 ) this.bbox.c1 = 0; this.bbox.r1 += offset.offsetRow; if( this.bbox.r1 < 0 ) this.bbox.r1 = 0; this.first = new CellAddress(this.bbox.r1, this.bbox.c1, 0); }; Range.prototype.setOffsetLast=function(offset){//offset = {offsetCol:intNumber, offsetRow:intNumber} this.bbox.c2 += offset.offsetCol; if( this.bbox.c2 < 0 ) this.bbox.c2 = 0; this.bbox.r2 += offset.offsetRow; if( this.bbox.r2 < 0 ) this.bbox.r2 = 0; this.last = new CellAddress(this.bbox.r2, this.bbox.c2, 0); }; Range.prototype.intersect=function(range){ var oBBox1 = this.bbox; var oBBox2 = range.bbox; var r1 = Math.max(oBBox1.r1, oBBox2.r1); var c1 = Math.max(oBBox1.c1, oBBox2.c1); var r2 = Math.min(oBBox1.r2, oBBox2.r2); var c2 = Math.min(oBBox1.c2, oBBox2.c2); if(r1 <= r2 && c1 <= c2) return this.worksheet.getRange3(r1, c1, r2, c2); return null; }; Range.prototype.cleanCache=function(){ this._setPropertyNoEmpty(null,null,function(cell, nRow0, nCol0, nRowStart, nColStart){ cell.cleanCache(); }); }; Range.prototype.cleanFormat=function(){ History.Create_NewPoint(); History.StartTransaction(); this.unmerge(); this._setPropertyNoEmpty(function(row){ row.setStyle(null); // if(row.isEmpty()) // row.Remove(); },function(col){ col.setStyle(null); // if(col.isEmpty()) // col.Remove(); },function(cell, nRow0, nCol0, nRowStart, nColStart){ cell.setStyle(null); // if(cell.isEmpty()) // cell.Remove(); }); History.EndTransaction(); }; Range.prototype.cleanText=function(){ History.Create_NewPoint(); History.StartTransaction(); this._setPropertyNoEmpty(null, null, function(cell, nRow0, nCol0, nRowStart, nColStart){ cell.setValue(""); // if(cell.isEmpty()) // cell.Remove(); }); History.EndTransaction(); }; Range.prototype.cleanAll=function(){ History.Create_NewPoint(); History.StartTransaction(); this.unmerge(); //удаляем только гиперссылки, которые полностью лежат в области var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(var i = 0, length = aHyperlinks.inner.length; i < length; ++i) this.removeHyperlink(aHyperlinks.inner[i].data); var oThis = this; this._setPropertyNoEmpty(function(row){ row.setStyle(null); // if(row.isEmpty()) // row.Remove(); },function(col){ col.setStyle(null); // if(col.isEmpty()) // col.Remove(); },function(cell, nRow0, nCol0, nRowStart, nColStart){ oThis.worksheet._removeCell(nRow0, nCol0); }); this.worksheet.workbook.buildRecalc(); History.EndTransaction(); }; Range.prototype.cleanHyperlinks=function(){ History.Create_NewPoint(); History.StartTransaction(); //удаляем только гиперссылки, которые полностью лежат в области var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(var i = 0, length = aHyperlinks.inner.length; i < length; ++i) this.removeHyperlink(aHyperlinks.inner[i].data); History.EndTransaction(); }; Range.prototype.sort=function(nOption, nStartCol, colorText, colorFill){ //todo горизонтальная сортировка var aMerged = this.worksheet.mergeManager.get(this.bbox); if(aMerged.outer.length > 0 || (aMerged.inner.length > 0 && null == _isSameSizeMerged(this.bbox, aMerged.inner))) return null; var nMergedHeight = 1; if(aMerged.inner.length > 0) { var merged = aMerged.inner[0]; nMergedHeight = merged.bbox.r2 - merged.bbox.r1 + 1; //меняем nStartCol, потому что приходит колонка той ячейки, на которой начали выделение nStartCol = merged.bbox.c1; } this.worksheet.workbook.lockDraw(); var isSortColor = !!(colorText || colorFill); var oRes = null; var oThis = this; var bAscent = false; if(nOption == AscCommonExcel.c_oAscSortOptions.Ascending) bAscent = true; var nRowFirst0 = this.bbox.r1; var nRowLast0 = this.bbox.r2; var nColFirst0 = this.bbox.c1; var nColLast0 = this.bbox.c2; var bWholeCol = false; var bWholeRow = false; if(0 == nRowFirst0 && gc_nMaxRow0 == nRowLast0) bWholeCol = true; if(0 == nColFirst0 && gc_nMaxCol0 == nColLast0) bWholeRow = true; var oRangeCol = this.worksheet.getRange(new CellAddress(nRowFirst0, nStartCol, 0), new CellAddress(nRowLast0, nStartCol, 0)); var nLastRow0 = 0; var nLastCol0 = nColLast0; if(true == bWholeRow) { nLastCol0 = 0; this._foreachRowNoEmpty(function(){}, function(cell){ var nCurCol0 = cell.nCol; if(nCurCol0 > nLastCol0) nLastCol0 = nCurCol0; }); } //собираем массив обьектов для сортировки var aSortElems = []; var aHiddenRow = {}; var fAddSortElems = function(oCell, nRow0, nCol0,nRowStart0, nColStart0){ //не сортируем сткрытие строки var row = oThis.worksheet._getRowNoEmpty(nRow0); if(null != row) { if(0 != (AscCommonExcel.g_nRowFlag_hd & row.flags)) aHiddenRow[nRow0] = 1; else { if(nLastRow0 < nRow0) nLastRow0 = nRow0; var val = oCell.getValueWithoutFormat(); //for sort color var colorFillCell, colorsTextCell = null; if(colorFill) { var styleCell = oCell.getStyle(); colorFillCell = styleCell !== null ? styleCell.fill : null; } else if(colorText) { var value2 = oCell.getValue2(); for(var n = 0; n < value2.length; n++) { colorsTextCell.push(value2[n].c); } } var nNumber = null; var sText = null; if("" != val) { var nVal = val - 0; if(nVal == val) nNumber = nVal; else sText = val; aSortElems.push({row: nRow0, num: nNumber, text: sText, colorFill: colorFillCell, colorsText: colorsTextCell}); } else if(isSortColor) { aSortElems.push({row: nRow0, num: nNumber, text: sText, colorFill: colorFillCell, colorsText: colorsTextCell}); } } } }; if(nColFirst0 == nStartCol) { while(0 == aSortElems.length && nStartCol <= nLastCol0) { if(false == bWholeCol) oRangeCol._foreachNoEmpty(fAddSortElems); else oRangeCol._foreachColNoEmpty(null, fAddSortElems); if(0 == aSortElems.length) { nStartCol++; oRangeCol = this.worksheet.getRange(new CellAddress(nRowFirst0, nStartCol, 0), new CellAddress(nRowLast0, nStartCol, 0)); } } } else { if(false == bWholeCol) oRangeCol._foreachNoEmpty(fAddSortElems); else oRangeCol._foreachColNoEmpty(null, fAddSortElems); } function strcmp ( str1, str2 ) { return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) ); } //color sort var colorFillCmp = function(color1, color2) { var res = false; if(colorFill) { res = color1 !== null && color2 !== null && color1.isEqual(color2) === true ? true : false; } else if(colorText && color1 && color1.length) { for(var n = 0; n < color1.length; n++) { if(color1[n] && color1[n].isEqual(color2)) { res = true; break; } } } return res; }; if(isSortColor) { var newArrayNeedColor = []; var newArrayAnotherColor = []; var sortColor = colorText ? colorText : colorFill; for(var i = 0; i < aSortElems.length; i++) { var color = colorFill ? aSortElems[i].colorFill : aSortElems[i].colorText; if(colorFillCmp(color, sortColor)) { newArrayNeedColor.push(aSortElems[i]); } else { newArrayAnotherColor.push(aSortElems[i]); } } aSortElems = newArrayAnotherColor.concat(newArrayNeedColor); } else { aSortElems.sort(function(a, b){ var res = 0; if(null != a.text) { if(null != b.text) res = strcmp(a.text.toUpperCase(), b.text.toUpperCase()); else res = 1; } else if(null != a.num) { if(null != b.num) res = a.num - b.num; else res = -1; } if(0 == res) res = a.row - b.row; else if(!bAscent) res = -res; return res; }); } //проверяем что это не пустая операция var aSortData = []; var nHiddenCount = 0; var oFromArray = {}; var nRowMax = 0; var nRowMin = gc_nMaxRow0; var nToMax = 0; for(var i = 0, length = aSortElems.length; i < length; ++i) { var item = aSortElems[i]; var nNewIndex = i * nMergedHeight + nRowFirst0 + nHiddenCount; while(null != aHiddenRow[nNewIndex]) { nHiddenCount++; nNewIndex = i * nMergedHeight + nRowFirst0 + nHiddenCount; } var oNewElem = new UndoRedoData_FromToRowCol(true, item.row, nNewIndex); oFromArray[item.row] = 1; if(nRowMax < item.row) nRowMax = item.row; if(nRowMax < nNewIndex) nRowMax = nNewIndex; if(nRowMin > item.row) nRowMin = item.row; if(nRowMin > nNewIndex) nRowMin = nNewIndex; if(nToMax < nNewIndex) nToMax = nNewIndex; if(oNewElem.from != oNewElem.to) aSortData.push(oNewElem); } if(aSortData.length > 0) { //добавляем индексы перехода пустых ячеек(нужно для сортировки комментариев) for(var i = nRowMin; i <= nRowMax; ++i) { if(null == oFromArray[i] && null == aHiddenRow[i]) { var nFrom = i; var nTo = ++nToMax; while(null != aHiddenRow[nTo]) nTo = ++nToMax; if(nFrom != nTo) { var oNewElem = new UndoRedoData_FromToRowCol(true, nFrom, nTo); aSortData.push(oNewElem); } } } History.Create_NewPoint(); var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(nColFirst0, nRowFirst0, nLastCol0, nLastRow0); History.SetSelection(oSelection); History.SetSelectionRedo(oSelection); } var oUndoRedoBBox = new UndoRedoData_BBox({r1:nRowFirst0, c1:nColFirst0, r2:nLastRow0, c2:nLastCol0}); oRes = new AscCommonExcel.UndoRedoData_SortData(oUndoRedoBBox, aSortData); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_Sort, this.worksheet.getId(), new Asc.Range(0, nRowFirst0, gc_nMaxCol0, nLastRow0), oRes); this._sortByArray(oUndoRedoBBox, aSortData); } this.worksheet.workbook.unLockDraw(); this.worksheet.workbook.buildRecalc(); return oRes; }; Range.prototype._sortByArray=function(oBBox, aSortData, bUndo){ var rec = {length:0}; var oSortedIndexes = {}; for(var i = 0, length = aSortData.length; i < length; ++i) { var item = aSortData[i]; var nFrom = item.from; var nTo = item.to; if(true == this.worksheet.workbook.bUndoChanges) { nFrom = item.to; nTo = item.from; } oSortedIndexes[nFrom] = nTo; } //сортируются только одинарные гиперссылки, все неодинарные оставляем var aSortedHyperlinks = []; if(false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; var aHyperlinks = this.worksheet.hyperlinkManager.get(this.bbox); for(var i = 0, length = aHyperlinks.inner.length; i < length; i++) { var elem = aHyperlinks.inner[i]; var hyp = elem.data; if(hyp.Ref.isOneCell()) { var nFrom = elem.bbox.r1; var nTo = oSortedIndexes[nFrom]; if(null != nTo) { //удаляем ссылки, а не перемеаем, чтобы не было конфликтов(например в случае если все ячейки имеют ссылки и их надо передвинуть) var oTempBBox = hyp.Ref.getBBox0(); this.worksheet.hyperlinkManager.removeElement(new RangeDataManagerElem(oTempBBox, hyp)); var oNewHyp = hyp.clone(); oNewHyp.Ref.setOffset({offsetCol: 0, offsetRow: nTo - nFrom}); aSortedHyperlinks.push(oNewHyp); } } } History.LocalChange = false; } //окончательно устанавливаем ячейки var nColFirst0 = oBBox.c1; var nLastCol0 = oBBox.c2; for(var i = nColFirst0; i <= nLastCol0; ++i) { //запоминаем ячейки в которые уже что-то передвинули, чтобы не потерять их var oTempCellsTo = {}; for(var j in oSortedIndexes) { var nIndexFrom = j - 0; var nIndexTo = oSortedIndexes[j]; var shift = nIndexTo - nIndexFrom; var rowFrom = this.worksheet._getRow(nIndexFrom); var rowTo = this.worksheet._getRow(nIndexTo); var oCurCell; if(oTempCellsTo.hasOwnProperty(nIndexFrom)) oCurCell = oTempCellsTo[nIndexFrom]; else{ oCurCell = rowFrom.c[i]; delete rowFrom.c[i]; } oTempCellsTo[nIndexTo] = rowTo.c[i]; if(null != oCurCell) { var lastName = oCurCell.getName(); oCurCell.moveVer(shift); rowTo.c[i] = oCurCell; if(oCurCell.sFormula) { var sNewName = oCurCell.getName(); oCurCell.setFormula(oCurCell.formulaParsed.changeOffset({offsetCol:0, offsetRow:shift}).assemble());//получаем новую формулу, путем сдвига входящих в нее ссылок на ячейки на offsetCol и offsetRow. не путать с shiftCells - меняет одну конкретную ячейку в формуле, changeOffset - меняет оффсет для всех входящих в формулу ячеек. this.worksheet.workbook.dependencyFormulas.deleteMasterNodes2( this.worksheet.Id, lastName );//разрываем ссылки между старой ячейкой и ведущими ячейками для нее. addToArrRecalc(this.worksheet.getId(), oCurCell); } } else { if(null != rowTo.c[i]) { //здесь достаточно простого delete, потому что на самом деле в функции ячейки только меняются местами, удаления не происходит delete rowTo.c[i]; } } } } var aNodes = this.worksheet.workbook.dependencyFormulas.getInRange( this.worksheet.Id, new Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2) ); if(aNodes && aNodes.length > 0) { for(var i = 0, length = aNodes.length; i < length; ++i) { var node = aNodes[i]; this.worksheet.workbook.needRecalc.nodes[ node.nodeId ] = [ node.sheetId, node.cellId ]; this.worksheet.workbook.needRecalc.length++; } } if (!this.worksheet.workbook.lockCounter) this.worksheet.workbook.sortDependency(); if(false == this.worksheet.workbook.bUndoChanges && (false == this.worksheet.workbook.bRedoChanges || true == this.worksheet.workbook.bCollaborativeChanges)) { History.LocalChange = true; //восстанавливаем удаленые гиперссылки if(aSortedHyperlinks.length > 0) { for(var i = 0, length = aSortedHyperlinks.length; i < length; i++) { var hyp = aSortedHyperlinks[i]; this.worksheet.hyperlinkManager.add(hyp.Ref.getBBox0(), hyp); } } History.LocalChange = false; } }; function _isSameSizeMerged(bbox, aMerged) { var oRes = null; var nWidth = null; var nHeight = null; for(var i = 0, length = aMerged.length; i < length; i++) { var mergedBBox = aMerged[i].bbox; var nCurWidth = mergedBBox.c2 - mergedBBox.c1 + 1; var nCurHeight = mergedBBox.r2 - mergedBBox.r1 + 1; if(null == nWidth || null == nHeight) { nWidth = nCurWidth; nHeight = nCurHeight; } else if(nCurWidth != nWidth || nCurHeight != nHeight) { nWidth = null; nHeight = null; break; } } if(null != nWidth && null != nHeight) { //проверяем что merge ячеки полностью заполняют область var nBBoxWidth = bbox.c2 - bbox.c1 + 1; var nBBoxHeight = bbox.r2 - bbox.r1 + 1; if(nBBoxWidth == nWidth || nBBoxHeight == nHeight) { var bRes = false; var aRowColTest = null; if(nBBoxWidth == nWidth && nBBoxHeight == nHeight) bRes = true; else if(nBBoxWidth == nWidth) { aRowColTest = new Array(nBBoxHeight); for(var i = 0, length = aMerged.length; i < length; i++) { var merged = aMerged[i]; for(var j = merged.bbox.r1; j <= merged.bbox.r2; j++) aRowColTest[j - bbox.r1] = 1; } } else if(nBBoxHeight == nHeight) { aRowColTest = new Array(nBBoxWidth); for(var i = 0, length = aMerged.length; i < length; i++) { var merged = aMerged[i]; for(var j = merged.bbox.c1; j <= merged.bbox.c2; j++) aRowColTest[j - bbox.c1] = 1; } } if(null != aRowColTest) { var bExistNull = false; for(var i = 0, length = aRowColTest.length; i < length; i++) { if(null == aRowColTest[i]) { bExistNull = true; break; } } if(!bExistNull) bRes = true; } if(bRes) oRes = {width: nWidth, height: nHeight}; } } return oRes; } function _canPromote(from, wsFrom, to, wsTo, bIsPromote, nWidth, nHeight, bVertical, nIndex) { var oRes = {oMergedFrom: null, oMergedTo: null}; //если надо только удалить внутреннее содержимое не смотрим на замерженость if(!bIsPromote || !((true == bVertical && nIndex >= 0 && nIndex < nHeight) || (false == bVertical && nIndex >= 0 && nIndex < nWidth))) { if(null != to){ var oMergedTo = wsTo.mergeManager.get(to); if(oMergedTo.outer.length > 0) oRes = null; else { var oMergedFrom = wsFrom.mergeManager.get(from); oRes.oMergedFrom = oMergedFrom; if(oMergedTo.inner.length > 0) { oRes.oMergedTo = oMergedTo; if (bIsPromote) { if (oMergedFrom.inner.length > 0) { //merge области должны иметь одинаковый размер var oSizeFrom = _isSameSizeMerged(from, oMergedFrom.inner); var oSizeTo = _isSameSizeMerged(to, oMergedTo.inner); if (!(null != oSizeFrom && null != oSizeTo && oSizeTo.width == oSizeFrom.width && oSizeTo.height == oSizeFrom.height)) oRes = null; } else oRes = null; } } } } } return oRes; } // Подготовка Copy Style function preparePromoteFromTo(from, to) { var bSuccess = true; if (to.isOneCell()) to.setOffsetLast({offsetCol: (from.c2 - from.c1) - (to.c2 - to.c1), offsetRow: (from.r2 - from.r1) - (to.r2 - to.r1)}); if(!from.isIntersect(to)) { var bFromWholeCol = (0 == from.c1 && gc_nMaxCol0 == from.c2); var bFromWholeRow = (0 == from.r1 && gc_nMaxRow0 == from.r2); var bToWholeCol = (0 == to.c1 && gc_nMaxCol0 == to.c2); var bToWholeRow = (0 == to.r1 && gc_nMaxRow0 == to.r2); bSuccess = (bFromWholeCol === bToWholeCol && bFromWholeRow === bToWholeRow); } else bSuccess = false; return bSuccess; } // Перед promoteFromTo обязательно должна быть вызывана функция preparePromoteFromTo function promoteFromTo(from, wsFrom, to, wsTo) { var bVertical = true; var nIndex = 1; //проверяем можно ли осуществить promote var oCanPromote = _canPromote(from, wsFrom, to, wsTo, false, 1, 1, bVertical, nIndex); if(null != oCanPromote) { History.Create_NewPoint(); var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(from.c1, from.r1, from.c2, from.r2); History.SetSelection(oSelection); } var oSelectionRedo = History.GetSelectionRedo(); if(null != oSelectionRedo) { oSelectionRedo = oSelectionRedo.clone(); oSelectionRedo.assign(to.c1, to.r1, to.c2, to.r2); History.SetSelectionRedo(oSelectionRedo); } //удаляем merge ячейки в to(после _canPromote должны остаться только inner) wsTo.mergeManager.remove(to, true); _promoteFromTo(from, wsFrom, to, wsTo, false, oCanPromote, false, bVertical, nIndex); } } Range.prototype.promote=function(bCtrl, bVertical, nIndex){ //todo отдельный метод для promote в таблицах и merge в таблицах var oBBox = this.bbox; var nWidth = oBBox.c2 - oBBox.c1 + 1; var nHeight = oBBox.r2 - oBBox.r1 + 1; var bWholeCol = false; var bWholeRow = false; if(0 == oBBox.r1 && gc_nMaxRow0 == oBBox.r2) bWholeCol = true; if(0 == oBBox.c1 && gc_nMaxCol0 == oBBox.c2) bWholeRow = true; if((bWholeCol && bWholeRow) || (true == bVertical && bWholeCol) || (false == bVertical && bWholeRow)) return false; var oPromoteAscRange = null; if(0 == nIndex) oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2); else { if(bVertical) { if(nIndex > 0) { if(nIndex >= nHeight) oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r2 + 1, oBBox.c2, oBBox.r1 + nIndex); else oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r2); } else oPromoteAscRange = Asc.Range(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r1 - 1); } else { if(nIndex > 0) { if(nIndex >= nWidth) oPromoteAscRange = Asc.Range(oBBox.c2 + 1, oBBox.r1, oBBox.c1 + nIndex, oBBox.r2); else oPromoteAscRange = Asc.Range(oBBox.c1 + nIndex, oBBox.r1, oBBox.c2, oBBox.r2); } else oPromoteAscRange = Asc.Range(oBBox.c1 + nIndex, oBBox.r1, oBBox.c1 - 1, oBBox.r2); } } //проверяем можно ли осуществить promote var oCanPromote = _canPromote(oBBox, this.worksheet, oPromoteAscRange, this.worksheet, true, nWidth, nHeight, bVertical, nIndex); if(null == oCanPromote) return false; History.Create_NewPoint(); var oSelection = History.GetSelection(); if(null != oSelection) { oSelection = oSelection.clone(); oSelection.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2); History.SetSelection(oSelection); } var oSelectionRedo = History.GetSelectionRedo(); if(null != oSelectionRedo) { oSelectionRedo = oSelectionRedo.clone(); if(0 == nIndex) oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r2); else { if(bVertical) { if(nIndex > 0) { if(nIndex >= nHeight) oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r1 + nIndex); else oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c2, oBBox.r1 + nIndex - 1); } else oSelectionRedo.assign(oBBox.c1, oBBox.r1 + nIndex, oBBox.c2, oBBox.r2); } else { if(nIndex > 0) { if(nIndex >= nWidth) oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c1 + nIndex, oBBox.r2); else oSelectionRedo.assign(oBBox.c1, oBBox.r1, oBBox.c1 + nIndex - 1, oBBox.r2); } else oSelectionRedo.assign(oBBox.c1 + nIndex, oBBox.r1, oBBox.c2, oBBox.r2); } } History.SetSelectionRedo(oSelectionRedo); } oFormulaLocaleInfo.Parse = false; oFormulaLocaleInfo.DigitSep = false; _promoteFromTo(oBBox, this.worksheet, oPromoteAscRange, this.worksheet, true, oCanPromote, bCtrl, bVertical, nIndex); oFormulaLocaleInfo.Parse = true; oFormulaLocaleInfo.DigitSep = true; return true; }; function _promoteFromTo(from, wsFrom, to, wsTo, bIsPromote, oCanPromote, bCtrl, bVertical, nIndex) { var wb = wsFrom.workbook; wb.lockDraw(); History.StartTransaction(); var toRange = wsTo.getRange3(to.r1, to.c1, to.r2, to.c2); var fromRange = wsFrom.getRange3(from.r1, from.c1, from.r2, from.c2); var bChangeRowColProp = false; var nLastCol = from.c2; if (0 == from.c1 && gc_nMaxCol0 == from.c2) { var aRowProperties = []; nLastCol = 0; fromRange._foreachRowNoEmpty(function(row){ if(!row.isEmptyProp()) aRowProperties.push({index: row.index - from.r1, prop: row.getHeightProp(), style: row.getStyle()}); }, function(cell){ var nCurCol0 = cell.nCol; if(nCurCol0 > nLastCol) nLastCol = nCurCol0; }); if(aRowProperties.length > 0) { bChangeRowColProp = true; var nCurCount = 0; var nCurIndex = 0; while (true) { for (var i = 0, length = aRowProperties.length; i < length; ++i) { var propElem = aRowProperties[i]; nCurIndex = to.r1 + nCurCount * (from.r2 - from.r1 + 1) + propElem.index; if (nCurIndex > to.r2) break; else{ var row = wsTo._getRow(nCurIndex); if (null != propElem.style) row.setStyle(propElem.style); if (null != propElem.prop) { var oNewProps = propElem.prop; var oOldProps = row.getHeightProp(); if (false === oOldProps.isEqual(oNewProps)) { row.setHeightProp(oNewProps); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_RowProp, wsTo.getId(), row._getUpdateRange(), new UndoRedoData_IndexSimpleProp(nCurIndex, true, oOldProps, oNewProps)); } } } } nCurCount++; if (nCurIndex > to.r2) break; } } } var nLastRow = from.r2; if (0 == from.r1 && gc_nMaxRow0 == from.r2) { var aColProperties = []; nLastRow = 0; fromRange._foreachColNoEmpty(function(col){ if(!col.isEmpty()) aColProperties.push({ index: col.index - from.c1, prop: col.getWidthProp(), style: col.getStyle() }); }, function(cell){ var nCurRow0 = cell.nRow; if(nCurRow0 > nLastRow) nLastRow = nCurRow0; }); if (aColProperties.length > 0) { bChangeRowColProp = true; var nCurCount = 0; var nCurIndex = 0; while (true) { for (var i = 0, length = aColProperties.length; i < length; ++i) { var propElem = aColProperties[i]; nCurIndex = to.c1 + nCurCount * (from.c2 - from.c1 + 1) + propElem.index; if (nCurIndex > to.c2) break; else{ var col = wsTo._getCol(nCurIndex); if (null != propElem.style) col.setStyle(propElem.style); if (null != propElem.prop) { var oNewProps = propElem.prop; var oOldProps = col.getWidthProp(); if (false == oOldProps.isEqual(oNewProps)) { col.setWidthProp(oNewProps); History.Add(AscCommonExcel.g_oUndoRedoWorksheet, AscCH.historyitem_Worksheet_ColProp, wsTo.getId(), new Asc.Range(nCurIndex, 0, nCurIndex, gc_nMaxRow0), new UndoRedoData_IndexSimpleProp(nCurIndex, false, oOldProps, oNewProps)); } } } } nCurCount++; if (nCurIndex > to.c2) break; } } } if (bChangeRowColProp) wb.handlers.trigger("changeWorksheetUpdate", wsTo.getId()); if(nLastCol != from.c2 || nLastRow != from.r2) { var offset = {offsetCol:nLastCol - from.c2, offsetRow:nLastRow - from.r2}; toRange.setOffsetLast(offset); to = toRange.getBBox0(); fromRange.setOffsetLast(offset); from = fromRange.getBBox0(); } var nWidth = from.c2 - from.c1 + 1; var nHeight = from.r2 - from.r1 + 1; //удаляем текст или все в области для заполнения if(bIsPromote && nIndex >= 0 && ((true == bVertical && nHeight > nIndex) || (false == bVertical && nWidth > nIndex))) { //удаляем только текст в области для заполнения toRange.cleanText(); } else { //удаляем все в области для заполнения if(bIsPromote) toRange.cleanAll(); else toRange.cleanFormat(); //собираем все данные var bReverse = false; if(nIndex < 0) bReverse = true; var oPromoteHelper = new PromoteHelper(bVertical, bReverse, from); fromRange._foreachNoEmpty(function(oCell, nRow0, nCol0, nRowStart0, nColStart0){ if(null != oCell) { var nVal = null; var bDelimiter = false; var sPrefix = null; var bDate = false; if(bIsPromote) { if (!oCell.sFormula) { var sValue = oCell.getValueWithoutFormat(); if("" != sValue) { bDelimiter = true; var nType = oCell.getType(); if(CellValueType.Number == nType || CellValueType.String == nType) { if(CellValueType.Number == nType) nVal = sValue - 0; else { //если текст заканчивается на цифру тоже используем ее var nEndIndex = sValue.length; for(var k = sValue.length - 1; k >= 0; --k) { var sCurChart = sValue[k]; if('0' <= sCurChart && sCurChart <= '9') nEndIndex--; else break; } if(sValue.length != nEndIndex) { sPrefix = sValue.substring(0, nEndIndex); nVal = sValue.substring(nEndIndex) - 0; } } } if(null != oCell.xfs && null != oCell.xfs.num && null != oCell.xfs.num.getFormat()){ var numFormat = oNumFormatCache.get(oCell.xfs.num.getFormat()); if(numFormat.isDateTimeFormat()) bDate = true; } if(null != nVal) bDelimiter = false; } } else bDelimiter = true; } oPromoteHelper.add(nRow0 - nRowStart0, nCol0 - nColStart0, nVal, bDelimiter, sPrefix, bDate, oCell); } }); var bCopy = false; if(bCtrl) bCopy = true; //в случае одной ячейки с числом меняется смысл bCtrl if(1 == nWidth && 1 == nHeight && oPromoteHelper.isOnlyIntegerSequence()) bCopy = !bCopy; oPromoteHelper.finishAdd(bCopy); //заполняем ячейки данными var nStartRow, nEndRow, nStartCol, nEndCol, nColDx, bRowFirst; if(bVertical) { nStartRow = to.c1; nEndRow = to.c2; bRowFirst = false; if(bReverse) { nStartCol = to.r2; nEndCol = to.r1; nColDx = -1; } else { nStartCol = to.r1; nEndCol = to.r2; nColDx = 1; } } else { nStartRow = to.r1; nEndRow = to.r2; bRowFirst = true; if(bReverse) { nStartCol = to.c2; nEndCol = to.c1; nColDx = -1; } else { nStartCol = to.c1; nEndCol = to.c2; nColDx = 1; } } for(var i = nStartRow; i <= nEndRow; i ++) { oPromoteHelper.setIndex(i - nStartRow); for(var j = nStartCol; (nStartCol - j) * (nEndCol - j) <= 0; j += nColDx) { var data = oPromoteHelper.getNext(); if(null != data && (data.oAdditional || (false == bCopy && null != data.nCurValue))) { var oFromCell = data.oAdditional; var oCopyCell = null; if(bRowFirst) oCopyCell = wsTo._getCell(i, j); else oCopyCell = wsTo._getCell(j, i); if(bIsPromote) { if(false == bCopy && null != data.nCurValue) { var sVal = ""; if(null != data.sPrefix) sVal += data.sPrefix; //change javascript NumberDecimalSeparator '.' , to cultural NumberDecimalSeparator sVal += data.nCurValue.toString().replace(/\./g, AscCommon.g_oDefaultCultureInfo.NumberDecimalSeparator); oCopyCell.setValue(sVal); } else if(null != oFromCell) { //копируем полностью if(!oFromCell.formulaParsed){ var DataOld = oCopyCell.getValueData(); oCopyCell.oValue = oFromCell.oValue.clone(); var DataNew = oCopyCell.getValueData(); if(false == DataOld.isEqual(DataNew)) History.Add(AscCommonExcel.g_oUndoRedoCell, AscCH.historyitem_Cell_ChangeValue, wsTo.getId(), new Asc.Range(oCopyCell.nCol, oCopyCell.nRow, oCopyCell.nCol, oCopyCell.nRow), new UndoRedoData_CellSimpleData(oCopyCell.nRow, oCopyCell.nCol, DataOld, DataNew)); //todo // if(oCopyCell.isEmptyTextString()) // wsTo._getHyperlink().remove({r1: oCopyCell.nRow, c1: oCopyCell.nCol, r2: oCopyCell.nRow, c2: oCopyCell.nCol}); } else{ var assemb; var _p_ = new parserFormula(oFromCell.sFormula,oCopyCell.getName(),wsTo); if( _p_.parse() ){ assemb = _p_.changeOffset(oCopyCell.getOffset2(oFromCell.getName())).assemble(); oCopyCell.setValue("="+assemb); } } } } //выставляем стиль после текста, потому что если выставить числовой стиль ячейки 'text', то после этого не применится формула if (null != oFromCell) { oCopyCell.setStyle(oFromCell.getStyle()); if (bIsPromote) oCopyCell.setType(oFromCell.getType()); } } } } if(bIsPromote) { var aNodes = wb.dependencyFormulas.getInRange( wsTo.Id, to ); if(aNodes && aNodes.length > 0) { for(var i = 0, length = aNodes.length; i < length; ++i) { var node = aNodes[i]; wb.needRecalc.nodes[ node.nodeId ] = [ node.sheetId, node.cellId ]; wb.needRecalc.length++; } } } //добавляем замерженые области var nDx = from.c2 - from.c1 + 1; var nDy = from.r2 - from.r1 + 1; var oMergedFrom = oCanPromote.oMergedFrom; if(null != oMergedFrom && oMergedFrom.all.length > 0) { for (var i = to.c1; i <= to.c2; i += nDx) { for (var j = to.r1; j <= to.r2; j += nDy) { for (var k = 0, length3 = oMergedFrom.all.length; k < length3; k++) { var oMergedBBox = oMergedFrom.all[k].bbox; var oNewMerged = Asc.Range(i + oMergedBBox.c1 - from.c1, j + oMergedBBox.r1 - from.r1, i + oMergedBBox.c2 - from.c1, j + oMergedBBox.r2 - from.r1); if(to.contains(oNewMerged.c1, oNewMerged.r1)) { if(to.c2 < oNewMerged.c2) oNewMerged.c2 = to.c2; if(to.r2 < oNewMerged.r2) oNewMerged.r2 = to.r2; if(!oNewMerged.isOneCell()) wsTo.mergeManager.add(oNewMerged, 1); } } } } } if(bIsPromote) { //добавляем ссылки //не как в Excel поддерживаются ссылки на диапазоны var oHyperlinks = wsFrom.hyperlinkManager.get(from); if(oHyperlinks.inner.length > 0) { for (var i = to.c1; i <= to.c2; i += nDx) { for (var j = to.r1; j <= to.r2; j += nDy) { for(var k = 0, length3 = oHyperlinks.inner.length; k < length3; k++){ var oHyperlink = oHyperlinks.inner[k]; var oHyperlinkBBox = oHyperlink.bbox; var oNewHyperlink = Asc.Range(i + oHyperlinkBBox.c1 - from.c1, j + oHyperlinkBBox.r1 - from.r1, i + oHyperlinkBBox.c2 - from.c1, j + oHyperlinkBBox.r2 - from.r1); if (to.containsRange(oNewHyperlink)) wsTo.hyperlinkManager.add(oNewHyperlink, oHyperlink.data.clone()); } } } } } } History.EndTransaction(); wb.unLockDraw(); wb.buildRecalc(); } Range.prototype.createCellOnRowColCross=function(){ var oThis = this; var bbox = this.bbox; var nRangeType = this._getRangeType(bbox); if(c_oRangeType.Row == nRangeType) { this._foreachColNoEmpty(function(col){ if(null != col.xfs) { for(var i = bbox.r1; i <= bbox.r2; ++i) oThis.worksheet._getCell(i, col.index); } }, null); } else if(c_oRangeType.Col == nRangeType) { this._foreachRowNoEmpty(function(row){ if(null != row.xfs) { for(var i = bbox.c1; i <= bbox.c2; ++i) oThis.worksheet._getCell(row.index, i); } }, null); } }; //------------------------------------------------------------------------------------------------- /** * @constructor */ function PromoteHelper(bVerical, bReverse, bbox){ //автозаполнение происходит всегда в правую сторону, поэтому менются индексы в методе add, и это надо учитывать при вызове getNext this.bVerical = bVerical; this.bReverse = bReverse; this.bbox = bbox; this.oDataRow = {}; //для get this.oCurRow = null; this.nCurColIndex = null; this.nRowLength = 0; this.nColLength = 0; if(this.bVerical) { this.nRowLength = this.bbox.c2 - this.bbox.c1 + 1; this.nColLength = this.bbox.r2 - this.bbox.r1 + 1; } else { this.nRowLength = this.bbox.r2 - this.bbox.r1 + 1; this.nColLength = this.bbox.c2 - this.bbox.c1 + 1; } } PromoteHelper.prototype = { add: function(nRow, nCol, nVal, bDelimiter, sPrefix, bDate, oAdditional){ if(this.bVerical) { //транспонируем для удобства var temp = nRow; nRow = nCol; nCol = temp; } if(this.bReverse) nCol = this.nColLength - nCol - 1; var row = this.oDataRow[nRow]; if(null == row) { row = {}; this.oDataRow[nRow] = row; } row[nCol] = {nCol: nCol, nVal: nVal, bDelimiter: bDelimiter, sPrefix: sPrefix, bDate: bDate, oAdditional: oAdditional, oSequence: null, nCurValue: null}; }, isOnlyIntegerSequence: function(){ var bRes = true; var bEmpty = true; for(var i in this.oDataRow) { var row = this.oDataRow[i]; for(var j in row) { var data = row[j]; bEmpty = false; if(!(null != data.nVal && true != data.bDate && null == data.sPrefix)) { bRes = false; break; } } if(!bRes) break; } if(bEmpty) bRes = false; return bRes; }, _promoteSequence: function(aDigits){ // Это коэффициенты линейного приближения (http://office.microsoft.com/ru-ru/excel-help/HP010072685.aspx) // y=a1*x+a0 (где: x=0,1....; y=значения в ячейках; a0 и a1 - это решения приближения функции методом наименьших квадратов // (n+1)*a0 + (x0+x1+....) *a1=(y0+y1+...) // (x0+x1+....)*a0 + (x0*x0+x1*x1+....)*a1=(y0*x0+y1*x1+...) // http://www.exponenta.ru/educat/class/courses/vvm/theme_7/theory.asp var a0 = 0.0; var a1 = 0.0; // Индекс X var nX = 0; if(1 == aDigits.length) { nX = 1; a1 = 1; a0 = aDigits[0].y; } else { // (n+1) var nN = aDigits.length; // (x0+x1+....) var nXi = 0; // (x0*x0+x1*x1+....) var nXiXi = 0; // (y0+y1+...) var dYi = 0.0; // (y0*x0+y1*x1+...) var dYiXi = 0.0; // Цикл по всем строкам for (var i = 0, length = aDigits.length; i < length; ++i) { var data = aDigits[i]; nX = data.x; var dValue = data.y; // Вычисляем значения nXi += nX; nXiXi += nX * nX; dYi += dValue; dYiXi += dValue * nX; } nX++; // Теперь решаем систему уравнений // Общий детерминант var dD = nN * nXiXi - nXi * nXi; // Детерминант первого корня var dD1 = dYi * nXiXi - nXi * dYiXi; // Детерминант второго корня var dD2 = nN * dYiXi - dYi * nXi; a0 = dD1 / dD; a1 = dD2 / dD; } return {a0: a0, a1: a1, nX: nX}; }, _addSequenceToRow : function(nRowIndex, aSortRowIndex, row, aCurSequence){ if(aCurSequence.length > 0) { var oFirstData = aCurSequence[0]; var bCanPromote = true; //если последовательность состоит из одного числа и той же колонке есть еще последовательности, то надо копировать, а не автозаполнять if(1 == aCurSequence.length) { var bVisitRowIndex = false; var oVisitData = null; for(var i = 0, length = aSortRowIndex.length; i < length; i++) { var nCurRowIndex = aSortRowIndex[i]; if(nRowIndex == nCurRowIndex) { bVisitRowIndex = true; if(oVisitData && oFirstData.sPrefix == oVisitData.sPrefix && oFirstData.bDate == oVisitData.bDate) { bCanPromote = false; break; } } else { var oCurRow = this.oDataRow[nCurRowIndex]; if(oCurRow) { var data = oCurRow[oFirstData.nCol]; if(null != data) { if(null != data.nVal) { oVisitData = data; if(bVisitRowIndex) { if(oFirstData.sPrefix == oVisitData.sPrefix && oFirstData.bDate == oVisitData.bDate) bCanPromote = false; break; } } else if(data.bDelimiter) { oVisitData = null; if(bVisitRowIndex) break; } } } } } } if(bCanPromote) { var nMinIndex = null; var nMaxIndex = null; var bValidIndexDif = true; var nPrevX = null; var nPrevVal = null; var nIndexDif = null; var nValueDif = null; //анализируем последовательность, если числа расположены не на одинаковом расстоянии, то считаем их сплошной последовательностью //последовательность с промежутками может быть только целочисленной for(var i = 0, length = aCurSequence.length; i < length; i++) { var data = aCurSequence[i]; var nCurX = data.nCol; if(null == nMinIndex || null == nMaxIndex) nMinIndex = nMaxIndex = nCurX; else { if(nCurX < nMinIndex) nMinIndex = nCurX; if(nCurX > nMaxIndex) nMaxIndex = nCurX; } if(bValidIndexDif) { if(null != nPrevX && null != nPrevVal) { var nCurDif = nCurX - nPrevX; var nCurValDif = data.nVal - nPrevVal; if(null == nIndexDif || null == nCurValDif) { nIndexDif = nCurDif; nValueDif = nCurValDif; } else if(nIndexDif != nCurDif || nValueDif != nCurValDif) { nIndexDif = null; bValidIndexDif = false; } } } nPrevX = nCurX; nPrevVal = data.nVal; } var bWithSpace = false; if(null != nIndexDif) { nIndexDif = Math.abs(nIndexDif); if(nIndexDif > 1) bWithSpace = true; } //заполняем массив с координатами var bExistSpace = false; nPrevX = null; var aDigits = []; for(var i = 0, length = aCurSequence.length; i < length; i++) { var data = aCurSequence[i]; var nCurX = data.nCol; var x = nCurX - nMinIndex; if(null != nIndexDif && nIndexDif > 0) x /= nIndexDif; if(null != nPrevX && nCurX - nPrevX > 1) bExistSpace = true; var y = data.nVal; //даты автозаполняем только по целой части if(data.bDate) y = parseInt(y); aDigits.push({x: x, y: y}); nPrevX = nCurX; } if(aDigits.length > 0) { var oSequence = this._promoteSequence(aDigits); if(1 == aDigits.length && this.bReverse) { //меняем коэффициенты для случая одного числа в последовательности, иначе она в любую сторону будет возрастающей oSequence.a1 *= -1; } var bIsIntegerSequence = oSequence.a1 != parseInt(oSequence.a1); //для дат и чисел с префиксом автозаполняются только целочисленные последовательности if(!((null != oFirstData.sPrefix || true == oFirstData.bDate) && bIsIntegerSequence)) { if(false == bWithSpace && bExistSpace) { for(var i = nMinIndex; i <= nMaxIndex; i++) { var data = row[i]; if(null == data) { data = {nCol: i, nVal: null, bDelimiter: oFirstData.bDelimiter, sPrefix: oFirstData.sPrefix, bDate: oFirstData.bDate, oAdditional: null, oSequence: null, nCurValue: null}; row[i] = data; } data.oSequence = oSequence; } } else { for(var i = 0, length = aCurSequence.length; i < length; i++) { var nCurX = aCurSequence[i].nCol; if(null != nCurX) row[nCurX].oSequence = oSequence; } } } } } } }, finishAdd : function(bCopy){ if(true != bCopy) { var aSortRowIndex = []; for(var i in this.oDataRow) aSortRowIndex.push(i - 0); aSortRowIndex.sort(fSortAscending); for(var i = 0, length = aSortRowIndex.length; i < length; i++) { var nRowIndex = aSortRowIndex[i]; var row = this.oDataRow[nRowIndex]; //собираем информация о последовательностях в row var aSortIndex = []; for(var j in row) aSortIndex.push(j - 0); aSortIndex.sort(fSortAscending); var aCurSequence = []; var oPrevData = null; for(var j = 0, length2 = aSortIndex.length; j < length2; j++) { var nColIndex = aSortIndex[j]; var data = row[nColIndex]; var bAddToSequence = false; if(null != data.nVal) { bAddToSequence = true; if(null != oPrevData && (oPrevData.bDelimiter != data.bDelimiter || oPrevData.sPrefix != data.sPrefix || oPrevData.bDate != data.bDate)) { this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence); aCurSequence = []; oPrevData = null; } oPrevData = data; } else if(data.bDelimiter) { this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence); aCurSequence = []; oPrevData = null; } if(bAddToSequence) aCurSequence.push(data); } this._addSequenceToRow(nRowIndex, aSortRowIndex, row, aCurSequence); } } }, setIndex: function(index){ if(0 != this.nRowLength && index >= this.nRowLength) index = index % (this.nRowLength); this.oCurRow = this.oDataRow[index]; this.nCurColIndex = 0; }, getNext: function(){ var oRes = null; if(this.oCurRow) { var oRes = this.oCurRow[this.nCurColIndex]; if(null != oRes) { oRes.nCurValue = null; if(null != oRes.oSequence) { var sequence = oRes.oSequence; if(oRes.bDate || null != oRes.sPrefix) oRes.nCurValue = Math.abs(sequence.a1 * sequence.nX + sequence.a0); else oRes.nCurValue = sequence.a1 * sequence.nX + sequence.a0; sequence.nX ++; } } this.nCurColIndex++; if(this.nCurColIndex >= this.nColLength) this.nCurColIndex = 0; } return oRes; } }; function DefinedName(){ this.Name = null; this.Ref = null; this.LocalSheetId = null; this.Hidden = null; this.bTable = false; } //------------------------------------------------------------------------------------------------- /** * @constructor */ function DrawingObjectsManager(worksheet) { this.worksheet = worksheet; } DrawingObjectsManager.prototype.updateChartReferences = function(oldWorksheet, newWorksheet) { AscFormat.ExecuteNoHistory(function(){ this.updateChartReferencesWidthHistory(oldWorksheet, newWorksheet); }, this, []); }; DrawingObjectsManager.prototype.updateChartReferencesWidthHistory = function(oldWorksheet, newWorksheet, bNoRebuildCache) { var aObjects = this.worksheet.Drawings; for (var i = 0; i < aObjects.length; i++) { var graphicObject = aObjects[i].graphicObject; if ( graphicObject.updateChartReferences ) { graphicObject.updateChartReferences(oldWorksheet, newWorksheet, bNoRebuildCache); } } }; DrawingObjectsManager.prototype.rebuildCharts = function(data) { var aObjects = this.worksheet.Drawings; for(var i = 0; i < aObjects.length; ++i) { if(aObjects[i].graphicObject.rebuildSeries) { aObjects[i].graphicObject.rebuildSeries(data); } } }; window['AscCommonExcel'] = window['AscCommonExcel'] || {}; window['AscCommonExcel'].g_nVerticalTextAngle = g_nVerticalTextAngle; window['AscCommonExcel'].oDefaultMetrics = oDefaultMetrics; window['AscCommonExcel'].g_nAllColIndex = g_nAllColIndex; window['AscCommonExcel'].g_nAllRowIndex = g_nAllRowIndex; window['AscCommonExcel'].aStandartNumFormats = aStandartNumFormats; window['AscCommonExcel'].aStandartNumFormatsId = aStandartNumFormatsId; window['AscCommonExcel'].oFormulaLocaleInfo = oFormulaLocaleInfo; window['AscCommonExcel'].DependencyGraph = DependencyGraph; window['AscCommonExcel'].getVertexId = getVertexId; window['AscCommonExcel'].buildDefNameAfterRenameWorksheet = buildDefNameAfterRenameWorksheet; window['AscCommonExcel'].angleFormatToInterface2 = angleFormatToInterface2; window['AscCommonExcel'].angleInterfaceToFormat = angleInterfaceToFormat; window['AscCommonExcel'].Workbook = Workbook; window['AscCommonExcel'].Woorksheet = Woorksheet; window['AscCommonExcel'].Cell = Cell; window['AscCommonExcel'].Range = Range; window['AscCommonExcel'].preparePromoteFromTo = preparePromoteFromTo; window['AscCommonExcel'].promoteFromTo = promoteFromTo; window['AscCommonExcel'].DefinedName = DefinedName; })(window);
support uniqueValues and duplicateValues in conditional formatting
cell/model/Workbook.js
support uniqueValues and duplicateValues in conditional formatting
<ide><path>ell/model/Workbook.js <ide> function getUniqueKeys(array) { <ide> var i, o = {}; <ide> for (i = 0; i < array.length; ++i) { <del> o[array[i]] = !o.hasOwnProperty(array[i]); <add> o[array[i]] = o.hasOwnProperty(array[i]); <ide> } <ide> return o; <ide> } <ide> var aRules, oRule; <ide> var oRuleElement = null; <ide> var o; <del> var i, j, cell, sqref, values, tmp, min, max, dxf; <add> var i, j, cell, sqref, values, tmp, min, max, dxf, condition; <ide> for (i = 0; i < aCFs.length; ++i) { <ide> sqref = aCFs[i].sqref; <ide> // ToDo убрать null === sqref когда научимся мультиселект обрабатывать (\\192.168.5.2\source\DOCUMENTS\XLSX\Matematika Quantum Sedekah.xlsx) <ide> } <ide> } <ide> break; <add> case Asc.ECfType.duplicateValues: <ide> case Asc.ECfType.uniqueValues: <del> o = getUniqueKeys(values.v); <add> if (oRule.dxf) { <add> condition = oRule.type === Asc.ECfType.uniqueValues; <add> values = this._getValuesForConditionalFormatting(sqref); <add> o = getUniqueKeys(values.v); <add> for (cell = 0; cell < values.c.length; ++cell) { <add> values.c[cell].setConditionalFormattingStyle((condition === o[values.v[cell]]) ? null : oRule.dxf); <add> } <add> } <ide> break; <ide> } <ide> }
Java
mit
501f7e5c394b69632b4eff9612c766ecefe60695
0
aima-java/aima-java,aimacode/aima-java,dariosena/aima-java,ramgovin/aima-java,EvgenyKarataev/aima-java,sonyccd/aima-java,j129008/aima-java,futuristixa/aima-java,aimacode/aima-java,ngrj93/aima-java,futuristixa/aima-java
package aima.gui.applications.vacuum; import java.awt.Color; import java.util.ArrayList; import java.util.Hashtable; import java.util.List; import aima.core.agent.Action; import aima.core.agent.Agent; import aima.core.agent.EnvironmentState; import aima.core.agent.impl.DynamicAction; import aima.core.environment.vacuum.VacuumEnvironment; import aima.gui.framework.EmptyEnvironmentView; /** * Displays the informations provided by a <code>VacuumEnvironment</code> on a * panel using 2D-graphics. */ public class VacuumView extends EmptyEnvironmentView { private Hashtable<Agent, Action> lastActions = new Hashtable<Agent, Action>(); @Override public void agentActed(Agent agent, Action action, EnvironmentState resultingState) { lastActions.put(agent, action); String prefix = ""; if (env.getAgents().size() > 1) prefix = "A" + env.getAgents().indexOf(agent) + ": "; notify(prefix + action.toString()); super.agentActed(agent, action, resultingState); } protected VacuumEnvironment getVacuumEnv() { return (VacuumEnvironment) env; } /** * Creates a 2D-graphics showing the agent in its environment. Locations * are represented as rectangles, dirt as grey ovals, and the agent as * red circle. */ @Override public void paint(java.awt.Graphics g) { List<String> locations = getLocations(); adjustTransformation(0, 0, 11 * locations.size() - 1, 10); java.awt.Graphics2D g2 = (java.awt.Graphics2D) g; g2.setColor(Color.white); g2.fillRect(0, 0, getWidth(), getHeight()); for (int i = 0; i < locations.size(); i++) { String location = locations.get(i); Agent agent = getAgent(location); if (isDirty(location)) { g2.setColor(Color.LIGHT_GRAY); g2.fillRect(x(11 * i), y(0), scale(10), scale(10)); } g2.setColor(Color.black); g2.drawRect(x(11 * i), y(0), scale(10), scale(10)); g2.drawString(location.toString(), x(11 * i) + 10, y(0) + 20); if (agent != null) { Action action = lastActions.get(agent); g2.setColor(Color.red); if (action == null || !((DynamicAction) action).getAttribute("name").equals("Suck")) g2.fillArc(x(11 * i + 2), y(2), scale(6), scale(6), 200, 320); else g2.fillOval(x(11 * i + 2), y(2), scale(6), scale(6)); } } } /** Returns the names of all locations used. */ protected List<String> getLocations() { List<String> result = new ArrayList<String>(); if (env != null) { result.add(VacuumEnvironment.LOCATION_A); result.add(VacuumEnvironment.LOCATION_B); } return result; } /** Checks whether the specified location is dirty. */ protected boolean isDirty(String location) { return VacuumEnvironment.LocationState.Dirty == getVacuumEnv() .getLocationState(location); } /** * Checks whether an agent is currently at the specified location and * returns one of them if any. * */ protected Agent getAgent(Object location) { VacuumEnvironment e = getVacuumEnv(); for (Agent a : e.getAgents()) if (location.equals(e.getAgentLocation(a))) return a; return null; } }
aima-gui/src/main/java/aima/gui/applications/vacuum/VacuumView.java
package aima.gui.applications.vacuum; import java.awt.Color; import java.util.ArrayList; import java.util.List; import aima.core.agent.Action; import aima.core.agent.Agent; import aima.core.agent.EnvironmentState; import aima.core.environment.vacuum.VacuumEnvironment; import aima.gui.framework.EmptyEnvironmentView; /** * Displays the informations provided by a <code>VacuumEnvironment</code> on a * panel using 2D-graphics. */ public class VacuumView extends EmptyEnvironmentView { @Override public void agentActed(Agent agent, Action action, EnvironmentState resultingState) { String prefix = ""; if (env.getAgents().size() > 1) prefix = "A" + env.getAgents().indexOf(agent) + ": "; super.agentActed(agent, action, resultingState); notify(prefix + action.toString()); } protected VacuumEnvironment getVacuumEnv() { return (VacuumEnvironment) env; } /** * Creates a 2D-graphics showing the agent in its environment. Locations * are represented as rectangles, dirt as grey ovals, and the agent as * red circle. */ @Override public void paint(java.awt.Graphics g) { List<String> locations = getLocations(); adjustTransformation(0, 0, 11 * locations.size() - 1, 10); java.awt.Graphics2D g2 = (java.awt.Graphics2D) g; g2.setColor(Color.white); g2.fillRect(0, 0, getWidth(), getHeight()); for (int i = 0; i < locations.size(); i++) { String location = locations.get(i); if (isDirty(location)) { g2.setColor(Color.LIGHT_GRAY); g2.fillRect(x(11 * i), y(0), scale(10), scale(10)); } g2.setColor(Color.black); g2.drawRect(x(11 * i), y(0), scale(10), scale(10)); g2.drawString(location.toString(), x(11 * i) + 10, y(0) + 20); if (hasAgent(location)) { g2.setColor(Color.red); g2.fillArc(x(11 * i + 2), y(2), scale(6), scale(6), 200, 320); } } } /** Returns the names of all locations used. */ protected List<String> getLocations() { List<String> result = new ArrayList<String>(); if (env != null) { result.add(VacuumEnvironment.LOCATION_A); result.add(VacuumEnvironment.LOCATION_B); } return result; } /** Checks whether the specified location is dirty. */ protected boolean isDirty(String location) { return VacuumEnvironment.LocationState.Dirty == getVacuumEnv() .getLocationState(location); } /** Checks whether the agent is currently at the specified location. */ protected boolean hasAgent(Object location) { VacuumEnvironment e = getVacuumEnv(); for (Agent a : e.getAgents()) if (location.equals(e.getAgentLocation(a))) return true; return false; } }
- vacuum cleaner symbol now animated
aima-gui/src/main/java/aima/gui/applications/vacuum/VacuumView.java
- vacuum cleaner symbol now animated
<ide><path>ima-gui/src/main/java/aima/gui/applications/vacuum/VacuumView.java <ide> <ide> import java.awt.Color; <ide> import java.util.ArrayList; <add>import java.util.Hashtable; <ide> import java.util.List; <ide> <ide> import aima.core.agent.Action; <ide> import aima.core.agent.Agent; <ide> import aima.core.agent.EnvironmentState; <add>import aima.core.agent.impl.DynamicAction; <ide> import aima.core.environment.vacuum.VacuumEnvironment; <ide> import aima.gui.framework.EmptyEnvironmentView; <ide> <ide> */ <ide> public class VacuumView extends EmptyEnvironmentView { <ide> <add> private Hashtable<Agent, Action> lastActions = new Hashtable<Agent, Action>(); <add> <ide> @Override <ide> public void agentActed(Agent agent, Action action, <ide> EnvironmentState resultingState) { <add> lastActions.put(agent, action); <ide> String prefix = ""; <ide> if (env.getAgents().size() > 1) <ide> prefix = "A" + env.getAgents().indexOf(agent) + ": "; <add> notify(prefix + action.toString()); <ide> super.agentActed(agent, action, resultingState); <del> notify(prefix + action.toString()); <ide> } <ide> <ide> protected VacuumEnvironment getVacuumEnv() { <ide> g2.fillRect(0, 0, getWidth(), getHeight()); <ide> for (int i = 0; i < locations.size(); i++) { <ide> String location = locations.get(i); <add> Agent agent = getAgent(location); <ide> if (isDirty(location)) { <ide> g2.setColor(Color.LIGHT_GRAY); <ide> g2.fillRect(x(11 * i), y(0), scale(10), scale(10)); <ide> g2.setColor(Color.black); <ide> g2.drawRect(x(11 * i), y(0), scale(10), scale(10)); <ide> g2.drawString(location.toString(), x(11 * i) + 10, y(0) + 20); <del> if (hasAgent(location)) { <add> if (agent != null) { <add> Action action = lastActions.get(agent); <ide> g2.setColor(Color.red); <del> g2.fillArc(x(11 * i + 2), y(2), scale(6), scale(6), <del> 200, 320); <add> if (action == null || !((DynamicAction) action).getAttribute("name").equals("Suck")) <add> g2.fillArc(x(11 * i + 2), y(2), scale(6), scale(6), <add> 200, 320); <add> else <add> g2.fillOval(x(11 * i + 2), y(2), scale(6), scale(6)); <ide> } <ide> } <ide> } <ide> .getLocationState(location); <ide> } <ide> <del> /** Checks whether the agent is currently at the specified location. */ <del> protected boolean hasAgent(Object location) { <add> /** <add> * Checks whether an agent is currently at the specified location and <add> * returns one of them if any. <add> * */ <add> protected Agent getAgent(Object location) { <ide> VacuumEnvironment e = getVacuumEnv(); <ide> for (Agent a : e.getAgents()) <ide> if (location.equals(e.getAgentLocation(a))) <del> return true; <del> return false; <add> return a; <add> return null; <ide> } <ide> } <ide>
Java
apache-2.0
6de7e9f48f1c6f3929d2a157fcb21b327630eadd
0
IsuraD/identity-inbound-auth-oauth,darshanasbg/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth,wso2-extensions/identity-inbound-auth-oauth,IsuraD/identity-inbound-auth-oauth,darshanasbg/identity-inbound-auth-oauth
/* * Copyright (c) 2017, 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.openidconnect; import com.nimbusds.jose.Algorithm; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.PlainJWT; import org.apache.axiom.om.OMElement; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.Charsets; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.model.ClaimConfig; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.core.util.IdentityConfigParser; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCache; import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry; import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey; import org.wso2.carbon.identity.oauth.common.OAuthConstants; import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth2.IDTokenValidationFailureException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; import org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; import org.wso2.carbon.idp.mgt.IdentityProviderManager; import org.wso2.carbon.user.core.UserStoreException; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.util.UserCoreUtil; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import javax.xml.namespace.QName; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OIDCClaims.AT_HASH; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OIDCClaims.AUTH_TIME; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OIDCClaims.AZP; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OIDCClaims.NONCE; /** * Default IDToken generator for the OpenID Connect Implementation. * This IDToken Generator utilizes the Nimbus SDK to build the IDToken. */ public class DefaultIDTokenBuilder implements org.wso2.carbon.identity.openidconnect.IDTokenBuilder { private static final String SHA384 = "SHA-384"; private static final String SHA512 = "SHA-512"; private static final String AUTHORIZATION_CODE = "AuthorizationCode"; private static final String INBOUND_AUTH2_TYPE = "oauth2"; private static final String CONFIG_ELEM_OAUTH = "OAuth"; private static final String OPENID_CONNECT = "OpenIDConnect"; private static final String OPENID_CONNECT_AUDIENCES = "Audiences"; private static final String OPENID_CONNECT_AUDIENCE = "Audience"; private static final String OPENID_IDP_ENTITY_ID = "IdPEntityId"; private static final Log log = LogFactory.getLog(DefaultIDTokenBuilder.class); private JWSAlgorithm signatureAlgorithm = null; public DefaultIDTokenBuilder() throws IdentityOAuth2Exception { //map signature algorithm from identity.xml to nimbus format, this is a one time configuration signatureAlgorithm = OAuth2Util.mapSignatureAlgorithmForJWSAlgorithm( OAuthServerConfiguration.getInstance().getIdTokenSignatureAlgorithm()); } @Override public String buildIDToken(OAuthTokenReqMessageContext tokenReqMsgCtxt, OAuth2AccessTokenRespDTO tokenRespDTO) throws IdentityOAuth2Exception { String clientId = tokenReqMsgCtxt.getOauth2AccessTokenReqDTO().getClientId(); String spTenantDomain = getSpTenantDomain(tokenReqMsgCtxt); String idTokenIssuer = getIdTokenIssuer(spTenantDomain); long idTokenValidityInMillis = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenExpiryTimeInMillis(); long currentTimeInMillis = Calendar.getInstance().getTimeInMillis(); AuthenticatedUser authorizedUser = tokenReqMsgCtxt.getAuthorizedUser(); String subjectClaim = getSubjectClaim(tokenReqMsgCtxt, clientId, spTenantDomain, authorizedUser); String nonceValue = null; long authTime = 0; LinkedHashSet acrValue = new LinkedHashSet(); // AuthorizationCode only available for authorization code grant type if (getAuthorizationCode(tokenReqMsgCtxt) != null) { AuthorizationGrantCacheEntry authorizationGrantCacheEntry = getAuthorizationGrantCacheEntry(tokenReqMsgCtxt); if (authorizationGrantCacheEntry != null) { nonceValue = authorizationGrantCacheEntry.getNonceValue(); acrValue = authorizationGrantCacheEntry.getAcrValue(); if (authorizationGrantCacheEntry.getEssentialClaims() != null) { if (isEssentialClaim(authorizationGrantCacheEntry, AUTH_TIME)) { authTime = authorizationGrantCacheEntry.getAuthTime(); } } } } String atHash = null; String accessToken = tokenRespDTO.getAccessToken(); if (isIDTokenSigned()) { atHash = getAtHash(accessToken); } if (log.isDebugEnabled()) { log.debug(buildDebugMessage(idTokenIssuer, subjectClaim, nonceValue, idTokenValidityInMillis, currentTimeInMillis)); } List<String> audience = getOIDCAudience(clientId); JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(idTokenIssuer); jwtClaimsSet.setAudience(audience); jwtClaimsSet.setClaim(AZP, clientId); jwtClaimsSet.setExpirationTime(getIdTokenExpiryInMillis(idTokenValidityInMillis, currentTimeInMillis)); jwtClaimsSet.setIssueTime(new Date(currentTimeInMillis)); if (authTime != 0) { jwtClaimsSet.setClaim(AUTH_TIME, authTime / 1000); } if (atHash != null) { jwtClaimsSet.setClaim(AT_HASH, atHash); } if (nonceValue != null) { jwtClaimsSet.setClaim(NONCE, nonceValue); } if (acrValue != null) { jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.ACR, "urn:mace:incommon:iap:silver"); } tokenReqMsgCtxt.addProperty(OAuthConstants.ACCESS_TOKEN, accessToken); tokenReqMsgCtxt.addProperty(MultitenantConstants.TENANT_DOMAIN, getSpTenantDomain(tokenReqMsgCtxt)); handleOIDCCustomClaims(tokenReqMsgCtxt, jwtClaimsSet); jwtClaimsSet.setSubject(subjectClaim); if (isInvalidToken(jwtClaimsSet)) { throw new IDTokenValidationFailureException("Error while validating ID Token token for required claims"); } if (isIDTokenNotSigned()) { return new PlainJWT(jwtClaimsSet).serialize(); } String signingTenantDomain = getSigningTenantDomain(tokenReqMsgCtxt); return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); } @Override public String buildIDToken(OAuthAuthzReqMessageContext authzReqMessageContext, OAuth2AuthorizeRespDTO tokenRespDTO) throws IdentityOAuth2Exception { String accessToken = tokenRespDTO.getAccessToken(); String clientId = authzReqMessageContext.getAuthorizationReqDTO().getConsumerKey(); String spTenantDomain = getSpTenantDomain(authzReqMessageContext); String issuer = getIdTokenIssuer(spTenantDomain); // Get subject from Authenticated Subject Identifier AuthenticatedUser authorizedUser = authzReqMessageContext.getAuthorizationReqDTO().getUser(); String subject = getSubjectClaim(authzReqMessageContext, clientId, spTenantDomain, authorizedUser); String nonceValue = authzReqMessageContext.getAuthorizationReqDTO().getNonce(); LinkedHashSet acrValue = authzReqMessageContext.getAuthorizationReqDTO().getACRValues(); long idTokenLifeTimeInMillis = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenExpiryTimeInMillis(); long currentTimeInMillis = Calendar.getInstance().getTimeInMillis(); if (log.isDebugEnabled()) { log.debug(buildDebugMessage(issuer, subject, nonceValue, idTokenLifeTimeInMillis, currentTimeInMillis)); } JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(issuer); // Set the audience List<String> audience = getOIDCAudience(clientId); jwtClaimsSet.setAudience(audience); jwtClaimsSet.setClaim(AZP, clientId); jwtClaimsSet.setExpirationTime(getIdTokenExpiryInMillis(idTokenLifeTimeInMillis, currentTimeInMillis)); jwtClaimsSet.setIssueTime(new Date(currentTimeInMillis)); long authTime = getAuthTime(authzReqMessageContext, accessToken); if (authTime != 0) { jwtClaimsSet.setClaim(AUTH_TIME, authTime / 1000); } String responseType = authzReqMessageContext.getAuthorizationReqDTO().getResponseType(); String atHash = null; if (isIDTokenSigned() && isAccessTokenHashApplicable(responseType)) { atHash = getAtHash(accessToken); } if (atHash != null) { jwtClaimsSet.setClaim(AT_HASH, atHash); } if (nonceValue != null) { jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.NONCE, nonceValue); } if (acrValue != null) { jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.ACR, "urn:mace:incommon:iap:silver"); } authzReqMessageContext.addProperty(OAuthConstants.ACCESS_TOKEN, accessToken); authzReqMessageContext.addProperty(MultitenantConstants.TENANT_DOMAIN, getSpTenantDomain(authzReqMessageContext)); handleCustomOIDCClaims(authzReqMessageContext, jwtClaimsSet); jwtClaimsSet.setSubject(subject); if (isIDTokenNotSigned()) { return new PlainJWT(jwtClaimsSet).serialize(); } String signingTenantDomain = getSigningTenantDomain(authzReqMessageContext); return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); } protected String getSubjectClaim(OAuthTokenReqMessageContext tokenReqMessageContext, String clientId, String spTenantDomain, AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { return getSubjectClaim(clientId, spTenantDomain, authorizedUser); } protected String getSubjectClaim(OAuthAuthzReqMessageContext authzReqMessageContext, String clientId, String spTenantDomain, AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { return getSubjectClaim(clientId, spTenantDomain, authorizedUser); } private String getSubjectClaim(String clientId, String spTenantDomain, AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { String subjectClaim; if (isLocalUser(authorizedUser)) { // If the user is local then we need to find the subject claim of the user defined in SP configs and // append userStoreDomain/tenantDomain as configured ServiceProvider serviceProvider = getServiceProvider(spTenantDomain, clientId); if (serviceProvider == null) { throw new IdentityOAuth2Exception("Cannot find an service provider for client_id: " + clientId + " " + "in tenantDomain: " + spTenantDomain); } subjectClaim = getSubjectClaimForLocalUser(serviceProvider, authorizedUser); if (log.isDebugEnabled()) { log.debug("Subject claim: " + subjectClaim + " set for local user: " + authorizedUser + " for " + "application: " + clientId + " of tenantDomain: " + spTenantDomain); } } else { subjectClaim = authorizedUser.getAuthenticatedSubjectIdentifier(); if (log.isDebugEnabled()) { log.debug("Subject claim: " + subjectClaim + " set for federated user: " + authorizedUser + " for " + "application: " + clientId + " of tenantDomain: " + spTenantDomain); } } return subjectClaim; } private String buildDebugMessage(String issuer, String subject, String nonceValue, long idTokenLifeTimeInMillis, long currentTimeInMillis) { return (new StringBuilder()) .append("Using issuer ").append(issuer).append("\n") .append("Subject ").append(subject).append("\n") .append("ID Token life time ").append(idTokenLifeTimeInMillis / 1000).append("\n") .append("Current time ").append(currentTimeInMillis / 1000).append("\n") .append("Nonce Value ").append(nonceValue).append("\n") .append("Signature Algorithm ").append(signatureAlgorithm).append("\n") .toString(); } private boolean isInvalidToken(JWTClaimsSet jwtClaimsSet) { return !isValidIdToken(jwtClaimsSet); } private boolean isEssentialClaim(AuthorizationGrantCacheEntry authorizationGrantCacheEntry, String oidcClaimUri) { return OAuth2Util.getEssentialClaims(authorizationGrantCacheEntry.getEssentialClaims(), OAuthConstants.ID_TOKEN) .contains(oidcClaimUri); } private boolean isIDTokenNotSigned() { return JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()); } private boolean isIDTokenSigned() { return !JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()); } private String getAuthorizationCode(OAuthTokenReqMessageContext tokenReqMsgCtxt) { return (String) tokenReqMsgCtxt.getProperty(AUTHORIZATION_CODE); } private boolean isLocalUser(AuthenticatedUser authorizedUser) { return !authorizedUser.isFederatedUser(); } private String getSpTenantDomain(OAuthTokenReqMessageContext tokReqMsgCtx) { return tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain(); } private void handleOIDCCustomClaims(OAuthTokenReqMessageContext tokReqMsgCtx, JWTClaimsSet jwtClaimsSet) { CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance().getOpenIDConnectCustomClaimsCallbackHandler(); claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, tokReqMsgCtx); } private String getSubjectClaimForLocalUser(ServiceProvider serviceProvider, AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { String subject; String username = authorizedUser.getUserName(); String userStoreDomain = authorizedUser.getUserStoreDomain(); String userTenantDomain = authorizedUser.getTenantDomain(); String subjectClaimUri = getSubjectClaimUriInLocalDialect(serviceProvider); if (subjectClaimUri != null) { String fullQualifiedUsername = authorizedUser.toFullQualifiedUsername(); try { subject = getSubjectClaimFromUserStore(subjectClaimUri, authorizedUser); if (StringUtils.isBlank(subject)) { // Set username as the subject claim since we have no other option subject = username; log.warn("Cannot find subject claim: " + subjectClaimUri + " for user:" + fullQualifiedUsername + ". Defaulting to username: " + subject + " as the subject identifier."); } // Get the subject claim in the correct format (ie. tenantDomain or userStoreDomain appended) subject = getFormattedSubjectClaim(serviceProvider, subject, userStoreDomain, userTenantDomain); } catch (IdentityException e) { String error = "Error occurred while getting user claim for user: " + authorizedUser + ", claim: " + subjectClaimUri; throw new IdentityOAuth2Exception(error, e); } catch (UserStoreException e) { String error = "Error occurred while getting subject claim: " + subjectClaimUri + " for user: " + fullQualifiedUsername; throw new IdentityOAuth2Exception(error, e); } } else { subject = getFormattedSubjectClaim(serviceProvider, username, userStoreDomain, userTenantDomain); if (log.isDebugEnabled()) { log.debug("No subject claim defined for service provider: " + serviceProvider.getApplicationName() + ". Using username as the subject claim."); } } return subject; } private String getSubjectClaimFromUserStore(String subjectClaimUri, AuthenticatedUser authenticatedUser) throws UserStoreException, IdentityException { UserStoreManager userStoreManager = IdentityTenantUtil .getRealm(authenticatedUser.getTenantDomain(), authenticatedUser.toFullQualifiedUsername()) .getUserStoreManager(); return userStoreManager .getSecondaryUserStoreManager(authenticatedUser.getUserStoreDomain()) .getUserClaimValue(authenticatedUser.getUserName(), subjectClaimUri, null); } private String getSubjectClaimUriInLocalDialect(ServiceProvider serviceProvider) { String subjectClaimUri = serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSubjectClaimUri(); if (log.isDebugEnabled()) { if (StringUtils.isNotBlank(subjectClaimUri)) { log.debug(subjectClaimUri + " is defined as subject claim for service provider: " + serviceProvider.getApplicationName()); } else { log.debug("No subject claim defined for service provider: " + serviceProvider.getApplicationName()); } } // Get the local subject claim URI, if subject claim was a SP mapped one return getSubjectClaimUriInLocalDialect(serviceProvider, subjectClaimUri); } private String getFormattedSubjectClaim(ServiceProvider serviceProvider, String subjectClaimValue, String userStoreDomain, String tenantDomain) { boolean appendUserStoreDomainToSubjectClaim = serviceProvider.getLocalAndOutBoundAuthenticationConfig() .isUseUserstoreDomainInLocalSubjectIdentifier(); boolean appendTenantDomainToSubjectClaim = serviceProvider.getLocalAndOutBoundAuthenticationConfig() .isUseTenantDomainInLocalSubjectIdentifier(); if (appendTenantDomainToSubjectClaim) { subjectClaimValue = UserCoreUtil.addTenantDomainToEntry(subjectClaimValue, tenantDomain); } if (appendUserStoreDomainToSubjectClaim) { subjectClaimValue = IdentityUtil.addDomainToName(subjectClaimValue, userStoreDomain); } return subjectClaimValue; } private String getSigningTenantDomain(OAuthTokenReqMessageContext tokReqMsgCtx) { boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); if (isJWTSignedWithSPKey) { return (String) tokReqMsgCtx.getProperty(MultitenantConstants.TENANT_DOMAIN); } else { return tokReqMsgCtx.getAuthorizedUser().getTenantDomain(); } } private String getSubjectClaimUriInLocalDialect(ServiceProvider serviceProvider, String subjectClaimUri) { if (StringUtils.isNotBlank(subjectClaimUri)) { ClaimConfig claimConfig = serviceProvider.getClaimConfig(); if (claimConfig != null) { boolean isLocalClaimDialect = claimConfig.isLocalClaimDialect(); ClaimMapping[] claimMappings = claimConfig.getClaimMappings(); if (!isLocalClaimDialect && ArrayUtils.isNotEmpty(claimMappings)) { for (ClaimMapping claimMapping : claimMappings) { if (StringUtils.equals(claimMapping.getRemoteClaim().getClaimUri(), subjectClaimUri)) { return claimMapping.getLocalClaim().getClaimUri(); } } } } } // This means the original subjectClaimUri passed was the subject claim URI. return subjectClaimUri; } private List<String> getOIDCAudience(String clientId) { List<String> oidcAudiences = getDefinedCustomOIDCAudiences(); // Need to add client_id as an audience value according to the spec. oidcAudiences.add(clientId); return oidcAudiences; } private String getAtHash(String accessToken) throws IdentityOAuth2Exception { String digAlg = OAuth2Util.mapDigestAlgorithm(signatureAlgorithm); MessageDigest md; try { md = MessageDigest.getInstance(digAlg); } catch (NoSuchAlgorithmException e) { throw new IdentityOAuth2Exception("Error creating the at_hash value. Invalid Digest Algorithm: " + digAlg); } md.update(accessToken.getBytes(Charsets.UTF_8)); byte[] digest = md.digest(); int leftHalfBytes = 16; if (SHA384.equals(digAlg)) { leftHalfBytes = 24; } else if (SHA512.equals(digAlg)) { leftHalfBytes = 32; } byte[] leftmost = new byte[leftHalfBytes]; System.arraycopy(digest, 0, leftmost, 0, leftHalfBytes); return new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8); } private ServiceProvider getServiceProvider(String spTenantDomain, String clientId) throws IdentityOAuth2Exception { ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService(); try { String spName = applicationMgtService.getServiceProviderNameByClientId(clientId, INBOUND_AUTH2_TYPE, spTenantDomain); return applicationMgtService.getApplicationExcludingFileBasedSPs(spName, spTenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception("Error while getting service provider information for client_id: " + clientId + " tenantDomain: " + spTenantDomain, e); } } private String getIdTokenIssuer(String tenantDomain) throws IdentityOAuth2Exception { IdentityProvider identityProvider = getResidentIdp(tenantDomain); FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs(); // Get OIDC authenticator FederatedAuthenticatorConfig oidcAuthenticatorConfig = IdentityApplicationManagementUtil.getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME); return IdentityApplicationManagementUtil.getProperty(oidcAuthenticatorConfig.getProperties(), OPENID_IDP_ENTITY_ID).getValue(); } private long getAuthTime(OAuthAuthzReqMessageContext authzReqMessageContext, String accessToken) { long authTime = 0; if (StringUtils.isNotEmpty(accessToken)) { AuthorizationGrantCacheEntry authorizationGrantCacheEntry = getAuthorizationGrantCacheEntry(accessToken); if (StringUtils.isNotBlank(authorizationGrantCacheEntry.getEssentialClaims())) { if (isEssentialClaim(authorizationGrantCacheEntry, AUTH_TIME)) { authTime = authzReqMessageContext.getAuthorizationReqDTO().getAuthTime(); } } } return authTime; } private boolean isAccessTokenHashApplicable(String responseType) { // At_hash is generated on an access token. Therefore check whether the response type returns an access_token. // id_token and none response types don't return and access token return !OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType) && !OAuthConstants.NONE.equalsIgnoreCase(responseType); } private Date getIdTokenExpiryInMillis(long currentTimeInMillis, long lifetimeInMillis) { return new Date(currentTimeInMillis + lifetimeInMillis); } private void handleCustomOIDCClaims(OAuthAuthzReqMessageContext request, JWTClaimsSet jwtClaimsSet) { CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance().getOpenIDConnectCustomClaimsCallbackHandler(); claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request); } private String getSpTenantDomain(OAuthAuthzReqMessageContext request) { return request.getAuthorizationReqDTO().getTenantDomain(); } private String getSigningTenantDomain(OAuthAuthzReqMessageContext request) { boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); String signingTenantDomain; if (isJWTSignedWithSPKey) { signingTenantDomain = (String) request.getProperty(MultitenantConstants.TENANT_DOMAIN); } else { signingTenantDomain = request.getAuthorizationReqDTO().getUser().getTenantDomain(); } return signingTenantDomain; } /** * sign JWT token from RSA algorithm * * @param jwtClaimsSet contains JWT body * @param tokenReqMessageContext * @return signed JWT token * @throws IdentityOAuth2Exception */ @Deprecated protected String signJWTWithRSA(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext tokenReqMessageContext) throws IdentityOAuth2Exception { String tenantDomain = getSigningTenantDomain(tokenReqMessageContext); return OAuth2Util.signJWTWithRSA(jwtClaimsSet, signatureAlgorithm, tenantDomain).serialize(); } /** * sign JWT token from RSA algorithm * * @param jwtClaimsSet contains JWT body * @param authzReqMessageContext * @return signed JWT token * @throws IdentityOAuth2Exception */ @Deprecated protected String signJWTWithRSA(JWTClaimsSet jwtClaimsSet, OAuthAuthzReqMessageContext authzReqMessageContext) throws IdentityOAuth2Exception { String signingTenantDomain = getSigningTenantDomain(authzReqMessageContext); return OAuth2Util.signJWTWithRSA(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); } /** * @param request * @return AuthorizationGrantCacheEntry contains user attributes and nonce value */ private AuthorizationGrantCacheEntry getAuthorizationGrantCacheEntry(OAuthTokenReqMessageContext request) { String authorizationCode = getAuthorizationCode(request); AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(authorizationCode); return AuthorizationGrantCache.getInstance().getValueFromCacheByCode(authorizationGrantCacheKey); } private AuthorizationGrantCacheEntry getAuthorizationGrantCacheEntry(String accessToken) { AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(accessToken); return AuthorizationGrantCache.getInstance().getValueFromCacheByToken(authorizationGrantCacheKey); } /** * Generic Signing function * * @param jwtClaimsSet contains JWT body * @param tokenMsgContext * @return signed JWT token * @throws IdentityOAuth2Exception */ @Deprecated protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext tokenMsgContext) throws IdentityOAuth2Exception { if (isRSA(signatureAlgorithm)) { return signJWTWithRSA(jwtClaimsSet, tokenMsgContext); } else if (isHMAC(signatureAlgorithm)) { // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done return null; } else { // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done return null; } } private boolean isRSA(JWSAlgorithm signatureAlgorithm) { return JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) || JWSAlgorithm.RS512.equals(signatureAlgorithm); } /** * Generic Signing function * * @param jwtClaimsSet contains JWT body * @param authzReqMessageContext * @return signed JWT token * @throah ws IdentityOAuth2Exception */ @Deprecated protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthAuthzReqMessageContext authzReqMessageContext) throws IdentityOAuth2Exception { if (isRSA(signatureAlgorithm)) { return signJWTWithRSA(jwtClaimsSet, authzReqMessageContext); } else if (isHMAC(signatureAlgorithm)) { // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done return null; } else { // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done return null; } } private boolean isHMAC(JWSAlgorithm signatureAlgorithm) { return JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) || JWSAlgorithm.HS512.equals(signatureAlgorithm); } /** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * format, Strings are defined inline hence there are not being used any * where * * @param signatureAlgorithm signature algorithm * @return mapped JWSAlgorithm * @throws IdentityOAuth2Exception */ @Deprecated protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { return OAuth2Util.mapSignatureAlgorithmForJWSAlgorithm(signatureAlgorithm); } /** * This method maps signature algorithm define in identity.xml to digest algorithms to generate the at_hash * * @param signatureAlgorithm signature algorithm * @return mapped digest algorithm * @throws IdentityOAuth2Exception */ @Deprecated protected String mapDigestAlgorithm(Algorithm signatureAlgorithm) throws IdentityOAuth2Exception { return OAuth2Util.mapDigestAlgorithm(signatureAlgorithm); } private List<String> getDefinedCustomOIDCAudiences() { List<String> audiences = new ArrayList<>(); IdentityConfigParser configParser = IdentityConfigParser.getInstance(); OMElement oauthElem = configParser.getConfigElement(CONFIG_ELEM_OAUTH); if (oauthElem == null) { warnOnFaultyConfiguration("<OAuth> configuration element is not available in identity.xml."); return audiences; } OMElement oidcConfig = oauthElem.getFirstChildWithName(getQNameWithIdentityNS(OPENID_CONNECT)); if (oidcConfig == null) { warnOnFaultyConfiguration("<OpenIDConnect> element is not available in identity.xml."); return audiences; } OMElement audienceConfig = oidcConfig.getFirstChildWithName(getQNameWithIdentityNS(OPENID_CONNECT_AUDIENCES)); if (audienceConfig == null) { return audiences; } Iterator iterator = audienceConfig.getChildrenWithName(getQNameWithIdentityNS(OPENID_CONNECT_AUDIENCE)); while (iterator.hasNext()) { OMElement supportedAudience = (OMElement) iterator.next(); String supportedAudienceName; if (supportedAudience != null) { supportedAudienceName = IdentityUtil.fillURLPlaceholders(supportedAudience.getText()); if (StringUtils.isNotBlank(supportedAudienceName)) { audiences.add(supportedAudienceName); } } } return audiences; } private void warnOnFaultyConfiguration(String logMsg) { log.warn("Error in OAuth Configuration: " + logMsg); } private QName getQNameWithIdentityNS(String localPart) { return new QName(IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE, localPart); } private IdentityProvider getResidentIdp(String tenantDomain) throws IdentityOAuth2Exception { try { return IdentityProviderManager.getInstance().getResidentIdP(tenantDomain); } catch (IdentityProviderManagementException e) { final String ERROR_GET_RESIDENT_IDP = "Error while getting Resident Identity Provider of '%s' tenant."; String errorMsg = String.format(ERROR_GET_RESIDENT_IDP, tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } } /** * Method to check whether id token contains the required claims(iss,sub,aud,exp,iat) defined by the oidc spec * * @param jwtClaimsSet jwt claim set * @return true or false(whether id token contains the required claims) */ private boolean isValidIdToken(JWTClaimsSet jwtClaimsSet) { if (StringUtils.isBlank(jwtClaimsSet.getIssuer())) { log.error("ID token does not have required issuer claim"); return false; } if (StringUtils.isBlank(jwtClaimsSet.getSubject())) { log.error("ID token does not have required subject claim"); return false; } if (jwtClaimsSet.getAudience() == null) { log.error("ID token does not have required audience claim"); return false; } if (jwtClaimsSet.getExpirationTime() == null) { log.error("ID token does not have required expiration time claim"); return false; } if (jwtClaimsSet.getIssueTime() == null) { log.error("ID token does not have required issued time claim"); return false; } // All mandatory claims are present. return true; } }
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/openidconnect/DefaultIDTokenBuilder.java
/* * Copyright (c) 2017, 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.openidconnect; import com.nimbusds.jose.Algorithm; import com.nimbusds.jose.JWSAlgorithm; import com.nimbusds.jwt.JWTClaimsSet; import com.nimbusds.jwt.PlainJWT; import org.apache.axiom.om.OMElement; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.Charsets; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.identity.application.authentication.framework.model.AuthenticatedUser; import org.wso2.carbon.identity.application.common.IdentityApplicationManagementException; import org.wso2.carbon.identity.application.common.model.ClaimConfig; import org.wso2.carbon.identity.application.common.model.ClaimMapping; import org.wso2.carbon.identity.application.common.model.FederatedAuthenticatorConfig; import org.wso2.carbon.identity.application.common.model.IdentityProvider; import org.wso2.carbon.identity.application.common.model.ServiceProvider; import org.wso2.carbon.identity.application.common.util.IdentityApplicationConstants; import org.wso2.carbon.identity.application.common.util.IdentityApplicationManagementUtil; import org.wso2.carbon.identity.application.mgt.ApplicationManagementService; import org.wso2.carbon.identity.base.IdentityException; import org.wso2.carbon.identity.core.util.IdentityConfigParser; import org.wso2.carbon.identity.core.util.IdentityCoreConstants; import org.wso2.carbon.identity.core.util.IdentityTenantUtil; import org.wso2.carbon.identity.core.util.IdentityUtil; import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCache; import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheEntry; import org.wso2.carbon.identity.oauth.cache.AuthorizationGrantCacheKey; import org.wso2.carbon.identity.oauth.common.OAuthConstants; import org.wso2.carbon.identity.oauth.config.OAuthServerConfiguration; import org.wso2.carbon.identity.oauth2.IDTokenValidationFailureException; import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception; import org.wso2.carbon.identity.oauth2.authz.OAuthAuthzReqMessageContext; import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenRespDTO; import org.wso2.carbon.identity.oauth2.dto.OAuth2AuthorizeRespDTO; import org.wso2.carbon.identity.oauth2.internal.OAuth2ServiceComponentHolder; import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext; import org.wso2.carbon.identity.oauth2.util.OAuth2Util; import org.wso2.carbon.idp.mgt.IdentityProviderManagementException; import org.wso2.carbon.idp.mgt.IdentityProviderManager; import org.wso2.carbon.user.core.UserStoreException; import org.wso2.carbon.user.core.UserStoreManager; import org.wso2.carbon.user.core.util.UserCoreUtil; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import javax.xml.namespace.QName; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OIDCClaims.AT_HASH; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OIDCClaims.AUTH_TIME; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OIDCClaims.AZP; import static org.wso2.carbon.identity.oauth.common.OAuthConstants.OIDCClaims.NONCE; /** * Default IDToken generator for the OpenID Connect Implementation. * This IDToken Generator utilizes the Nimbus SDK to build the IDToken. */ public class DefaultIDTokenBuilder implements org.wso2.carbon.identity.openidconnect.IDTokenBuilder { private static final String SHA384 = "SHA-384"; private static final String SHA512 = "SHA-512"; private static final String AUTHORIZATION_CODE = "AuthorizationCode"; private static final String INBOUND_AUTH2_TYPE = "oauth2"; private static final String CONFIG_ELEM_OAUTH = "OAuth"; private static final String OPENID_CONNECT = "OpenIDConnect"; private static final String OPENID_CONNECT_AUDIENCES = "Audiences"; private static final String OPENID_CONNECT_AUDIENCE = "Audience"; private static final String OPENID_IDP_ENTITY_ID = "IdPEntityId"; private static final Log log = LogFactory.getLog(DefaultIDTokenBuilder.class); private JWSAlgorithm signatureAlgorithm = null; public DefaultIDTokenBuilder() throws IdentityOAuth2Exception { //map signature algorithm from identity.xml to nimbus format, this is a one time configuration signatureAlgorithm = OAuth2Util.mapSignatureAlgorithmForJWSAlgorithm( OAuthServerConfiguration.getInstance().getIdTokenSignatureAlgorithm()); } @Override public String buildIDToken(OAuthTokenReqMessageContext tokenReqMsgCtxt, OAuth2AccessTokenRespDTO tokenRespDTO) throws IdentityOAuth2Exception { String clientId = tokenReqMsgCtxt.getOauth2AccessTokenReqDTO().getClientId(); String spTenantDomain = getSpTenantDomain(tokenReqMsgCtxt); String idTokenIssuer = getIdTokenIssuer(spTenantDomain); long idTokenLifeTimeInMillis = getIdTokenValidityInMillis(); long currentTimeInMillis = Calendar.getInstance().getTimeInMillis(); AuthenticatedUser authorizedUser = tokenReqMsgCtxt.getAuthorizedUser(); String subjectClaim = getSubjectClaim(clientId, spTenantDomain, authorizedUser); String nonceValue = null; long authTime = 0; LinkedHashSet acrValue = new LinkedHashSet(); // AuthorizationCode only available for authorization code grant type if (getAuthorizationCode(tokenReqMsgCtxt) != null) { AuthorizationGrantCacheEntry authorizationGrantCacheEntry = getAuthorizationGrantCacheEntry(tokenReqMsgCtxt); if (authorizationGrantCacheEntry != null) { nonceValue = authorizationGrantCacheEntry.getNonceValue(); acrValue = authorizationGrantCacheEntry.getAcrValue(); if (authorizationGrantCacheEntry.getEssentialClaims() != null) { if (isEssentialClaim(authorizationGrantCacheEntry, AUTH_TIME)) { authTime = authorizationGrantCacheEntry.getAuthTime(); } } } } String atHash = null; String accessToken = tokenRespDTO.getAccessToken(); if (isIDTokenSigned()) { atHash = getAtHash(accessToken); } if (log.isDebugEnabled()) { StringBuilder stringBuilder = (new StringBuilder()) .append("Using issuer: ").append(idTokenIssuer).append("\n") .append("Subject: ").append(subjectClaim).append("\n") .append("Current time: ").append(currentTimeInMillis / 1000).append("\n") .append("ID Token life time: ").append(idTokenLifeTimeInMillis / 1000).append("\n") .append("Nonce Value: ").append(nonceValue).append("\n") .append("Signature Algorithm ").append(signatureAlgorithm).append("\n"); log.debug(stringBuilder.toString()); } List<String> audience = getOIDCAudience(clientId); JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(idTokenIssuer); jwtClaimsSet.setAudience(audience); jwtClaimsSet.setClaim(AZP, clientId); jwtClaimsSet.setExpirationTime(getIdTokenExpiryInMillis(idTokenLifeTimeInMillis, currentTimeInMillis)); jwtClaimsSet.setIssueTime(new Date(currentTimeInMillis)); if (authTime != 0) { jwtClaimsSet.setClaim(AUTH_TIME, authTime / 1000); } if (atHash != null) { jwtClaimsSet.setClaim(AT_HASH, atHash); } if (nonceValue != null) { jwtClaimsSet.setClaim(NONCE, nonceValue); } if (acrValue != null) { jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.ACR, "urn:mace:incommon:iap:silver"); } tokenReqMsgCtxt.addProperty(OAuthConstants.ACCESS_TOKEN, accessToken); tokenReqMsgCtxt.addProperty(MultitenantConstants.TENANT_DOMAIN, getSpTenantDomain(tokenReqMsgCtxt)); handleOIDCCustomClaims(tokenReqMsgCtxt, jwtClaimsSet); jwtClaimsSet.setSubject(subjectClaim); if (isInvalidToken(jwtClaimsSet)) { throw new IDTokenValidationFailureException("Error while validating ID Token token for required claims"); } if (isIDTokenNotSigned()) { return new PlainJWT(jwtClaimsSet).serialize(); } String signingTenantDomain = getSigningTenantDomain(tokenReqMsgCtxt); return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); } private boolean isInvalidToken(JWTClaimsSet jwtClaimsSet) { return !isValidIdToken(jwtClaimsSet); } private long getIdTokenValidityInMillis() { return OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenExpiryTimeInMillis(); } private boolean isEssentialClaim(AuthorizationGrantCacheEntry authorizationGrantCacheEntry, String oidcClaimUri) { return OAuth2Util.getEssentialClaims(authorizationGrantCacheEntry.getEssentialClaims(), OAuthConstants.ID_TOKEN) .contains(oidcClaimUri); } private boolean isIDTokenNotSigned() { return JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()); } private boolean isIDTokenSigned() { return !JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()); } private String getSubjectClaim(String clientId, String spTenantDomain, AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { String subjectClaim; if (isLocalUser(authorizedUser)) { // If the user is local then we need to find the subject claim of the user defined in SP configs and // append userStoreDomain/tenantDomain as configured ServiceProvider serviceProvider = getServiceProvider(spTenantDomain, clientId); if (serviceProvider == null) { throw new IdentityOAuth2Exception("Cannot find an service provider for client_id: " + clientId + " " + "in tenantDomain: " + spTenantDomain); } subjectClaim = getSubjectClaimForLocalUser(serviceProvider, authorizedUser); if (log.isDebugEnabled()) { log.debug("Subject claim: " + subjectClaim + " set for local user: " + authorizedUser + " for " + "application: " + clientId + " of tenantDomain: " + spTenantDomain); } } else { subjectClaim = authorizedUser.getAuthenticatedSubjectIdentifier(); if (log.isDebugEnabled()) { log.debug("Subject claim: " + subjectClaim + " set for federated user: " + authorizedUser + " for " + "application: " + clientId + " of tenantDomain: " + spTenantDomain); } } return subjectClaim; } private String getAuthorizationCode(OAuthTokenReqMessageContext tokenReqMsgCtxt) { return (String) tokenReqMsgCtxt.getProperty(AUTHORIZATION_CODE); } private boolean isLocalUser(AuthenticatedUser authorizedUser) { return !authorizedUser.isFederatedUser(); } private String getSpTenantDomain(OAuthTokenReqMessageContext tokReqMsgCtx) { return tokReqMsgCtx.getOauth2AccessTokenReqDTO().getTenantDomain(); } private void handleOIDCCustomClaims(OAuthTokenReqMessageContext tokReqMsgCtx, JWTClaimsSet jwtClaimsSet) { CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance().getOpenIDConnectCustomClaimsCallbackHandler(); claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, tokReqMsgCtx); } private String getSubjectClaimForLocalUser(ServiceProvider serviceProvider, AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { String subject; String username = authorizedUser.getUserName(); String userStoreDomain = authorizedUser.getUserStoreDomain(); String userTenantDomain = authorizedUser.getTenantDomain(); String subjectClaimUri = getSubjectClaimUriInLocalDialect(serviceProvider); if (subjectClaimUri != null) { String fullQualifiedUsername = authorizedUser.toFullQualifiedUsername(); try { subject = getSubjectClaimFromUserStore(subjectClaimUri, authorizedUser); if (StringUtils.isBlank(subject)) { // Set username as the subject claim since we have no other option subject = username; log.warn("Cannot find subject claim: " + subjectClaimUri + " for user:" + fullQualifiedUsername + ". Defaulting to username: " + subject + " as the subject identifier."); } // Get the subject claim in the correct format (ie. tenantDomain or userStoreDomain appended) subject = getFormattedSubjectClaim(serviceProvider, subject, userStoreDomain, userTenantDomain); } catch (IdentityException e) { String error = "Error occurred while getting user claim for user: " + authorizedUser + ", claim: " + subjectClaimUri; throw new IdentityOAuth2Exception(error, e); } catch (UserStoreException e) { String error = "Error occurred while getting subject claim: " + subjectClaimUri + " for user: " + fullQualifiedUsername; throw new IdentityOAuth2Exception(error, e); } } else { subject = getFormattedSubjectClaim(serviceProvider, username, userStoreDomain, userTenantDomain); if (log.isDebugEnabled()) { log.debug("No subject claim defined for service provider: " + serviceProvider.getApplicationName() + ". Using username as the subject claim."); } } return subject; } private String getSubjectClaimFromUserStore(String subjectClaimUri, AuthenticatedUser authenticatedUser) throws UserStoreException, IdentityException { UserStoreManager userStoreManager = IdentityTenantUtil .getRealm(authenticatedUser.getTenantDomain(), authenticatedUser.toFullQualifiedUsername()) .getUserStoreManager(); return userStoreManager .getSecondaryUserStoreManager(authenticatedUser.getUserStoreDomain()) .getUserClaimValue(authenticatedUser.getUserName(), subjectClaimUri, null); } private String getSubjectClaimUriInLocalDialect(ServiceProvider serviceProvider) { String subjectClaimUri = serviceProvider.getLocalAndOutBoundAuthenticationConfig().getSubjectClaimUri(); if (log.isDebugEnabled()) { if (StringUtils.isNotBlank(subjectClaimUri)) { log.debug(subjectClaimUri + " is defined as subject claim for service provider: " + serviceProvider.getApplicationName()); } else { log.debug("No subject claim defined for service provider: " + serviceProvider.getApplicationName()); } } // Get the local subject claim URI, if subject claim was a SP mapped one return getSubjectClaimUriInLocalDialect(serviceProvider, subjectClaimUri); } private String getFormattedSubjectClaim(ServiceProvider serviceProvider, String subjectClaimValue, String userStoreDomain, String tenantDomain) { boolean appendUserStoreDomainToSubjectClaim = serviceProvider.getLocalAndOutBoundAuthenticationConfig() .isUseUserstoreDomainInLocalSubjectIdentifier(); boolean appendTenantDomainToSubjectClaim = serviceProvider.getLocalAndOutBoundAuthenticationConfig() .isUseTenantDomainInLocalSubjectIdentifier(); if (appendTenantDomainToSubjectClaim) { subjectClaimValue = UserCoreUtil.addTenantDomainToEntry(subjectClaimValue, tenantDomain); } if (appendUserStoreDomainToSubjectClaim) { subjectClaimValue = IdentityUtil.addDomainToName(subjectClaimValue, userStoreDomain); } return subjectClaimValue; } private String getSigningTenantDomain(OAuthTokenReqMessageContext tokReqMsgCtx) { boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); if (isJWTSignedWithSPKey) { return (String) tokReqMsgCtx.getProperty(MultitenantConstants.TENANT_DOMAIN); } else { return tokReqMsgCtx.getAuthorizedUser().getTenantDomain(); } } private String getSubjectClaimUriInLocalDialect(ServiceProvider serviceProvider, String subjectClaimUri) { if (StringUtils.isNotBlank(subjectClaimUri)) { ClaimConfig claimConfig = serviceProvider.getClaimConfig(); if (claimConfig != null) { boolean isLocalClaimDialect = claimConfig.isLocalClaimDialect(); ClaimMapping[] claimMappings = claimConfig.getClaimMappings(); if (!isLocalClaimDialect && ArrayUtils.isNotEmpty(claimMappings)) { for (ClaimMapping claimMapping : claimMappings) { if (StringUtils.equals(claimMapping.getRemoteClaim().getClaimUri(), subjectClaimUri)) { return claimMapping.getLocalClaim().getClaimUri(); } } } } } // This means the original subjectClaimUri passed was the subject claim URI. return subjectClaimUri; } private List<String> getOIDCAudience(String clientId) { List<String> oidcAudiences = getDefinedCustomOIDCAudiences(); // Need to add client_id as an audience value according to the spec. oidcAudiences.add(clientId); return oidcAudiences; } private String getAtHash(String accessToken) throws IdentityOAuth2Exception { String digAlg = OAuth2Util.mapDigestAlgorithm(signatureAlgorithm); MessageDigest md; try { md = MessageDigest.getInstance(digAlg); } catch (NoSuchAlgorithmException e) { throw new IdentityOAuth2Exception("Error creating the at_hash value. Invalid Digest Algorithm: " + digAlg); } md.update(accessToken.getBytes(Charsets.UTF_8)); byte[] digest = md.digest(); int leftHalfBytes = 16; if (SHA384.equals(digAlg)) { leftHalfBytes = 24; } else if (SHA512.equals(digAlg)) { leftHalfBytes = 32; } byte[] leftmost = new byte[leftHalfBytes]; System.arraycopy(digest, 0, leftmost, 0, leftHalfBytes); return new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8); } protected ServiceProvider getServiceProvider(String spTenantDomain, String clientId) throws IdentityOAuth2Exception { ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService(); try { String spName = applicationMgtService.getServiceProviderNameByClientId(clientId, INBOUND_AUTH2_TYPE, spTenantDomain); return applicationMgtService.getApplicationExcludingFileBasedSPs(spName, spTenantDomain); } catch (IdentityApplicationManagementException e) { throw new IdentityOAuth2Exception("Error while getting service provider information for client_id: " + clientId + " tenantDomain: " + spTenantDomain, e); } } private String getIdTokenIssuer(String tenantDomain) throws IdentityOAuth2Exception { IdentityProvider identityProvider = getResidentIdp(tenantDomain); FederatedAuthenticatorConfig[] fedAuthnConfigs = identityProvider.getFederatedAuthenticatorConfigs(); // Get OIDC authenticator FederatedAuthenticatorConfig oidcAuthenticatorConfig = IdentityApplicationManagementUtil.getFederatedAuthenticator(fedAuthnConfigs, IdentityApplicationConstants.Authenticator.OIDC.NAME); return IdentityApplicationManagementUtil.getProperty(oidcAuthenticatorConfig.getProperties(), OPENID_IDP_ENTITY_ID).getValue(); } @Override public String buildIDToken(OAuthAuthzReqMessageContext authzReqMessageContext, OAuth2AuthorizeRespDTO tokenRespDTO) throws IdentityOAuth2Exception { String accessToken = tokenRespDTO.getAccessToken(); String clientId = authzReqMessageContext.getAuthorizationReqDTO().getConsumerKey(); String spTenantDomain = getSpTenantDomain(authzReqMessageContext); String issuer = getIdTokenIssuer(spTenantDomain); // Get subject from Authenticated Subject Identifier AuthenticatedUser authorizedUser = authzReqMessageContext.getAuthorizationReqDTO().getUser(); String subject = getSubjectClaim(clientId, spTenantDomain, authorizedUser); String nonceValue = authzReqMessageContext.getAuthorizationReqDTO().getNonce(); LinkedHashSet acrValue = authzReqMessageContext.getAuthorizationReqDTO().getACRValues(); long lifetimeInMillis = getIdTokenValidityInMillis(); long currentTimeInMillis = Calendar.getInstance().getTimeInMillis(); if (log.isDebugEnabled()) { StringBuilder stringBuilder = (new StringBuilder()) .append("Using issuer ").append(issuer).append("\n") .append("Subject ").append(subject).append("\n") .append("ID Token life time ").append(lifetimeInMillis / 1000).append("\n") .append("Current time ").append(currentTimeInMillis / 1000).append("\n") .append("Nonce Value ").append(nonceValue).append("\n") .append("Signature Algorithm ").append(signatureAlgorithm).append("\n"); log.debug(stringBuilder.toString()); } JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); jwtClaimsSet.setIssuer(issuer); // Set the audience List<String> audience = getOIDCAudience(clientId); jwtClaimsSet.setAudience(audience); jwtClaimsSet.setClaim(AZP, clientId); jwtClaimsSet.setExpirationTime(getIdTokenExpiryInMillis(lifetimeInMillis, currentTimeInMillis)); jwtClaimsSet.setIssueTime(new Date(currentTimeInMillis)); long authTime = getAuthTime(authzReqMessageContext, accessToken); if (authTime != 0) { jwtClaimsSet.setClaim(AUTH_TIME, authTime / 1000); } String responseType = authzReqMessageContext.getAuthorizationReqDTO().getResponseType(); String atHash = null; if (isIDTokenSigned() && isAccessTokenHashApplicable(responseType)) { atHash = getAtHash(accessToken); } if (atHash != null) { jwtClaimsSet.setClaim(AT_HASH, atHash); } if (nonceValue != null) { jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.NONCE, nonceValue); } if (acrValue != null) { jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.ACR, "urn:mace:incommon:iap:silver"); } authzReqMessageContext.addProperty(OAuthConstants.ACCESS_TOKEN, accessToken); authzReqMessageContext.addProperty(MultitenantConstants.TENANT_DOMAIN, getSpTenantDomain(authzReqMessageContext)); handleCustomOIDCClaims(authzReqMessageContext, jwtClaimsSet); jwtClaimsSet.setSubject(subject); if (isIDTokenNotSigned()) { return new PlainJWT(jwtClaimsSet).serialize(); } String signingTenantDomain = getSigningTenantDomain(authzReqMessageContext); return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); } private long getAuthTime(OAuthAuthzReqMessageContext authzReqMessageContext, String accessToken) { long authTime = 0; if (StringUtils.isNotEmpty(accessToken)) { AuthorizationGrantCacheEntry authorizationGrantCacheEntry = getAuthorizationGrantCacheEntry(accessToken); if (StringUtils.isNotBlank(authorizationGrantCacheEntry.getEssentialClaims())) { if (isEssentialClaim(authorizationGrantCacheEntry, AUTH_TIME)) { authTime = authzReqMessageContext.getAuthorizationReqDTO().getAuthTime(); } } } return authTime; } private boolean isAccessTokenHashApplicable(String responseType) { // At_hash is generated on an access token. Therefore check whether the response type returns an access_token. // id_token and none response types don't return and access token return !OAuthConstants.ID_TOKEN.equalsIgnoreCase(responseType) && !OAuthConstants.NONE.equalsIgnoreCase(responseType); } private Date getIdTokenExpiryInMillis(long currentTimeInMillis, long lifetimeInMillis) { return new Date(currentTimeInMillis + lifetimeInMillis); } private void handleCustomOIDCClaims(OAuthAuthzReqMessageContext request, JWTClaimsSet jwtClaimsSet) { CustomClaimsCallbackHandler claimsCallBackHandler = OAuthServerConfiguration.getInstance().getOpenIDConnectCustomClaimsCallbackHandler(); claimsCallBackHandler.handleCustomClaims(jwtClaimsSet, request); } private String getSpTenantDomain(OAuthAuthzReqMessageContext request) { return request.getAuthorizationReqDTO().getTenantDomain(); } private String getSigningTenantDomain(OAuthAuthzReqMessageContext request) { boolean isJWTSignedWithSPKey = OAuthServerConfiguration.getInstance().isJWTSignedWithSPKey(); String signingTenantDomain; if (isJWTSignedWithSPKey) { signingTenantDomain = (String) request.getProperty(MultitenantConstants.TENANT_DOMAIN); } else { signingTenantDomain = request.getAuthorizationReqDTO().getUser().getTenantDomain(); } return signingTenantDomain; } /** * sign JWT token from RSA algorithm * * @param jwtClaimsSet contains JWT body * @param tokenReqMessageContext * @return signed JWT token * @throws IdentityOAuth2Exception */ @Deprecated protected String signJWTWithRSA(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext tokenReqMessageContext) throws IdentityOAuth2Exception { String tenantDomain = getSigningTenantDomain(tokenReqMessageContext); return OAuth2Util.signJWTWithRSA(jwtClaimsSet, signatureAlgorithm, tenantDomain).serialize(); } /** * sign JWT token from RSA algorithm * * @param jwtClaimsSet contains JWT body * @param authzReqMessageContext * @return signed JWT token * @throws IdentityOAuth2Exception */ @Deprecated protected String signJWTWithRSA(JWTClaimsSet jwtClaimsSet, OAuthAuthzReqMessageContext authzReqMessageContext) throws IdentityOAuth2Exception { String signingTenantDomain = getSigningTenantDomain(authzReqMessageContext); return OAuth2Util.signJWTWithRSA(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); } /** * @param request * @return AuthorizationGrantCacheEntry contains user attributes and nonce value */ private AuthorizationGrantCacheEntry getAuthorizationGrantCacheEntry(OAuthTokenReqMessageContext request) { String authorizationCode = getAuthorizationCode(request); AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(authorizationCode); return AuthorizationGrantCache.getInstance().getValueFromCacheByCode(authorizationGrantCacheKey); } private AuthorizationGrantCacheEntry getAuthorizationGrantCacheEntry(String accessToken) { AuthorizationGrantCacheKey authorizationGrantCacheKey = new AuthorizationGrantCacheKey(accessToken); return AuthorizationGrantCache.getInstance().getValueFromCacheByToken(authorizationGrantCacheKey); } /** * Generic Signing function * * @param jwtClaimsSet contains JWT body * @param tokenMsgContext * @return signed JWT token * @throws IdentityOAuth2Exception */ @Deprecated protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext tokenMsgContext) throws IdentityOAuth2Exception { if (isRSA(signatureAlgorithm)) { return signJWTWithRSA(jwtClaimsSet, tokenMsgContext); } else if (isHMAC(signatureAlgorithm)) { // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done return null; } else { // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done return null; } } private boolean isRSA(JWSAlgorithm signatureAlgorithm) { return JWSAlgorithm.RS256.equals(signatureAlgorithm) || JWSAlgorithm.RS384.equals(signatureAlgorithm) || JWSAlgorithm.RS512.equals(signatureAlgorithm); } /** * Generic Signing function * * @param jwtClaimsSet contains JWT body * @param authzReqMessageContext * @return signed JWT token * @throah ws IdentityOAuth2Exception */ @Deprecated protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthAuthzReqMessageContext authzReqMessageContext) throws IdentityOAuth2Exception { if (isRSA(signatureAlgorithm)) { return signJWTWithRSA(jwtClaimsSet, authzReqMessageContext); } else if (isHMAC(signatureAlgorithm)) { // return signWithHMAC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done return null; } else { // return signWithEC(jwtClaimsSet,jwsAlgorithm,request); implementation need to be done return null; } } private boolean isHMAC(JWSAlgorithm signatureAlgorithm) { return JWSAlgorithm.HS256.equals(signatureAlgorithm) || JWSAlgorithm.HS384.equals(signatureAlgorithm) || JWSAlgorithm.HS512.equals(signatureAlgorithm); } /** * This method map signature algorithm define in identity.xml to nimbus * signature algorithm * format, Strings are defined inline hence there are not being used any * where * * @param signatureAlgorithm signature algorithm * @return mapped JWSAlgorithm * @throws IdentityOAuth2Exception */ @Deprecated protected JWSAlgorithm mapSignatureAlgorithm(String signatureAlgorithm) throws IdentityOAuth2Exception { return OAuth2Util.mapSignatureAlgorithmForJWSAlgorithm(signatureAlgorithm); } /** * This method maps signature algorithm define in identity.xml to digest algorithms to generate the at_hash * * @param signatureAlgorithm signature algorithm * @return mapped digest algorithm * @throws IdentityOAuth2Exception */ @Deprecated protected String mapDigestAlgorithm(Algorithm signatureAlgorithm) throws IdentityOAuth2Exception { return OAuth2Util.mapDigestAlgorithm(signatureAlgorithm); } private List<String> getDefinedCustomOIDCAudiences() { List<String> audiences = new ArrayList<>(); IdentityConfigParser configParser = IdentityConfigParser.getInstance(); OMElement oauthElem = configParser.getConfigElement(CONFIG_ELEM_OAUTH); if (oauthElem == null) { warnOnFaultyConfiguration("<OAuth> configuration element is not available in identity.xml."); return audiences; } OMElement oidcConfig = oauthElem.getFirstChildWithName(getQNameWithIdentityNS(OPENID_CONNECT)); if (oidcConfig == null) { warnOnFaultyConfiguration("<OpenIDConnect> element is not available in identity.xml."); return audiences; } OMElement audienceConfig = oidcConfig.getFirstChildWithName(getQNameWithIdentityNS(OPENID_CONNECT_AUDIENCES)); if (audienceConfig == null) { return audiences; } Iterator iterator = audienceConfig.getChildrenWithName(getQNameWithIdentityNS(OPENID_CONNECT_AUDIENCE)); while (iterator.hasNext()) { OMElement supportedAudience = (OMElement) iterator.next(); String supportedAudienceName = null; if (supportedAudience != null) { supportedAudienceName = IdentityUtil.fillURLPlaceholders(supportedAudience.getText()); } if (StringUtils.isNotBlank(supportedAudienceName)) { audiences.add(supportedAudienceName); } } return audiences; } private void warnOnFaultyConfiguration(String logMsg) { log.warn("Error in OAuth Configuration: " + logMsg); } private QName getQNameWithIdentityNS(String localPart) { return new QName(IdentityCoreConstants.IDENTITY_DEFAULT_NAMESPACE, localPart); } private IdentityProvider getResidentIdp(String tenantDomain) throws IdentityOAuth2Exception { try { return IdentityProviderManager.getInstance().getResidentIdP(tenantDomain); } catch (IdentityProviderManagementException e) { final String ERROR_GET_RESIDENT_IDP = "Error while getting Resident Identity Provider of '%s' tenant."; String errorMsg = String.format(ERROR_GET_RESIDENT_IDP, tenantDomain); throw new IdentityOAuth2Exception(errorMsg, e); } } /** * Method to check whether id token contains the required claims(iss,sub,aud,exp,iat) defined by the oidc spec * * @param jwtClaimsSet jwt claim set * @return true or false(whether id token contains the required claims) */ private boolean isValidIdToken(JWTClaimsSet jwtClaimsSet) { if (StringUtils.isBlank(jwtClaimsSet.getIssuer())) { log.error("ID token does not have required issuer claim"); return false; } if (StringUtils.isBlank(jwtClaimsSet.getSubject())) { log.error("ID token does not have required subject claim"); return false; } if (jwtClaimsSet.getAudience() == null) { log.error("ID token does not have required audience claim"); return false; } if (jwtClaimsSet.getExpirationTime() == null) { log.error("ID token does not have required expiration time claim"); return false; } if (jwtClaimsSet.getIssueTime() == null) { log.error("ID token does not have required issued time claim"); return false; } // All mandatory claims are present. return true; } }
Minor refactoring in DefaultIDTokenBuilder
components/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/openidconnect/DefaultIDTokenBuilder.java
Minor refactoring in DefaultIDTokenBuilder
<ide><path>omponents/org.wso2.carbon.identity.oauth/src/main/java/org/wso2/carbon/identity/openidconnect/DefaultIDTokenBuilder.java <ide> String spTenantDomain = getSpTenantDomain(tokenReqMsgCtxt); <ide> String idTokenIssuer = getIdTokenIssuer(spTenantDomain); <ide> <del> long idTokenLifeTimeInMillis = getIdTokenValidityInMillis(); <add> long idTokenValidityInMillis = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenExpiryTimeInMillis(); <ide> long currentTimeInMillis = Calendar.getInstance().getTimeInMillis(); <ide> <ide> AuthenticatedUser authorizedUser = tokenReqMsgCtxt.getAuthorizedUser(); <del> String subjectClaim = getSubjectClaim(clientId, spTenantDomain, authorizedUser); <add> String subjectClaim = getSubjectClaim(tokenReqMsgCtxt, clientId, spTenantDomain, authorizedUser); <ide> <ide> String nonceValue = null; <ide> long authTime = 0; <ide> LinkedHashSet acrValue = new LinkedHashSet(); <add> <ide> // AuthorizationCode only available for authorization code grant type <ide> if (getAuthorizationCode(tokenReqMsgCtxt) != null) { <ide> AuthorizationGrantCacheEntry authorizationGrantCacheEntry = getAuthorizationGrantCacheEntry(tokenReqMsgCtxt); <ide> } <ide> <ide> if (log.isDebugEnabled()) { <del> StringBuilder stringBuilder = (new StringBuilder()) <del> .append("Using issuer: ").append(idTokenIssuer).append("\n") <del> .append("Subject: ").append(subjectClaim).append("\n") <del> .append("Current time: ").append(currentTimeInMillis / 1000).append("\n") <del> .append("ID Token life time: ").append(idTokenLifeTimeInMillis / 1000).append("\n") <del> .append("Nonce Value: ").append(nonceValue).append("\n") <del> .append("Signature Algorithm ").append(signatureAlgorithm).append("\n"); <del> log.debug(stringBuilder.toString()); <add> log.debug(buildDebugMessage(idTokenIssuer, subjectClaim, nonceValue, idTokenValidityInMillis, currentTimeInMillis)); <ide> } <ide> <ide> List<String> audience = getOIDCAudience(clientId); <ide> jwtClaimsSet.setIssuer(idTokenIssuer); <ide> jwtClaimsSet.setAudience(audience); <ide> jwtClaimsSet.setClaim(AZP, clientId); <del> jwtClaimsSet.setExpirationTime(getIdTokenExpiryInMillis(idTokenLifeTimeInMillis, currentTimeInMillis)); <add> jwtClaimsSet.setExpirationTime(getIdTokenExpiryInMillis(idTokenValidityInMillis, currentTimeInMillis)); <ide> jwtClaimsSet.setIssueTime(new Date(currentTimeInMillis)); <ide> if (authTime != 0) { <ide> jwtClaimsSet.setClaim(AUTH_TIME, authTime / 1000); <ide> return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); <ide> } <ide> <del> private boolean isInvalidToken(JWTClaimsSet jwtClaimsSet) { <del> return !isValidIdToken(jwtClaimsSet); <del> } <del> <del> private long getIdTokenValidityInMillis() { <del> return OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenExpiryTimeInMillis(); <del> } <del> <del> private boolean isEssentialClaim(AuthorizationGrantCacheEntry authorizationGrantCacheEntry, <del> String oidcClaimUri) { <del> return OAuth2Util.getEssentialClaims(authorizationGrantCacheEntry.getEssentialClaims(), OAuthConstants.ID_TOKEN) <del> .contains(oidcClaimUri); <del> } <del> <del> private boolean isIDTokenNotSigned() { <del> return JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()); <del> } <del> <del> private boolean isIDTokenSigned() { <del> return !JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()); <add> @Override <add> public String buildIDToken(OAuthAuthzReqMessageContext authzReqMessageContext, <add> OAuth2AuthorizeRespDTO tokenRespDTO) throws IdentityOAuth2Exception { <add> <add> String accessToken = tokenRespDTO.getAccessToken(); <add> String clientId = authzReqMessageContext.getAuthorizationReqDTO().getConsumerKey(); <add> String spTenantDomain = getSpTenantDomain(authzReqMessageContext); <add> String issuer = getIdTokenIssuer(spTenantDomain); <add> <add> // Get subject from Authenticated Subject Identifier <add> AuthenticatedUser authorizedUser = authzReqMessageContext.getAuthorizationReqDTO().getUser(); <add> String subject = getSubjectClaim(authzReqMessageContext, clientId, spTenantDomain, authorizedUser); <add> <add> String nonceValue = authzReqMessageContext.getAuthorizationReqDTO().getNonce(); <add> LinkedHashSet acrValue = authzReqMessageContext.getAuthorizationReqDTO().getACRValues(); <add> <add> long idTokenLifeTimeInMillis = OAuthServerConfiguration.getInstance().getOpenIDConnectIDTokenExpiryTimeInMillis(); <add> long currentTimeInMillis = Calendar.getInstance().getTimeInMillis(); <add> <add> if (log.isDebugEnabled()) { <add> log.debug(buildDebugMessage(issuer, subject, nonceValue, idTokenLifeTimeInMillis, currentTimeInMillis)); <add> } <add> <add> JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); <add> jwtClaimsSet.setIssuer(issuer); <add> <add> // Set the audience <add> List<String> audience = getOIDCAudience(clientId); <add> jwtClaimsSet.setAudience(audience); <add> <add> jwtClaimsSet.setClaim(AZP, clientId); <add> jwtClaimsSet.setExpirationTime(getIdTokenExpiryInMillis(idTokenLifeTimeInMillis, currentTimeInMillis)); <add> jwtClaimsSet.setIssueTime(new Date(currentTimeInMillis)); <add> <add> long authTime = getAuthTime(authzReqMessageContext, accessToken); <add> if (authTime != 0) { <add> jwtClaimsSet.setClaim(AUTH_TIME, authTime / 1000); <add> } <add> <add> String responseType = authzReqMessageContext.getAuthorizationReqDTO().getResponseType(); <add> String atHash = null; <add> if (isIDTokenSigned() && isAccessTokenHashApplicable(responseType)) { <add> atHash = getAtHash(accessToken); <add> } <add> <add> if (atHash != null) { <add> jwtClaimsSet.setClaim(AT_HASH, atHash); <add> } <add> if (nonceValue != null) { <add> jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.NONCE, nonceValue); <add> } <add> if (acrValue != null) { <add> jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.ACR, "urn:mace:incommon:iap:silver"); <add> } <add> <add> authzReqMessageContext.addProperty(OAuthConstants.ACCESS_TOKEN, accessToken); <add> authzReqMessageContext.addProperty(MultitenantConstants.TENANT_DOMAIN, getSpTenantDomain(authzReqMessageContext)); <add> <add> handleCustomOIDCClaims(authzReqMessageContext, jwtClaimsSet); <add> jwtClaimsSet.setSubject(subject); <add> <add> if (isIDTokenNotSigned()) { <add> return new PlainJWT(jwtClaimsSet).serialize(); <add> } <add> <add> String signingTenantDomain = getSigningTenantDomain(authzReqMessageContext); <add> return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); <add> } <add> <add> protected String getSubjectClaim(OAuthTokenReqMessageContext tokenReqMessageContext, <add> String clientId, <add> String spTenantDomain, <add> AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { <add> return getSubjectClaim(clientId, spTenantDomain, authorizedUser); <add> } <add> <add> protected String getSubjectClaim(OAuthAuthzReqMessageContext authzReqMessageContext, <add> String clientId, <add> String spTenantDomain, <add> AuthenticatedUser authorizedUser) throws IdentityOAuth2Exception { <add> return getSubjectClaim(clientId, spTenantDomain, authorizedUser); <ide> } <ide> <ide> private String getSubjectClaim(String clientId, <ide> } <ide> } <ide> return subjectClaim; <add> } <add> <add> private String buildDebugMessage(String issuer, String subject, String nonceValue, long idTokenLifeTimeInMillis, <add> long currentTimeInMillis) { <add> return (new StringBuilder()) <add> .append("Using issuer ").append(issuer).append("\n") <add> .append("Subject ").append(subject).append("\n") <add> .append("ID Token life time ").append(idTokenLifeTimeInMillis / 1000).append("\n") <add> .append("Current time ").append(currentTimeInMillis / 1000).append("\n") <add> .append("Nonce Value ").append(nonceValue).append("\n") <add> .append("Signature Algorithm ").append(signatureAlgorithm).append("\n") <add> .toString(); <add> } <add> <add> private boolean isInvalidToken(JWTClaimsSet jwtClaimsSet) { <add> return !isValidIdToken(jwtClaimsSet); <add> } <add> <add> private boolean isEssentialClaim(AuthorizationGrantCacheEntry authorizationGrantCacheEntry, <add> String oidcClaimUri) { <add> return OAuth2Util.getEssentialClaims(authorizationGrantCacheEntry.getEssentialClaims(), OAuthConstants.ID_TOKEN) <add> .contains(oidcClaimUri); <add> } <add> <add> private boolean isIDTokenNotSigned() { <add> return JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()); <add> } <add> <add> private boolean isIDTokenSigned() { <add> return !JWSAlgorithm.NONE.getName().equals(signatureAlgorithm.getName()); <ide> } <ide> <ide> private String getAuthorizationCode(OAuthTokenReqMessageContext tokenReqMsgCtxt) { <ide> return new String(Base64.encodeBase64URLSafe(leftmost), Charsets.UTF_8); <ide> } <ide> <del> protected ServiceProvider getServiceProvider(String spTenantDomain, <del> String clientId) throws IdentityOAuth2Exception { <add> private ServiceProvider getServiceProvider(String spTenantDomain, <add> String clientId) throws IdentityOAuth2Exception { <ide> ApplicationManagementService applicationMgtService = OAuth2ServiceComponentHolder.getApplicationMgtService(); <ide> try { <ide> String spName = <ide> IdentityApplicationConstants.Authenticator.OIDC.NAME); <ide> return IdentityApplicationManagementUtil.getProperty(oidcAuthenticatorConfig.getProperties(), <ide> OPENID_IDP_ENTITY_ID).getValue(); <del> } <del> <del> @Override <del> public String buildIDToken(OAuthAuthzReqMessageContext authzReqMessageContext, <del> OAuth2AuthorizeRespDTO tokenRespDTO) throws IdentityOAuth2Exception { <del> <del> String accessToken = tokenRespDTO.getAccessToken(); <del> String clientId = authzReqMessageContext.getAuthorizationReqDTO().getConsumerKey(); <del> String spTenantDomain = getSpTenantDomain(authzReqMessageContext); <del> String issuer = getIdTokenIssuer(spTenantDomain); <del> <del> // Get subject from Authenticated Subject Identifier <del> AuthenticatedUser authorizedUser = authzReqMessageContext.getAuthorizationReqDTO().getUser(); <del> String subject = getSubjectClaim(clientId, spTenantDomain, authorizedUser); <del> <del> String nonceValue = authzReqMessageContext.getAuthorizationReqDTO().getNonce(); <del> LinkedHashSet acrValue = authzReqMessageContext.getAuthorizationReqDTO().getACRValues(); <del> <del> long lifetimeInMillis = getIdTokenValidityInMillis(); <del> long currentTimeInMillis = Calendar.getInstance().getTimeInMillis(); <del> <del> if (log.isDebugEnabled()) { <del> StringBuilder stringBuilder = (new StringBuilder()) <del> .append("Using issuer ").append(issuer).append("\n") <del> .append("Subject ").append(subject).append("\n") <del> .append("ID Token life time ").append(lifetimeInMillis / 1000).append("\n") <del> .append("Current time ").append(currentTimeInMillis / 1000).append("\n") <del> .append("Nonce Value ").append(nonceValue).append("\n") <del> .append("Signature Algorithm ").append(signatureAlgorithm).append("\n"); <del> log.debug(stringBuilder.toString()); <del> } <del> <del> JWTClaimsSet jwtClaimsSet = new JWTClaimsSet(); <del> jwtClaimsSet.setIssuer(issuer); <del> <del> // Set the audience <del> List<String> audience = getOIDCAudience(clientId); <del> jwtClaimsSet.setAudience(audience); <del> <del> jwtClaimsSet.setClaim(AZP, clientId); <del> jwtClaimsSet.setExpirationTime(getIdTokenExpiryInMillis(lifetimeInMillis, currentTimeInMillis)); <del> jwtClaimsSet.setIssueTime(new Date(currentTimeInMillis)); <del> <del> long authTime = getAuthTime(authzReqMessageContext, accessToken); <del> if (authTime != 0) { <del> jwtClaimsSet.setClaim(AUTH_TIME, authTime / 1000); <del> } <del> <del> String responseType = authzReqMessageContext.getAuthorizationReqDTO().getResponseType(); <del> String atHash = null; <del> if (isIDTokenSigned() && isAccessTokenHashApplicable(responseType)) { <del> atHash = getAtHash(accessToken); <del> } <del> <del> if (atHash != null) { <del> jwtClaimsSet.setClaim(AT_HASH, atHash); <del> } <del> if (nonceValue != null) { <del> jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.NONCE, nonceValue); <del> } <del> if (acrValue != null) { <del> jwtClaimsSet.setClaim(OAuthConstants.OIDCClaims.ACR, "urn:mace:incommon:iap:silver"); <del> } <del> <del> authzReqMessageContext.addProperty(OAuthConstants.ACCESS_TOKEN, accessToken); <del> authzReqMessageContext.addProperty(MultitenantConstants.TENANT_DOMAIN, getSpTenantDomain(authzReqMessageContext)); <del> <del> handleCustomOIDCClaims(authzReqMessageContext, jwtClaimsSet); <del> jwtClaimsSet.setSubject(subject); <del> <del> if (isIDTokenNotSigned()) { <del> return new PlainJWT(jwtClaimsSet).serialize(); <del> } <del> <del> String signingTenantDomain = getSigningTenantDomain(authzReqMessageContext); <del> return OAuth2Util.signJWT(jwtClaimsSet, signatureAlgorithm, signingTenantDomain).serialize(); <ide> } <ide> <ide> private long getAuthTime(OAuthAuthzReqMessageContext authzReqMessageContext, String accessToken) { <ide> * @throws IdentityOAuth2Exception <ide> */ <ide> @Deprecated <del> protected String signJWT(JWTClaimsSet jwtClaimsSet, OAuthTokenReqMessageContext tokenMsgContext) <del> throws IdentityOAuth2Exception { <del> <add> protected String signJWT(JWTClaimsSet jwtClaimsSet, <add> OAuthTokenReqMessageContext tokenMsgContext) throws IdentityOAuth2Exception { <ide> if (isRSA(signatureAlgorithm)) { <ide> return signJWTWithRSA(jwtClaimsSet, tokenMsgContext); <ide> } else if (isHMAC(signatureAlgorithm)) { <ide> Iterator iterator = audienceConfig.getChildrenWithName(getQNameWithIdentityNS(OPENID_CONNECT_AUDIENCE)); <ide> while (iterator.hasNext()) { <ide> OMElement supportedAudience = (OMElement) iterator.next(); <del> String supportedAudienceName = null; <del> <add> String supportedAudienceName; <ide> if (supportedAudience != null) { <ide> supportedAudienceName = IdentityUtil.fillURLPlaceholders(supportedAudience.getText()); <del> } <del> if (StringUtils.isNotBlank(supportedAudienceName)) { <del> audiences.add(supportedAudienceName); <add> if (StringUtils.isNotBlank(supportedAudienceName)) { <add> audiences.add(supportedAudienceName); <add> } <ide> } <ide> } <ide> return audiences;
Java
apache-2.0
7a55aef1173d6e488475fa365a61cd33bf191e12
0
Sage-Bionetworks/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,Sage-Bionetworks/SynapseWebClient,jay-hodgson/SynapseWebClient,jay-hodgson/SynapseWebClient
package org.sagebionetworks.web.unitclient.widget.entity.renderer; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.*; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.file.FileHandleAssociateType; import org.sagebionetworks.repo.model.file.FileHandleAssociation; import org.sagebionetworks.repo.model.file.FileResult; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.web.client.SynapseJavascriptClient; import org.sagebionetworks.web.client.security.AuthenticationController; import org.sagebionetworks.web.client.widget.asynch.FileHandleAsyncHandler; import org.sagebionetworks.web.client.widget.asynch.PresignedURLAsyncHandler; import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert; import org.sagebionetworks.web.client.widget.entity.renderer.ImageWidget; import org.sagebionetworks.web.client.widget.entity.renderer.ImageWidgetView; import org.sagebionetworks.web.shared.WidgetConstants; import org.sagebionetworks.web.shared.WikiPageKey; import org.sagebionetworks.web.test.helper.AsyncMockStubber; import com.google.gwt.user.client.rpc.AsyncCallback; public class ImageWidgetTest { // ImageWidget widget; @Mock ImageWidgetView mockView; Map<String, String> descriptor; WikiPageKey wikiKey = new WikiPageKey("syn222222", ObjectType.ENTITY.toString(), "9"); @Mock AuthenticationController mockAuthenticationController; @Mock PresignedURLAsyncHandler mockPresignedURLAsyncHandler; @Mock SynapseJavascriptClient mockSynapseJavascriptClient; @Mock SynapseAlert mockSynAlert; @Mock FileEntity mockFileEntity; @Mock FileResult mockFileResult; @Mock FileHandle mockFileHandle1; @Mock FileHandle mockFileHandle2; @Captor ArgumentCaptor<FileHandleAssociation> fhaCaptor; public static final String PRESIGNED_URL = "https://s3.presigned/image.jpg"; public static final String FILE_NAME = "image.jpg"; @Before public void setup() throws JSONObjectAdapterException{ MockitoAnnotations.initMocks(this); mockView = mock(ImageWidgetView.class); mockAuthenticationController = mock(AuthenticationController.class); widget = new ImageWidget( mockView, mockAuthenticationController, mockPresignedURLAsyncHandler, mockSynapseJavascriptClient, mockSynAlert); descriptor = new HashMap<String, String>(); descriptor.put(WidgetConstants.IMAGE_WIDGET_FILE_NAME_KEY, FILE_NAME); when(mockAuthenticationController.isLoggedIn()).thenReturn(true); when(mockFileResult.getPreSignedURL()).thenReturn(PRESIGNED_URL); AsyncMockStubber.callSuccessWith(mockFileResult).when(mockPresignedURLAsyncHandler).getFileResult(any(FileHandleAssociation.class), any(AsyncCallback.class)); } @Test public void testAsWidget() { widget.asWidget(); verify(mockView).asWidget(); } @Test public void testConfigureFromSynapseId() { AsyncMockStubber.callSuccessWith(mockFileEntity).when(mockSynapseJavascriptClient).getEntityForVersion(anyString(), anyLong(), any(AsyncCallback.class)); String synId = "syn239"; descriptor.put(WidgetConstants.IMAGE_WIDGET_SYNAPSE_ID_KEY, synId); String dataFileHandleId = "8765"; when(mockFileEntity.getId()).thenReturn(synId); when(mockFileEntity.getDataFileHandleId()).thenReturn(dataFileHandleId); widget.configure(wikiKey,descriptor, null, null); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getEntityForVersion(eq(synId), eq((Long)null), any(AsyncCallback.class)); verify(mockPresignedURLAsyncHandler).getFileResult(any(FileHandleAssociation.class), any(AsyncCallback.class)); boolean isLoggedIn = true; verify(mockView).configure(eq(PRESIGNED_URL), eq(FILE_NAME), anyString(), anyString(), eq(synId), eq(isLoggedIn)); } @Test public void testConfigureFromSynapseIdWithVersion() { AsyncMockStubber.callSuccessWith(mockFileEntity).when(mockSynapseJavascriptClient).getEntityForVersion(anyString(), anyLong(), any(AsyncCallback.class)); String synId = "syn239"; Long version = 999L; descriptor.put(WidgetConstants.IMAGE_WIDGET_SYNAPSE_ID_KEY, synId); descriptor.put(WidgetConstants.WIDGET_ENTITY_VERSION_KEY, version.toString()); String dataFileHandleId = "8765"; when(mockFileEntity.getId()).thenReturn(synId); when(mockFileEntity.getDataFileHandleId()).thenReturn(dataFileHandleId); widget.configure(wikiKey,descriptor, null, null); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getEntityForVersion(eq(synId), eq(version), any(AsyncCallback.class)); verify(mockPresignedURLAsyncHandler).getFileResult(fhaCaptor.capture(), any(AsyncCallback.class)); FileHandleAssociation fha = fhaCaptor.getValue(); assertEquals(synId, fha.getAssociateObjectId()); assertEquals(FileHandleAssociateType.FileEntity, fha.getAssociateObjectType()); assertEquals(dataFileHandleId, fha.getFileHandleId()); boolean isLoggedIn = true; verify(mockView).configure(eq(PRESIGNED_URL), eq(FILE_NAME), anyString(), anyString(), eq(synId), eq(isLoggedIn)); } @Test public void testConfigureFromSynapseIdError() { Exception ex = new Exception("so sad"); AsyncMockStubber.callFailureWith(ex).when(mockSynapseJavascriptClient).getEntityForVersion(anyString(), anyLong(), any(AsyncCallback.class)); String synId = "syn239"; descriptor.put(WidgetConstants.IMAGE_WIDGET_SYNAPSE_ID_KEY, synId); widget.configure(wikiKey,descriptor, null, null); verify(mockSynAlert).clear(); verify(mockSynAlert).handleException(ex); } @Test public void testConfigureFromWikiAttachment() { List<FileHandle> fileHandles = new ArrayList<>(); fileHandles.add(mockFileHandle1); fileHandles.add(mockFileHandle2); AsyncMockStubber.callSuccessWith(fileHandles).when(mockSynapseJavascriptClient).getWikiAttachmentFileHandles(any(WikiPageKey.class), anyLong(), any(AsyncCallback.class)); when(mockFileHandle1.getFileName()).thenReturn("wrong file.txt"); when(mockFileHandle2.getFileName()).thenReturn(FILE_NAME); String fileHandleId1 = "1111"; String fileHandleId2 = "2222"; when(mockFileHandle1.getId()).thenReturn(fileHandleId1); when(mockFileHandle2.getId()).thenReturn(fileHandleId2); Long wikiVersion = 2L; widget.configure(wikiKey,descriptor, null, wikiVersion); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getWikiAttachmentFileHandles(any(WikiPageKey.class), eq(wikiVersion), any(AsyncCallback.class)); verify(mockPresignedURLAsyncHandler).getFileResult(fhaCaptor.capture(), any(AsyncCallback.class)); FileHandleAssociation fha = fhaCaptor.getValue(); assertEquals(wikiKey.getWikiPageId(), fha.getAssociateObjectId()); assertEquals(FileHandleAssociateType.WikiAttachment, fha.getAssociateObjectType()); assertEquals(fileHandleId2, fha.getFileHandleId()); boolean isLoggedIn = true; verify(mockView).configure(eq(PRESIGNED_URL), eq(FILE_NAME), anyString(), anyString(), eq((String)null), eq(isLoggedIn)); } @Test public void testConfigureFromWikiAttachmentError() { Exception ex = new Exception("so sad"); AsyncMockStubber.callFailureWith(ex).when(mockSynapseJavascriptClient).getWikiAttachmentFileHandles(any(WikiPageKey.class), anyLong(), any(AsyncCallback.class)); widget.configure(wikiKey,descriptor, null, null); verify(mockSynAlert).clear(); verify(mockSynAlert).handleException(ex); } @Test public void testConfigureDefaultResponsive() { descriptor.put(WidgetConstants.IMAGE_WIDGET_RESPONSIVE_KEY, null); widget.configure(wikiKey,descriptor, null, null); verify(mockView, never()).addStyleName(ImageWidget.MAX_WIDTH_NONE); } @Test public void testConfigureResponsive() { descriptor.put(WidgetConstants.IMAGE_WIDGET_RESPONSIVE_KEY, Boolean.TRUE.toString()); widget.configure(wikiKey,descriptor, null, null); verify(mockView, never()).addStyleName(ImageWidget.MAX_WIDTH_NONE); } @Test public void testConfigureNotResponsive() { descriptor.put(WidgetConstants.IMAGE_WIDGET_RESPONSIVE_KEY, Boolean.FALSE.toString()); widget.configure(wikiKey,descriptor, null, null); verify(mockView).addStyleName(ImageWidget.MAX_WIDTH_NONE); } }
src/test/java/org/sagebionetworks/web/unitclient/widget/entity/renderer/ImageWidgetTest.java
package org.sagebionetworks.web.unitclient.widget.entity.renderer; import static org.junit.Assert.*; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyBoolean; import static org.mockito.Matchers.*; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.sagebionetworks.repo.model.FileEntity; import org.sagebionetworks.repo.model.ObjectType; import org.sagebionetworks.repo.model.file.FileHandle; import org.sagebionetworks.repo.model.file.FileHandleAssociateType; import org.sagebionetworks.repo.model.file.FileHandleAssociation; import org.sagebionetworks.repo.model.file.FileResult; import org.sagebionetworks.schema.adapter.JSONObjectAdapterException; import org.sagebionetworks.web.client.SynapseJavascriptClient; import org.sagebionetworks.web.client.security.AuthenticationController; import org.sagebionetworks.web.client.widget.asynch.FileHandleAsyncHandler; import org.sagebionetworks.web.client.widget.asynch.PresignedURLAsyncHandler; import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert; import org.sagebionetworks.web.client.widget.entity.renderer.ImageWidget; import org.sagebionetworks.web.client.widget.entity.renderer.ImageWidgetView; import org.sagebionetworks.web.shared.WidgetConstants; import org.sagebionetworks.web.shared.WikiPageKey; import org.sagebionetworks.web.test.helper.AsyncMockStubber; import com.google.gwt.user.client.rpc.AsyncCallback; public class ImageWidgetTest { // ImageWidget widget; @Mock ImageWidgetView mockView; Map<String, String> descriptor; WikiPageKey wikiKey = new WikiPageKey("syn222222", ObjectType.ENTITY.toString(), "9"); @Mock AuthenticationController mockAuthenticationController; @Mock PresignedURLAsyncHandler mockPresignedURLAsyncHandler; @Mock SynapseJavascriptClient mockSynapseJavascriptClient; @Mock SynapseAlert mockSynAlert; @Mock FileEntity mockFileEntity; @Mock FileResult mockFileResult; @Mock FileHandle mockFileHandle1; @Mock FileHandle mockFileHandle2; @Captor ArgumentCaptor<FileHandleAssociation> fhaCaptor; public static final String PRESIGNED_URL = "https://s3.presigned/image.jpg"; public static final String FILE_NAME = "image.jpg"; @Before public void setup() throws JSONObjectAdapterException{ MockitoAnnotations.initMocks(this); mockView = mock(ImageWidgetView.class); mockAuthenticationController = mock(AuthenticationController.class); widget = new ImageWidget( mockView, mockAuthenticationController, mockPresignedURLAsyncHandler, mockSynapseJavascriptClient, mockSynAlert); descriptor = new HashMap<String, String>(); descriptor.put(WidgetConstants.IMAGE_WIDGET_FILE_NAME_KEY, FILE_NAME); when(mockAuthenticationController.isLoggedIn()).thenReturn(true); when(mockFileResult.getPreSignedURL()).thenReturn(PRESIGNED_URL); AsyncMockStubber.callSuccessWith(mockFileResult).when(mockPresignedURLAsyncHandler).getFileResult(any(FileHandleAssociation.class), any(AsyncCallback.class)); } @Test public void testAsWidget() { widget.asWidget(); verify(mockView).asWidget(); } @Test public void testConfigureFromSynapseId() { AsyncMockStubber.callSuccessWith(mockFileEntity).when(mockSynapseJavascriptClient).getEntityForVersion(anyString(), anyLong(), any(AsyncCallback.class)); String synId = "syn239"; descriptor.put(WidgetConstants.IMAGE_WIDGET_SYNAPSE_ID_KEY, synId); String dataFileHandleId = "8765"; when(mockFileEntity.getId()).thenReturn(synId); when(mockFileEntity.getDataFileHandleId()).thenReturn(dataFileHandleId); widget.configure(wikiKey,descriptor, null, null); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getEntityForVersion(eq(synId), eq((Long)null), any(AsyncCallback.class)); verify(mockPresignedURLAsyncHandler).getFileResult(any(FileHandleAssociation.class), any(AsyncCallback.class)); boolean isLoggedIn = true; verify(mockView).configure(eq(PRESIGNED_URL), eq(FILE_NAME), anyString(), anyString(), eq(synId), eq(isLoggedIn)); } @Test public void testConfigureFromSynapseIdWithVersion() { AsyncMockStubber.callSuccessWith(mockFileEntity).when(mockSynapseJavascriptClient).getEntityForVersion(anyString(), anyLong(), any(AsyncCallback.class)); String synId = "syn239"; Long version = 999L; descriptor.put(WidgetConstants.IMAGE_WIDGET_SYNAPSE_ID_KEY, synId); descriptor.put(WidgetConstants.WIDGET_ENTITY_VERSION_KEY, version.toString()); String dataFileHandleId = "8765"; when(mockFileEntity.getId()).thenReturn(synId); when(mockFileEntity.getDataFileHandleId()).thenReturn(dataFileHandleId); widget.configure(wikiKey,descriptor, null, null); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getEntityForVersion(eq(synId), eq(version), any(AsyncCallback.class)); verify(mockPresignedURLAsyncHandler).getFileResult(fhaCaptor.capture(), any(AsyncCallback.class)); FileHandleAssociation fha = fhaCaptor.getValue(); assertEquals(synId, fha.getAssociateObjectId()); assertEquals(FileHandleAssociateType.FileEntity, fha.getAssociateObjectType()); assertEquals(dataFileHandleId, fha.getFileHandleId()); boolean isLoggedIn = true; verify(mockView).configure(eq(PRESIGNED_URL), eq(FILE_NAME), anyString(), anyString(), eq(synId), eq(isLoggedIn)); } @Test public void testConfigureFromWikiAttachment() { List<FileHandle> fileHandles = new ArrayList<>(); fileHandles.add(mockFileHandle1); fileHandles.add(mockFileHandle2); AsyncMockStubber.callSuccessWith(fileHandles).when(mockSynapseJavascriptClient).getWikiAttachmentFileHandles(any(WikiPageKey.class), anyLong(), any(AsyncCallback.class)); when(mockFileHandle1.getFileName()).thenReturn("wrong file.txt"); when(mockFileHandle2.getFileName()).thenReturn(FILE_NAME); String fileHandleId1 = "1111"; String fileHandleId2 = "2222"; when(mockFileHandle1.getId()).thenReturn(fileHandleId1); when(mockFileHandle2.getId()).thenReturn(fileHandleId2); Long wikiVersion = 2L; widget.configure(wikiKey,descriptor, null, wikiVersion); verify(mockSynAlert).clear(); verify(mockSynapseJavascriptClient).getWikiAttachmentFileHandles(any(WikiPageKey.class), eq(wikiVersion), any(AsyncCallback.class)); verify(mockPresignedURLAsyncHandler).getFileResult(fhaCaptor.capture(), any(AsyncCallback.class)); FileHandleAssociation fha = fhaCaptor.getValue(); assertEquals(wikiKey.getWikiPageId(), fha.getAssociateObjectId()); assertEquals(FileHandleAssociateType.WikiAttachment, fha.getAssociateObjectType()); assertEquals(fileHandleId2, fha.getFileHandleId()); boolean isLoggedIn = true; verify(mockView).configure(eq(PRESIGNED_URL), eq(FILE_NAME), anyString(), anyString(), eq((String)null), eq(isLoggedIn)); } @Test public void testConfigureDefaultResponsive() { descriptor.put(WidgetConstants.IMAGE_WIDGET_RESPONSIVE_KEY, null); widget.configure(wikiKey,descriptor, null, null); verify(mockView, never()).addStyleName(ImageWidget.MAX_WIDTH_NONE); } @Test public void testConfigureResponsive() { descriptor.put(WidgetConstants.IMAGE_WIDGET_RESPONSIVE_KEY, Boolean.TRUE.toString()); widget.configure(wikiKey,descriptor, null, null); verify(mockView, never()).addStyleName(ImageWidget.MAX_WIDTH_NONE); } @Test public void testConfigureNotResponsive() { descriptor.put(WidgetConstants.IMAGE_WIDGET_RESPONSIVE_KEY, Boolean.FALSE.toString()); widget.configure(wikiKey,descriptor, null, null); verify(mockView).addStyleName(ImageWidget.MAX_WIDTH_NONE); } }
include failure tests
src/test/java/org/sagebionetworks/web/unitclient/widget/entity/renderer/ImageWidgetTest.java
include failure tests
<ide><path>rc/test/java/org/sagebionetworks/web/unitclient/widget/entity/renderer/ImageWidgetTest.java <ide> } <ide> <ide> @Test <add> public void testConfigureFromSynapseIdError() { <add> Exception ex = new Exception("so sad"); <add> AsyncMockStubber.callFailureWith(ex).when(mockSynapseJavascriptClient).getEntityForVersion(anyString(), anyLong(), any(AsyncCallback.class)); <add> String synId = "syn239"; <add> descriptor.put(WidgetConstants.IMAGE_WIDGET_SYNAPSE_ID_KEY, synId); <add> <add> widget.configure(wikiKey,descriptor, null, null); <add> <add> verify(mockSynAlert).clear(); <add> verify(mockSynAlert).handleException(ex); <add> } <add> <add> @Test <ide> public void testConfigureFromWikiAttachment() { <ide> List<FileHandle> fileHandles = new ArrayList<>(); <ide> fileHandles.add(mockFileHandle1); <ide> } <ide> <ide> @Test <add> public void testConfigureFromWikiAttachmentError() { <add> Exception ex = new Exception("so sad"); <add> AsyncMockStubber.callFailureWith(ex).when(mockSynapseJavascriptClient).getWikiAttachmentFileHandles(any(WikiPageKey.class), anyLong(), any(AsyncCallback.class)); <add> <add> widget.configure(wikiKey,descriptor, null, null); <add> <add> verify(mockSynAlert).clear(); <add> verify(mockSynAlert).handleException(ex); <add> } <add> <add> <add> @Test <ide> public void testConfigureDefaultResponsive() { <ide> descriptor.put(WidgetConstants.IMAGE_WIDGET_RESPONSIVE_KEY, null); <ide> widget.configure(wikiKey,descriptor, null, null);
Java
mit
51ab3ad9410979a0f63daa204b4fcba83b39b31a
0
DigitalStrawberry/ANE-Sounds
package com.digitalstrawberry.nativeExtensions.anesounds.functions; import android.media.AudioAttributes; import android.media.AudioManager; import android.media.SoundPool; import android.os.Build; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREObject; import com.digitalstrawberry.nativeExtensions.anesounds.ANESoundsContext; public class Initialize implements FREFunction { @Override public FREObject call( FREContext context, FREObject[] args ) { ANESoundsContext soundsContext = (ANESoundsContext) context; // SoundPool constructor is deprecated since API 21 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { AudioAttributes attributes = new AudioAttributes.Builder() .setUsage(AudioAttributes.USAGE_GAME) .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) .build(); soundsContext.soundPool = new SoundPool.Builder() .setAudioAttributes(attributes) .build(); } else { soundsContext.soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); } context.getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC); return null; } }
android/src/com/digitalstrawberry/nativeExtensions/anesounds/functions/Initialize.java
package com.digitalstrawberry.nativeExtensions.anesounds.functions; import android.media.AudioManager; import android.media.SoundPool; import com.adobe.fre.FREContext; import com.adobe.fre.FREFunction; import com.adobe.fre.FREObject; import com.digitalstrawberry.nativeExtensions.anesounds.ANESoundsContext; public class Initialize implements FREFunction { @Override public FREObject call( FREContext context, FREObject[] args ) { ANESoundsContext soundsContext = (ANESoundsContext) context; soundsContext.soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); context.getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC); return null; } }
Updated native 'initialize' function Avoids using deprecated API when running on Android 5+
android/src/com/digitalstrawberry/nativeExtensions/anesounds/functions/Initialize.java
Updated native 'initialize' function
<ide><path>ndroid/src/com/digitalstrawberry/nativeExtensions/anesounds/functions/Initialize.java <ide> package com.digitalstrawberry.nativeExtensions.anesounds.functions; <ide> <add>import android.media.AudioAttributes; <ide> import android.media.AudioManager; <ide> import android.media.SoundPool; <add>import android.os.Build; <ide> import com.adobe.fre.FREContext; <ide> import com.adobe.fre.FREFunction; <ide> import com.adobe.fre.FREObject; <ide> { <ide> ANESoundsContext soundsContext = (ANESoundsContext) context; <ide> <del> soundsContext.soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); <del> context.getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC); <add> // SoundPool constructor is deprecated since API 21 <add> if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) <add> { <add> AudioAttributes attributes = new AudioAttributes.Builder() <add> .setUsage(AudioAttributes.USAGE_GAME) <add> .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) <add> .build(); <ide> <del> return null; <del> } <add> soundsContext.soundPool = new SoundPool.Builder() <add> .setAudioAttributes(attributes) <add> .build(); <add> } <add> else <add> { <add> soundsContext.soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); <add> } <add> context.getActivity().setVolumeControlStream(AudioManager.STREAM_MUSIC); <add> <add> return null; <add> } <ide> }
Java
apache-2.0
96849fa3d799ca7258d74e1f9b2dbd04c51cc478
0
apache/httpcomponents-core
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.hc.core5.reactor; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.UnresolvedAddressException; import java.nio.charset.StandardCharsets; import org.apache.hc.core5.http.nio.command.CommandSupport; import org.apache.hc.core5.io.CloseMode; import org.apache.hc.core5.io.SocketTimeoutExceptionFactory; import org.apache.hc.core5.net.InetAddressUtils; import org.apache.hc.core5.util.Timeout; /** * Implements the client side of SOCKS protocol version 5 as per https://tools.ietf.org/html/rfc1928. Supports SOCKS username/password * authentication as per https://tools.ietf.org/html/rfc1929. */ final class SocksProxyProtocolHandler implements IOEventHandler { private static final int MAX_COMMAND_CONNECT_LENGTH = 22; private static final byte CLIENT_VERSION = 5; private static final byte NO_AUTHENTICATION_REQUIRED = 0; private static final byte USERNAME_PASSWORD = 2; private static final byte USERNAME_PASSWORD_VERSION = 1; private static final byte SUCCESS = 0; private static final byte COMMAND_CONNECT = 1; private static final byte ATYP_DOMAINNAME = 3; private enum State { SEND_AUTH, RECEIVE_AUTH_METHOD, SEND_USERNAME_PASSWORD, RECEIVE_AUTH, SEND_CONNECT, RECEIVE_RESPONSE_CODE, RECEIVE_ADDRESS_TYPE, RECEIVE_ADDRESS, COMPLETE } private final ProtocolIOSession ioSession; private final Object attachment; private final InetSocketAddress targetAddress; private final String username; private final String password; private final IOEventHandlerFactory eventHandlerFactory; // a 32 byte buffer is enough for all usual SOCKS negotiations, we expand it if necessary during the processing private ByteBuffer buffer = ByteBuffer.allocate(32); private State state = State.SEND_AUTH; SocksProxyProtocolHandler(final ProtocolIOSession ioSession, final Object attachment, final InetSocketAddress targetAddress, final String username, final String password, final IOEventHandlerFactory eventHandlerFactory) { this.ioSession = ioSession; this.attachment = attachment; this.targetAddress = targetAddress; this.username = username; this.password = password; this.eventHandlerFactory = eventHandlerFactory; } @Override public void connected(final IOSession session) throws IOException { this.buffer.put(CLIENT_VERSION); this.buffer.put((byte) 1); this.buffer.put(NO_AUTHENTICATION_REQUIRED); this.buffer.flip(); session.setEventMask(SelectionKey.OP_WRITE); } @Override public void outputReady(final IOSession session) throws IOException { switch (this.state) { case SEND_AUTH: if (writeAndPrepareRead(session, 2)) { session.setEventMask(SelectionKey.OP_READ); this.state = State.RECEIVE_AUTH_METHOD; } break; case SEND_USERNAME_PASSWORD: if (writeAndPrepareRead(session, 2)) { session.setEventMask(SelectionKey.OP_READ); this.state = State.RECEIVE_AUTH; } break; case SEND_CONNECT: if (writeAndPrepareRead(session, 2)) { session.setEventMask(SelectionKey.OP_READ); this.state = State.RECEIVE_RESPONSE_CODE; } break; case RECEIVE_AUTH_METHOD: case RECEIVE_AUTH: case RECEIVE_ADDRESS: case RECEIVE_ADDRESS_TYPE: case RECEIVE_RESPONSE_CODE: session.setEventMask(SelectionKey.OP_READ); break; case COMPLETE: break; } } @Override public void inputReady(final IOSession session, final ByteBuffer src) throws IOException { if (src != null) { try { this.buffer.put(src); } catch (final BufferOverflowException ex) { throw new IOException("Unexpected input data"); } } switch (this.state) { case RECEIVE_AUTH_METHOD: if (fillBuffer(session)) { this.buffer.flip(); final byte serverVersion = this.buffer.get(); final byte serverMethod = this.buffer.get(); if (serverVersion != CLIENT_VERSION) { throw new IOException("SOCKS server returned unsupported version: " + serverVersion); } if (serverMethod == USERNAME_PASSWORD) { this.buffer.clear(); setBufferLimit(this.username.length() + this.password.length() + 3); this.buffer.put(USERNAME_PASSWORD_VERSION); this.buffer.put((byte) this.username.length()); this.buffer.put(this.username.getBytes(StandardCharsets.ISO_8859_1)); this.buffer.put((byte) this.password.length()); this.buffer.put(this.password.getBytes(StandardCharsets.ISO_8859_1)); session.setEventMask(SelectionKey.OP_WRITE); this.state = State.SEND_USERNAME_PASSWORD; } else if (serverMethod == NO_AUTHENTICATION_REQUIRED) { prepareConnectCommand(); session.setEventMask(SelectionKey.OP_WRITE); this.state = State.SEND_CONNECT; } else { throw new IOException("SOCKS server return unsupported authentication method: " + serverMethod); } } break; case RECEIVE_AUTH: if (fillBuffer(session)) { this.buffer.flip(); this.buffer.get(); // skip server auth version final byte status = this.buffer.get(); if (status != SUCCESS) { throw new IOException("Authentication failed for external SOCKS proxy"); } prepareConnectCommand(); session.setEventMask(SelectionKey.OP_WRITE); this.state = State.SEND_CONNECT; } break; case RECEIVE_RESPONSE_CODE: if (fillBuffer(session)) { this.buffer.flip(); final byte serverVersion = this.buffer.get(); final byte responseCode = this.buffer.get(); if (serverVersion != CLIENT_VERSION) { throw new IOException("SOCKS server returned unsupported version: " + serverVersion); } if (responseCode != SUCCESS) { throw new IOException("SOCKS server was unable to establish connection returned error code: " + responseCode); } this.buffer.compact(); this.buffer.limit(3); this.state = State.RECEIVE_ADDRESS_TYPE; // deliberate fall-through } else { break; } case RECEIVE_ADDRESS_TYPE: if (fillBuffer(session)) { this.buffer.flip(); this.buffer.get(); // reserved byte that has no purpose final byte aType = this.buffer.get(); final int addressSize; if (aType == InetAddressUtils.IPV4) { addressSize = 4; } else if (aType == InetAddressUtils.IPV6) { addressSize = 16; } else if (aType == ATYP_DOMAINNAME) { // mask with 0xFF to convert to unsigned byte value addressSize = this.buffer.get() & 0xFF; } else { throw new IOException("SOCKS server returned unsupported address type: " + aType); } final int remainingResponseSize = addressSize + 2; this.buffer.compact(); // make sure we only read what we need to, don't read too much this.buffer.limit(remainingResponseSize); this.state = State.RECEIVE_ADDRESS; // deliberate fall-through } else { break; } case RECEIVE_ADDRESS: if (fillBuffer(session)) { this.buffer.clear(); this.state = State.COMPLETE; final IOEventHandler newHandler = this.eventHandlerFactory.createHandler(this.ioSession, this.attachment); this.ioSession.upgrade(newHandler); newHandler.connected(this.ioSession); } break; case SEND_AUTH: case SEND_USERNAME_PASSWORD: case SEND_CONNECT: session.setEventMask(SelectionKey.OP_WRITE); break; case COMPLETE: break; } } private void prepareConnectCommand() throws IOException { final InetAddress address = this.targetAddress.getAddress(); final int port = this.targetAddress.getPort(); if (address == null || port == 0) { throw new UnresolvedAddressException(); } this.buffer.clear(); setBufferLimit(MAX_COMMAND_CONNECT_LENGTH); this.buffer.put(CLIENT_VERSION); this.buffer.put(COMMAND_CONNECT); this.buffer.put((byte) 0); // reserved if (address instanceof Inet4Address) { this.buffer.put(InetAddressUtils.IPV4); } else if (address instanceof Inet6Address) { this.buffer.put(InetAddressUtils.IPV6); } else { throw new IOException("Unsupported remote address class: " + address.getClass().getName()); } this.buffer.put(address.getAddress()); this.buffer.putShort((short) port); this.buffer.flip(); } private void setBufferLimit(final int newLimit) { if (this.buffer.capacity() < newLimit) { final ByteBuffer newBuffer = ByteBuffer.allocate(newLimit); this.buffer.flip(); newBuffer.put(this.buffer); this.buffer = newBuffer; } else { this.buffer.limit(newLimit); } } private boolean writeAndPrepareRead(final ByteChannel channel, final int readSize) throws IOException { if (writeBuffer(channel)) { this.buffer.clear(); setBufferLimit(readSize); return true; } return false; } private boolean writeBuffer(final ByteChannel channel) throws IOException { if (this.buffer.hasRemaining()) { channel.write(this.buffer); } return !this.buffer.hasRemaining(); } private boolean fillBuffer(final ByteChannel channel) throws IOException { if (this.buffer.hasRemaining()) { channel.read(this.buffer); } return !this.buffer.hasRemaining(); } @Override public void timeout(final IOSession session, final Timeout timeout) throws IOException { exception(session, SocketTimeoutExceptionFactory.create(timeout)); } @Override public void exception(final IOSession session, final Exception cause) { session.close(CloseMode.IMMEDIATE); CommandSupport.failCommands(session, cause); } @Override public void disconnected(final IOSession session) { CommandSupport.cancelCommands(session); } }
httpcore5/src/main/java/org/apache/hc/core5/reactor/SocksProxyProtocolHandler.java
/* * ==================================================================== * 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.hc.core5.reactor; import java.io.IOException; import java.net.Inet4Address; import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.BufferOverflowException; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.UnresolvedAddressException; import java.nio.charset.StandardCharsets; import org.apache.hc.core5.http.nio.command.CommandSupport; import org.apache.hc.core5.io.CloseMode; import org.apache.hc.core5.io.SocketTimeoutExceptionFactory; import org.apache.hc.core5.net.InetAddressUtils; import org.apache.hc.core5.util.Timeout; /** * Implements the client side of SOCKS protocol version 5 as per https://tools.ietf.org/html/rfc1928. Supports SOCKS username/password * authentication as per https://tools.ietf.org/html/rfc1929. */ final class SocksProxyProtocolHandler implements IOEventHandler { private static final int MAX_COMMAND_CONNECT_LENGTH = 22; private static final byte CLIENT_VERSION = 5; private static final byte NO_AUTHENTICATION_REQUIRED = 0; private static final byte USERNAME_PASSWORD = 2; private static final byte USERNAME_PASSWORD_VERSION = 1; private static final byte SUCCESS = 0; private static final byte COMMAND_CONNECT = 1; private static final byte ATYP_DOMAINNAME = 3; private enum State { SEND_AUTH, RECEIVE_AUTH_METHOD, SEND_USERNAME_PASSWORD, RECEIVE_AUTH, SEND_CONNECT, RECEIVE_RESPONSE_CODE, RECEIVE_ADDRESS_TYPE, RECEIVE_ADDRESS, COMPLETE } private final ProtocolIOSession ioSession; private final Object attachment; private final InetSocketAddress targetAddress; private final String username; private final String password; private final IOEventHandlerFactory eventHandlerFactory; // a 32 byte buffer is enough for all usual SOCKS negotiations, we expand it if necessary during the processing private ByteBuffer buffer = ByteBuffer.allocate(32); private State state = State.SEND_AUTH; private int remainingResponseSize = -1; SocksProxyProtocolHandler(final ProtocolIOSession ioSession, final Object attachment, final InetSocketAddress targetAddress, final String username, final String password, final IOEventHandlerFactory eventHandlerFactory) { this.ioSession = ioSession; this.attachment = attachment; this.targetAddress = targetAddress; this.username = username; this.password = password; this.eventHandlerFactory = eventHandlerFactory; } @Override public void connected(final IOSession session) throws IOException { this.buffer.put(CLIENT_VERSION); this.buffer.put((byte) 1); this.buffer.put(NO_AUTHENTICATION_REQUIRED); this.buffer.flip(); session.setEventMask(SelectionKey.OP_WRITE); } @Override public void outputReady(final IOSession session) throws IOException { switch (this.state) { case SEND_AUTH: if (writeAndPrepareRead(session, 2)) { session.setEventMask(SelectionKey.OP_READ); this.state = State.RECEIVE_AUTH_METHOD; } break; case SEND_USERNAME_PASSWORD: if (writeAndPrepareRead(session, 2)) { session.setEventMask(SelectionKey.OP_READ); this.state = State.RECEIVE_AUTH; } break; case SEND_CONNECT: if (writeAndPrepareRead(session, 2)) { session.setEventMask(SelectionKey.OP_READ); this.state = State.RECEIVE_RESPONSE_CODE; } break; case RECEIVE_AUTH_METHOD: case RECEIVE_AUTH: case RECEIVE_ADDRESS: case RECEIVE_ADDRESS_TYPE: case RECEIVE_RESPONSE_CODE: session.setEventMask(SelectionKey.OP_READ); break; case COMPLETE: break; } } @Override public void inputReady(final IOSession session, final ByteBuffer src) throws IOException { if (src != null) { try { this.buffer.put(src); } catch (final BufferOverflowException ex) { throw new IOException("Unexpected input data"); } } switch (this.state) { case RECEIVE_AUTH_METHOD: if (fillBuffer(session)) { this.buffer.flip(); final byte serverVersion = this.buffer.get(); final byte serverMethod = this.buffer.get(); if (serverVersion != CLIENT_VERSION) { throw new IOException("SOCKS server returned unsupported version: " + serverVersion); } if (serverMethod == USERNAME_PASSWORD) { this.buffer.clear(); setBufferLimit(this.username.length() + this.password.length() + 3); this.buffer.put(USERNAME_PASSWORD_VERSION); this.buffer.put((byte) this.username.length()); this.buffer.put(this.username.getBytes(StandardCharsets.ISO_8859_1)); this.buffer.put((byte) this.password.length()); this.buffer.put(this.password.getBytes(StandardCharsets.ISO_8859_1)); session.setEventMask(SelectionKey.OP_WRITE); this.state = State.SEND_USERNAME_PASSWORD; } else if (serverMethod == NO_AUTHENTICATION_REQUIRED) { prepareConnectCommand(); session.setEventMask(SelectionKey.OP_WRITE); this.state = State.SEND_CONNECT; } else { throw new IOException("SOCKS server return unsupported authentication method: " + serverMethod); } } break; case RECEIVE_AUTH: if (fillBuffer(session)) { this.buffer.flip(); this.buffer.get(); // skip server auth version final byte status = this.buffer.get(); if (status != SUCCESS) { throw new IOException("Authentication failed for external SOCKS proxy"); } prepareConnectCommand(); session.setEventMask(SelectionKey.OP_WRITE); this.state = State.SEND_CONNECT; } break; case RECEIVE_RESPONSE_CODE: if (fillBuffer(session)) { this.buffer.flip(); final byte serverVersion = this.buffer.get(); final byte responseCode = this.buffer.get(); if (serverVersion != CLIENT_VERSION) { throw new IOException("SOCKS server returned unsupported version: " + serverVersion); } if (responseCode != SUCCESS) { throw new IOException("SOCKS server was unable to establish connection returned error code: " + responseCode); } this.buffer.compact(); this.buffer.limit(3); this.state = State.RECEIVE_ADDRESS_TYPE; // deliberate fall-through } else { break; } case RECEIVE_ADDRESS_TYPE: if (fillBuffer(session)) { this.buffer.flip(); this.buffer.get(); // reserved byte that has no purpose final byte aType = this.buffer.get(); final int addressSize; if (aType == InetAddressUtils.IPV4) { addressSize = 4; } else if (aType == InetAddressUtils.IPV6) { addressSize = 16; } else if (aType == ATYP_DOMAINNAME) { // mask with 0xFF to convert to unsigned byte value addressSize = this.buffer.get() & 0xFF; } else { throw new IOException("SOCKS server returned unsupported address type: " + aType); } this.remainingResponseSize = addressSize + 2; this.buffer.compact(); // make sure we only read what we need to, don't read too much this.buffer.limit(this.remainingResponseSize); this.state = State.RECEIVE_ADDRESS; // deliberate fall-through } else { break; } case RECEIVE_ADDRESS: if (fillBuffer(session)) { this.buffer.clear(); this.state = State.COMPLETE; final IOEventHandler newHandler = this.eventHandlerFactory.createHandler(this.ioSession, this.attachment); this.ioSession.upgrade(newHandler); newHandler.connected(this.ioSession); } break; case SEND_AUTH: case SEND_USERNAME_PASSWORD: case SEND_CONNECT: session.setEventMask(SelectionKey.OP_WRITE); break; case COMPLETE: break; } } private void prepareConnectCommand() throws IOException { final InetAddress address = this.targetAddress.getAddress(); final int port = this.targetAddress.getPort(); if (address == null || port == 0) { throw new UnresolvedAddressException(); } this.buffer.clear(); setBufferLimit(MAX_COMMAND_CONNECT_LENGTH); this.buffer.put(CLIENT_VERSION); this.buffer.put(COMMAND_CONNECT); this.buffer.put((byte) 0); // reserved if (address instanceof Inet4Address) { this.buffer.put(InetAddressUtils.IPV4); this.buffer.put(address.getAddress()); } else if (address instanceof Inet6Address) { this.buffer.put(InetAddressUtils.IPV6); this.buffer.put(address.getAddress()); } else { throw new IOException("Unsupported remote address class: " + address.getClass().getName()); } this.buffer.putShort((short) port); this.buffer.flip(); } private void setBufferLimit(final int newLimit) { if (this.buffer.capacity() < newLimit) { final ByteBuffer newBuffer = ByteBuffer.allocate(newLimit); this.buffer.flip(); newBuffer.put(this.buffer); this.buffer = newBuffer; } else { this.buffer.limit(newLimit); } } private boolean writeAndPrepareRead(final ByteChannel channel, final int readSize) throws IOException { if (writeBuffer(channel)) { this.buffer.clear(); setBufferLimit(readSize); return true; } return false; } private boolean writeBuffer(final ByteChannel channel) throws IOException { if (this.buffer.hasRemaining()) { channel.write(this.buffer); } return !this.buffer.hasRemaining(); } private boolean fillBuffer(final ByteChannel channel) throws IOException { if (this.buffer.hasRemaining()) { channel.read(this.buffer); } return !this.buffer.hasRemaining(); } @Override public void timeout(final IOSession session, final Timeout timeout) throws IOException { exception(session, SocketTimeoutExceptionFactory.create(timeout)); } @Override public void exception(final IOSession session, final Exception cause) { session.close(CloseMode.IMMEDIATE); CommandSupport.failCommands(session, cause); } @Override public void disconnected(final IOSession session) { CommandSupport.cancelCommands(session); } }
Minor cleanup (#354)
httpcore5/src/main/java/org/apache/hc/core5/reactor/SocksProxyProtocolHandler.java
Minor cleanup (#354)
<ide><path>ttpcore5/src/main/java/org/apache/hc/core5/reactor/SocksProxyProtocolHandler.java <ide> // a 32 byte buffer is enough for all usual SOCKS negotiations, we expand it if necessary during the processing <ide> private ByteBuffer buffer = ByteBuffer.allocate(32); <ide> private State state = State.SEND_AUTH; <del> private int remainingResponseSize = -1; <del> <ide> SocksProxyProtocolHandler(final ProtocolIOSession ioSession, final Object attachment, final InetSocketAddress targetAddress, <ide> final String username, final String password, final IOEventHandlerFactory eventHandlerFactory) { <ide> this.ioSession = ioSession; <ide> } else { <ide> throw new IOException("SOCKS server returned unsupported address type: " + aType); <ide> } <del> this.remainingResponseSize = addressSize + 2; <add> final int remainingResponseSize = addressSize + 2; <ide> this.buffer.compact(); <ide> // make sure we only read what we need to, don't read too much <del> this.buffer.limit(this.remainingResponseSize); <add> this.buffer.limit(remainingResponseSize); <ide> this.state = State.RECEIVE_ADDRESS; <ide> // deliberate fall-through <ide> } else { <ide> this.buffer.put((byte) 0); // reserved <ide> if (address instanceof Inet4Address) { <ide> this.buffer.put(InetAddressUtils.IPV4); <del> this.buffer.put(address.getAddress()); <ide> } else if (address instanceof Inet6Address) { <ide> this.buffer.put(InetAddressUtils.IPV6); <del> this.buffer.put(address.getAddress()); <ide> } else { <ide> throw new IOException("Unsupported remote address class: " + address.getClass().getName()); <ide> } <add> this.buffer.put(address.getAddress()); <ide> this.buffer.putShort((short) port); <ide> this.buffer.flip(); <ide> }
JavaScript
mit
5116b20def742dcd32530fb2cbcb9bb0eb409a86
0
flaviocopes/grav-plugin-shoppingcart,flaviocopes/grav-plugin-shoppingcart,flaviocopes/grav-plugin-shoppingcart,flaviocopes/grav-plugin-shoppingcart
(function(ShoppingCart) { ShoppingCart.processCheckoutFormSubmission = function processCheckoutFormSubmission() { var that = this; /********************************************************/ /* Function called if I later can go on with the checkout /********************************************************/ var _goOnWithCheckout = function _goOnWithCheckout() { var randomToken = function randomToken(length) { var upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var lower = 'abcdefghijklmnopqrstuvwxyz'; var number = '0123456789'; var token = '', i; var seed = upper + lower + number; length = length || 13; for (i = 0; i < length; i++) { token += seed[Math.floor(Math.random() * (seed.length - 1))]; } return token; }; var url = ''; var token = randomToken(10); var shippingMethod = {}; //Determine shipping method if (ShoppingCart.settings.shipping.methods.length === 0) { shippingMethod = { method: '', cost: 0 }; } else if (ShoppingCart.settings.shipping.methods.length === 1) { shippingMethod = { method: ShoppingCart.settings.shipping.methods[0].name, cost: ShoppingCart.settings.shipping.methods[0].price }; } else { shippingMethod = { method: jQuery('.js__shipping__method').val(), cost: ShoppingCart.shippingPrice }; } //Store in localstorage storejs.set('grav-shoppingcart-shipping-method', shippingMethod); storejs.set('grav-shoppingcart-order-token', { token: token }); //Calculate the order price var orderPrice = ShoppingCart.totalOrderPriceIncludingTaxes; if (!orderPrice) { orderPrice = 0; var i = 0; var cart = ShoppingCart.items; while (i < cart.length) { orderPrice += cart[i].product.price * cart[i].quantity; i++; } } ////////////////////////////////////////////////////////// //Add shipping costs to the order price ////////////////////////////////////////////////////////// ShoppingCart.generateShippingPrice(); orderPrice = parseFloat(parseFloat(orderPrice) + parseFloat(ShoppingCart.shippingPrice)).toFixed(2); ShoppingCart.totalOrderPrice = orderPrice; ////////////////////////////////////////////////////////// //Remove coupon discount from the total amount ////////////////////////////////////////////////////////// if (!ShoppingCart.amountOfDiscount) ShoppingCart.amountOfDiscount = 0; ShoppingCart.totalOrderPrice = parseFloat(parseFloat(parseFloat(ShoppingCart.totalOrderPrice) - parseFloat(ShoppingCart.amountOfDiscount)).toFixed(2)).toFixed(2); jQuery(that).attr('disabled', 'disabled'); jQuery(document).trigger('proceedToPayment', ShoppingCart); }; var address = { firstname: jQuery('.js__billing__firstname').val(), lastname: jQuery('.js__billing__lastname').val(), email: jQuery('.js__billing__email').val(), telephone: jQuery('.js__billing__telephone').val(), address1: jQuery('.js__billing__address').val(), address2: '', city: jQuery('.js__billing__city').val(), zip: jQuery('.js__billing__zip').val(), country: jQuery('.js__billing__country').val(), state: jQuery('.js__billing__state').val(), province: jQuery('.js__billing__province').val() }; if (address.country != 'US' && !address.province) { alert(window.PLUGIN_SHOPPINGCART.translations.PLEASE_FILL_ALL_THE_REQUIRED_FIELDS); return; } ShoppingCart.shippingAddress = address; storejs.set('grav-shoppingcart-person-address', address); //Store address info in cookie ShoppingCart.gateway = jQuery('.js__payment__method').val(); _goOnWithCheckout(); }; /***********************************************************/ /* Get the shipping options based on the settings /***********************************************************/ ShoppingCart.populateShippingOptions = function populateShippingOptions() { var shippingMethods = []; for (index in ShoppingCart.settings.shipping.methods) { shippingMethods[index] = ShoppingCart.settings.shipping.methods[index]; } var methodIsAllowedInCountry = function methodIsAllowedInCountry(method, country) { for (index in method.allowedCountries) { if (method.allowedCountries[index] == country) return true; if (method.allowedCountries[index] == '*') return true; } return false; }; var ifIsGenericThereIsNoCountrySpecificMethod = function ifIsGenericThereIsNoCountrySpecificMethod(method, country) { return true; }; var orderWeightIsAllowedForThisMethod = function orderWeightIsAllowedForThisMethod(method) { return true; }; var orderPriceIsAllowedForThisMethod = function orderPriceIsAllowedForThisMethod(method) { return true; }; if (jQuery('.js__billing__country').val() === 'US') { jQuery('.js__billing__state__control').show(); jQuery('.js__billing__province__control').hide(); } else { jQuery('.js__billing__state__control').hide(); jQuery('.js__billing__province__control').show(); } if (shippingMethods.length === 0) { jQuery('.checkout-choose-shipping-block').hide(); } else if (shippingMethods.length === 1) { var priceBlock = shippingMethods[0].price + ' ' + ShoppingCart.getCurrentCurrencySymbol(); if (ShoppingCart.settings.ui.currencySymbolPosition === 'before') { priceBlock = ShoppingCart.getCurrentCurrencySymbol() + ' ' + shippingMethods[0].price; } jQuery('.checkout-choose-shipping-block .form-select-wrapper').html(shippingMethods[0].name + ' - ' + priceBlock); jQuery('.checkout-choose-shipping-block').show(); } else { var select = document.getElementById('js__shipping__method'); if (select) { //Calculate shipping methods for the shipping country select.options.length = 0; ShoppingCart.generateShippingPrice(); for (index in shippingMethods) { if (shippingMethods.hasOwnProperty(index)) { method = shippingMethods[index]; if (methodIsAllowedInCountry(method, ShoppingCart.shippingAddress.country) && ifIsGenericThereIsNoCountrySpecificMethod(method, ShoppingCart.shippingAddress.country) && orderWeightIsAllowedForThisMethod(method) && orderPriceIsAllowedForThisMethod(method)) { var priceBlock = method.price + ' ' + ShoppingCart.getCurrentCurrencySymbol(); if (ShoppingCart.settings.ui.currencySymbolPosition === 'before') { priceBlock = ShoppingCart.getCurrentCurrencySymbol() + ' ' + shippingMethods[index].price; } select.options[select.options.length] = new Option(method.name + ' - ' + priceBlock, method.name); } } } } jQuery('.checkout-choose-shipping-block').show(); } }; /***********************************************************/ /* Get the payment options based on the settings /***********************************************************/ ShoppingCart.populatePaymentOptions = function populatePaymentOptions() { jQuery('.checkout-choose-payment-block').hide(); jQuery('.checkout-choose-payment-block-title').hide(); var paymentMethods = []; for (index in ShoppingCart.settings.payment.methods) { paymentMethods[index] = ShoppingCart.settings.payment.methods[index]; } var paymentMethodsCount = 0; for (index in paymentMethods) { if (paymentMethods.hasOwnProperty(index)) { paymentMethodsCount++; } } var select = document.getElementById('js__payment__method'); if (select) { select.options.length = 0; for (index in paymentMethods) { if (paymentMethods.hasOwnProperty(index)) { method = paymentMethods[index]; select.options[select.options.length] = new Option(method.name, index); } } } if (paymentMethodsCount > 1) { jQuery('.checkout-choose-payment-block').show(); jQuery('.checkout-choose-payment-block-title').show(); } }; /***********************************************************/ /* Setup the checkout page /***********************************************************/ ShoppingCart.setupCheckout = function setupCheckout() { if (!storejs.get('grav-shoppingcart-basket-data') || storejs.get('grav-shoppingcart-basket-data').length == 0) { jQuery('.js__checkout__block').html(window.PLUGIN_SHOPPINGCART.translations.NO_ITEMS_IN_CART); jQuery('.js__checkout__block').show(); return; } jQuery('.js__checkout__block').show(); //I have items in the cart, I can go on var countries = ShoppingCart.getCountries(); var select = document.getElementById('js__billing__country'); if (select) { for (index in countries) { if (ShoppingCart.countryCanBuy(countries[index].code)) { select.options[select.options.length] = new Option(countries[index].name, countries[index].code); } } } var states = ShoppingCart.getUSAStates(); select = document.getElementById('js__billing__state'); if (select) { for (var i = 0; i < states.length; i++) { select.options[select.options.length] = new Option(states[i].name, states[i].code); } } var _stateChanged = function _stateChanged() { //Calculate immediately the shipping address, so it's used for taxes if (!ShoppingCart.shippingAddress) { ShoppingCart.shippingAddress = { state: jQuery('.js__billing__state').val(), }; } else { ShoppingCart.shippingAddress.state = jQuery('.js__billing__state').val(); } ShoppingCart.calculateTotalPriceIncludingTaxes(); ShoppingCart.calculateTotalPriceIncludingTaxesAndShipping(); ShoppingCart.renderCart(); }; /***********************************************************/ /* Called when first populating the country field with the default /* country, and when the user changes the country. /* Used to calculate the default shipping price too. /***********************************************************/ var _countryChanged = function _countryChanged() { //Calculate immediately the shipping price, so it's shown in the cart if (!ShoppingCart.shippingAddress) { ShoppingCart.shippingAddress = { country: jQuery('.js__billing__country').val(), }; } else { ShoppingCart.shippingAddress.country = jQuery('.js__billing__country').val(); } ShoppingCart.populateShippingOptions(); ShoppingCart.generateShippingPrice(); if (jQuery('.js__billing__country').val() === 'US') { jQuery('.js__billing__state__control').show(); jQuery('.js__billing__province__control').hide(); } else { jQuery('.js__billing__state__control').hide(); jQuery('.js__billing__province__control').show(); } ShoppingCart.calculateTotalPriceIncludingTaxes(); ShoppingCart.calculateTotalPriceIncludingTaxesAndShipping(); ShoppingCart.renderCart(); }; jQuery("#js__billing__country").val(ShoppingCart.settings.general.defaultCountry || 'US'); _countryChanged(); ShoppingCart.populatePaymentOptions(); if ((ShoppingCart.settings.general.defaultCountry || 'US') === 'US') { jQuery('.js__billing__state__control').show(); _stateChanged(); } else { jQuery('.js__billing__province__control').show(); } jQuery(document).delegate('.js__billing__country', 'change', function() { _countryChanged(); }); jQuery(document).delegate('.js__billing__state', 'change', function() { _stateChanged(); }); }; })(window.ShoppingCart);
js/shoppingcart_checkout.js
(function(ShoppingCart) { ShoppingCart.processCheckoutFormSubmission = function processCheckoutFormSubmission() { var that = this; /********************************************************/ /* Function called if I later can go on with the checkout /********************************************************/ var _goOnWithCheckout = function _goOnWithCheckout() { var randomToken = function randomToken(length) { var upper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; var lower = 'abcdefghijklmnopqrstuvwxyz'; var number = '0123456789'; var token = '', i; var seed = upper + lower + number; length = length || 13; for (i = 0; i < length; i++) { token += seed[Math.floor(Math.random() * (seed.length - 1))]; } return token; }; var url = ''; var token = randomToken(10); var paymentMethod = 'stripe'; var shippingMethod = {}; //Determine shipping method if (ShoppingCart.settings.shipping.methods.length === 0) { shippingMethod = { method: '', cost: 0 }; } else if (ShoppingCart.settings.shipping.methods.length === 1) { shippingMethod = { method: ShoppingCart.settings.shipping.methods[0].name, cost: ShoppingCart.settings.shipping.methods[0].price }; } else { shippingMethod = { method: jQuery('.js__shipping__method').val(), cost: ShoppingCart.shippingPrice }; } //Store in localstorage storejs.set('grav-shoppingcart-shipping-method', shippingMethod); storejs.set('grav-shoppingcart-payment-method', { method: paymentMethod }); storejs.set('grav-shoppingcart-order-token', { token: token }); //Calculate the order price var orderPrice = ShoppingCart.totalOrderPriceIncludingTaxes; if (!orderPrice) { orderPrice = 0; var i = 0; var cart = ShoppingCart.items; while (i < cart.length) { orderPrice += cart[i].product.price * cart[i].quantity; i++; } } ////////////////////////////////////////////////////////// //Add shipping costs to the order price ////////////////////////////////////////////////////////// ShoppingCart.generateShippingPrice(); orderPrice = parseFloat(parseFloat(orderPrice) + parseFloat(ShoppingCart.shippingPrice)).toFixed(2); ShoppingCart.totalOrderPrice = orderPrice; ////////////////////////////////////////////////////////// //Remove coupon discount from the total amount ////////////////////////////////////////////////////////// if (!ShoppingCart.amountOfDiscount) ShoppingCart.amountOfDiscount = 0; ShoppingCart.totalOrderPrice = parseFloat(parseFloat(parseFloat(ShoppingCart.totalOrderPrice) - parseFloat(ShoppingCart.amountOfDiscount)).toFixed(2)).toFixed(2); jQuery(that).attr('disabled', 'disabled'); jQuery(document).trigger('proceedToPayment', ShoppingCart); }; var address = { firstname: jQuery('.js__billing__firstname').val(), lastname: jQuery('.js__billing__lastname').val(), email: jQuery('.js__billing__email').val(), telephone: jQuery('.js__billing__telephone').val(), address1: jQuery('.js__billing__address').val(), address2: '', city: jQuery('.js__billing__city').val(), zip: jQuery('.js__billing__zip').val(), country: jQuery('.js__billing__country').val(), state: jQuery('.js__billing__state').val(), province: jQuery('.js__billing__province').val() }; if (address.country != 'US' && !address.province) { alert(window.PLUGIN_SHOPPINGCART.translations.PLEASE_FILL_ALL_THE_REQUIRED_FIELDS); return; } ShoppingCart.shippingAddress = address; storejs.set('grav-shoppingcart-person-address', address); //Store address info in cookie ShoppingCart.gateway = jQuery('.js__payment__method').val(); _goOnWithCheckout(); }; /***********************************************************/ /* Get the shipping options based on the settings /***********************************************************/ ShoppingCart.populateShippingOptions = function populateShippingOptions() { var shippingMethods = []; for (index in ShoppingCart.settings.shipping.methods) { shippingMethods[index] = ShoppingCart.settings.shipping.methods[index]; } var methodIsAllowedInCountry = function methodIsAllowedInCountry(method, country) { for (index in method.allowedCountries) { if (method.allowedCountries[index] == country) return true; if (method.allowedCountries[index] == '*') return true; } return false; }; var ifIsGenericThereIsNoCountrySpecificMethod = function ifIsGenericThereIsNoCountrySpecificMethod(method, country) { return true; }; var orderWeightIsAllowedForThisMethod = function orderWeightIsAllowedForThisMethod(method) { return true; }; var orderPriceIsAllowedForThisMethod = function orderPriceIsAllowedForThisMethod(method) { return true; }; if (jQuery('.js__billing__country').val() === 'US') { jQuery('.js__billing__state__control').show(); jQuery('.js__billing__province__control').hide(); } else { jQuery('.js__billing__state__control').hide(); jQuery('.js__billing__province__control').show(); } if (shippingMethods.length === 0) { jQuery('.checkout-choose-shipping-block').hide(); } else if (shippingMethods.length === 1) { var priceBlock = shippingMethods[0].price + ' ' + ShoppingCart.getCurrentCurrencySymbol(); if (ShoppingCart.settings.ui.currencySymbolPosition === 'before') { priceBlock = ShoppingCart.getCurrentCurrencySymbol() + ' ' + shippingMethods[0].price; } jQuery('.checkout-choose-shipping-block .form-select-wrapper').html(shippingMethods[0].name + ' - ' + priceBlock); jQuery('.checkout-choose-shipping-block').show(); } else { var select = document.getElementById('js__shipping__method'); if (select) { //Calculate shipping methods for the shipping country select.options.length = 0; ShoppingCart.generateShippingPrice(); for (index in shippingMethods) { if (shippingMethods.hasOwnProperty(index)) { method = shippingMethods[index]; if (methodIsAllowedInCountry(method, ShoppingCart.shippingAddress.country) && ifIsGenericThereIsNoCountrySpecificMethod(method, ShoppingCart.shippingAddress.country) && orderWeightIsAllowedForThisMethod(method) && orderPriceIsAllowedForThisMethod(method)) { var priceBlock = method.price + ' ' + ShoppingCart.getCurrentCurrencySymbol(); if (ShoppingCart.settings.ui.currencySymbolPosition === 'before') { priceBlock = ShoppingCart.getCurrentCurrencySymbol() + ' ' + shippingMethods[index].price; } select.options[select.options.length] = new Option(method.name + ' - ' + priceBlock, method.name); } } } } jQuery('.checkout-choose-shipping-block').show(); } }; /***********************************************************/ /* Get the payment options based on the settings /***********************************************************/ ShoppingCart.populatePaymentOptions = function populatePaymentOptions() { jQuery('.checkout-choose-payment-block').hide(); jQuery('.checkout-choose-payment-block-title').hide(); var paymentMethods = []; for (index in ShoppingCart.settings.payment.methods) { paymentMethods[index] = ShoppingCart.settings.payment.methods[index]; } var paymentMethodsCount = 0; for (index in paymentMethods) { if (paymentMethods.hasOwnProperty(index)) { paymentMethodsCount++; } } var select = document.getElementById('js__payment__method'); if (select) { select.options.length = 0; for (index in paymentMethods) { if (paymentMethods.hasOwnProperty(index)) { method = paymentMethods[index]; select.options[select.options.length] = new Option(method.name, index); } } } if (paymentMethodsCount > 1) { jQuery('.checkout-choose-payment-block').show(); jQuery('.checkout-choose-payment-block-title').show(); } }; /***********************************************************/ /* Setup the checkout page /***********************************************************/ ShoppingCart.setupCheckout = function setupCheckout() { if (!storejs.get('grav-shoppingcart-basket-data') || storejs.get('grav-shoppingcart-basket-data').length == 0) { jQuery('.js__checkout__block').html(window.PLUGIN_SHOPPINGCART.translations.NO_ITEMS_IN_CART); jQuery('.js__checkout__block').show(); return; } jQuery('.js__checkout__block').show(); //I have items in the cart, I can go on var countries = ShoppingCart.getCountries(); var select = document.getElementById('js__billing__country'); if (select) { for (index in countries) { if (ShoppingCart.countryCanBuy(countries[index].code)) { select.options[select.options.length] = new Option(countries[index].name, countries[index].code); } } } var states = ShoppingCart.getUSAStates(); select = document.getElementById('js__billing__state'); if (select) { for (var i = 0; i < states.length; i++) { select.options[select.options.length] = new Option(states[i].name, states[i].code); } } var _stateChanged = function _stateChanged() { //Calculate immediately the shipping address, so it's used for taxes if (!ShoppingCart.shippingAddress) { ShoppingCart.shippingAddress = { state: jQuery('.js__billing__state').val(), }; } else { ShoppingCart.shippingAddress.state = jQuery('.js__billing__state').val(); } ShoppingCart.calculateTotalPriceIncludingTaxes(); ShoppingCart.calculateTotalPriceIncludingTaxesAndShipping(); ShoppingCart.renderCart(); }; /***********************************************************/ /* Called when first populating the country field with the default /* country, and when the user changes the country. /* Used to calculate the default shipping price too. /***********************************************************/ var _countryChanged = function _countryChanged() { //Calculate immediately the shipping price, so it's shown in the cart if (!ShoppingCart.shippingAddress) { ShoppingCart.shippingAddress = { country: jQuery('.js__billing__country').val(), }; } else { ShoppingCart.shippingAddress.country = jQuery('.js__billing__country').val(); } ShoppingCart.populateShippingOptions(); ShoppingCart.generateShippingPrice(); if (jQuery('.js__billing__country').val() === 'US') { jQuery('.js__billing__state__control').show(); jQuery('.js__billing__province__control').hide(); } else { jQuery('.js__billing__state__control').hide(); jQuery('.js__billing__province__control').show(); } ShoppingCart.calculateTotalPriceIncludingTaxes(); ShoppingCart.calculateTotalPriceIncludingTaxesAndShipping(); ShoppingCart.renderCart(); }; jQuery("#js__billing__country").val(ShoppingCart.settings.general.defaultCountry || 'US'); _countryChanged(); ShoppingCart.populatePaymentOptions(); if ((ShoppingCart.settings.general.defaultCountry || 'US') === 'US') { jQuery('.js__billing__state__control').show(); _stateChanged(); } else { jQuery('.js__billing__province__control').show(); } jQuery(document).delegate('.js__billing__country', 'change', function() { _countryChanged(); }); jQuery(document).delegate('.js__billing__state', 'change', function() { _stateChanged(); }); }; })(window.ShoppingCart);
Drop unneeded statement
js/shoppingcart_checkout.js
Drop unneeded statement
<ide><path>s/shoppingcart_checkout.js <ide> <ide> var url = ''; <ide> var token = randomToken(10); <del> var paymentMethod = 'stripe'; <ide> var shippingMethod = {}; <ide> <ide> //Determine shipping method <ide> <ide> //Store in localstorage <ide> storejs.set('grav-shoppingcart-shipping-method', shippingMethod); <del> storejs.set('grav-shoppingcart-payment-method', { method: paymentMethod }); <ide> storejs.set('grav-shoppingcart-order-token', { token: token }); <ide> <ide> //Calculate the order price
Java
apache-2.0
abed30ed5cc159e2c7afd3e575c90fc86bb0846f
0
sakai-mirror/k2,sakai-mirror/k2,sakai-mirror/k2
/* * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF 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.sakaiproject.kernel.rest.friends; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.name.Named; import edu.emory.mathcs.backport.java.util.Arrays; import org.sakaiproject.kernel.api.Registry; import org.sakaiproject.kernel.api.RegistryService; import org.sakaiproject.kernel.api.jcr.support.JCRNodeFactoryServiceException; import org.sakaiproject.kernel.api.rest.RestProvider; import org.sakaiproject.kernel.api.serialization.BeanConverter; import org.sakaiproject.kernel.api.session.SessionManagerService; import org.sakaiproject.kernel.api.social.FriendsResolverService; import org.sakaiproject.kernel.api.user.ProfileResolverService; import org.sakaiproject.kernel.api.user.UserProfile; import org.sakaiproject.kernel.api.userenv.UserEnvironmentResolverService; import org.sakaiproject.kernel.model.FriendBean; import org.sakaiproject.kernel.model.FriendStatus; import org.sakaiproject.kernel.model.FriendsBean; import org.sakaiproject.kernel.model.FriendsIndexBean; import org.sakaiproject.kernel.util.StringUtils; import org.sakaiproject.kernel.util.rest.RestDescription; import org.sakaiproject.kernel.webapp.RestServiceFaultException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import javax.jcr.RepositoryException; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * The rest friends provider provides management of friends lists. These are * stored in a known place with metadata, as a json file. The service works on * the basis of adding and removing friends records from a json file. */ public class RestFriendsProvider implements RestProvider { private static final RestDescription DESC = new RestDescription(); private static final String KEY = "friend"; static { DESC.setTitle("Friends"); DESC.setShortDescription("Managed Friend Pairs"); DESC.addSection(1, "Introduction", "This service allows the management of a friends list."); DESC .addSection( 2, "Connect ", "A client may request a connection to a friend, with with the connect/request service. This starts a simple workflow" + "between the users. Once requesting, the requesting user may cancel the request. The invited friend may accept, reject or ignore" + "the request. For all these actions the response status code is " + HttpServletResponse.SC_OK + ", if the operation is denied " + "as a result of a conflicting record the response status code is " + HttpServletResponse.SC_CONFLICT); DESC .addSection( 2, "Status ", "Responds with the current users friends records. Super admins may request other users friends records. "); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.status + "/" + "/<userid>", "Accepts GET to remove get the friend list for a user. A super user may specify the user who is performing the " + "accept, otherwise its the current user. "); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.request + "/<userid>", "Accepts POST to invite a friend to this user id. A super user may specify the user who is performing the " + "invite, otherwise its the current user. The post must be accompanied by a text message and a friend to invite."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.accept + "/<userid>", "Accepts POST to accept an earlier invitation. A super user may specify the user who is performing the " + "accept, otherwise its the current user. The post must be accompanied by friend to accept."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.reject + "/<userid>", "Accepts POST to reject an earlier invitation. A super user may specify the user who is performing the " + "reject, otherwise its the current user. The post must be accompanied by friend to reject, the target user will be notified."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.ignore + "/<userid>", "Accepts POST to ignore an earlier invitation. A super user may specify the user who is performing the " + "ignore, otherwise its the current user. The post must be accompanied by friend to reject, the target user will not be notified."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.cancel + "/<userid>", "Accepts POST to cancel an earlier invitation. A super user may specify the user who is performing the " + "accept, otherwise its the current user. The post must be accompanied by friend to cancel."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.remove + "/<userid>", "Accepts POST to remove an earlier connection. A super user may specify the user who is performing the " + "accept, otherwise its the current user. The post must be accompanied by friend to cancel."); DESC.addSection(2, "POST", ""); DESC.addParameter(FriendsParams.FRIENDUUID, "the UUID of the friend"); DESC.addParameter(FriendsParams.FRIENDTYPE, "the type of the friend, a string associated with the connection."); DESC.addParameter(FriendsParams.FRIENDSTATUS, "filter a status request to only retrune the type requested."); DESC.addParameter(FriendsParams.MESSAGE, "the message associated with the request, required for requests"); DESC.addParameter(FriendsParams.PAGE, "the page of friends to respond with. (optional, default all)"); DESC.addParameter(FriendsParams.NRESUTS_PER_PAGE, "the number of friends per page. (optional, default 10)"); DESC.addParameter(FriendsParams.SORT, "an array of fields to sort on from " + Arrays.toString(FriendsSortField.values()) + " (optional)"); DESC.addParameter(FriendsParams.SORTORDER, "an array of directions to sort, from " + Arrays.toString(FriendsSortOrder.values()) + " (optional)"); DESC.addResponse(String.valueOf(HttpServletResponse.SC_OK), "If the action completed Ok"); DESC.addResponse(String.valueOf(HttpServletResponse.SC_CONFLICT), "If the request could not be compelted at this time"); DESC.addResponse(String.valueOf(HttpServletResponse.SC_FORBIDDEN), "If permission to manage the connection is denied"); DESC.addResponse(String .valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), " Any other error"); } private BeanConverter beanConverter; private SessionManagerService sessionManagerService; private UserEnvironmentResolverService userEnvironmentResolverService; private Map<String, Object> OK = ImmutableMap.of("response", (Object) "OK"); private EntityManager entityManager; private ProfileResolverService profileResolverService; private FriendsResolverService friendsResolverService; @Inject public RestFriendsProvider(RegistryService registryService, SessionManagerService sessionManagerService, UserEnvironmentResolverService userEnvironmentResolverService, ProfileResolverService profileResolverService, EntityManager entityManager, FriendsResolverService friendsResolverService, @Named(BeanConverter.REPOSITORY_BEANCONVETER) BeanConverter beanConverter) { Registry<String, RestProvider> registry = registryService .getRegistry(RestProvider.REST_REGISTRY); registry.add(this); this.beanConverter = beanConverter; this.sessionManagerService = sessionManagerService; this.userEnvironmentResolverService = userEnvironmentResolverService; this.entityManager = entityManager; this.profileResolverService = profileResolverService; this.friendsResolverService = friendsResolverService; } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.rest.RestProvider#dispatch(java.lang.String[], * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ public void dispatch(String[] elements, HttpServletRequest request, HttpServletResponse response) { try { FriendsParams params = new FriendsParams(elements, request, sessionManagerService, userEnvironmentResolverService); Map<String, Object> map = Maps.newHashMap(); switch (params.major) { case connect: if (!"POST".equals(request.getMethod())) { throw new RestServiceFaultException( HttpServletResponse.SC_METHOD_NOT_ALLOWED); } switch (params.minor) { case request: map = doRequestConnect(params, request, response); break; case accept: map = doAcceptConnect(params, request, response); break; case cancel: map = doCancelConnect(params, request, response); break; case reject: map = doRejectConnect(params, request, response); break; case ignore: map = doIgnoreConnect(params, request, response); break; case remove: map = doRemoveConnect(params, request, response); break; default: doRequestError(); break; } break; case status: if (!"GET".equals(request.getMethod())) { throw new RestServiceFaultException( HttpServletResponse.SC_METHOD_NOT_ALLOWED); } map = doStatus(params, request, response); break; default: doRequestError(); break; } if (map != null) { String responseBody = beanConverter.convertToString(map); response.setContentType(RestProvider.CONTENT_TYPE); response.getOutputStream().print(responseBody); } } catch (SecurityException ex) { throw ex; } catch (RestServiceFaultException ex) { throw ex; } catch (Exception ex) { throw new RestServiceFaultException(ex.getMessage(), ex); } } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doRemoveConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } myFriends.removeFriend(params.friendUuid); friendFriends.removeFriend(params.uuid); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doRequestConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (myFriends.hasFriend(params.friendUuid) || friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "There is already a connection invited, pending or accepted "); } FriendBean friend = new FriendBean(params.uuid, params.friendUuid, FriendStatus.PENDING); FriendBean me = new FriendBean(params.friendUuid, params.uuid, FriendStatus.INVITED); if (!StringUtils.isEmpty(params.type)) { me.setProperties(ImmutableMap.of("type", params.type, "message", params.message)); friend.setProperties(ImmutableMap.of("type", params.type, "message", params.message)); } myFriends.addFriend(friend); friendFriends.addFriend(me); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doAcceptConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } FriendBean myFriendBean = myFriends.getFriend(params.friendUuid); FriendBean friendFriendBean = friendFriends.getFriend(params.uuid); if (!myFriendBean.isInState(FriendStatus.INVITED) || !friendFriendBean.isInState(FriendStatus.PENDING)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "The invitation to connect is not current"); } myFriendBean.updateStatus(FriendStatus.ACCEPTED); friendFriendBean.updateStatus(FriendStatus.ACCEPTED); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doCancelConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } FriendBean myFriendBean = myFriends.getFriend(params.friendUuid); FriendBean friendFriendBean = friendFriends.getFriend(params.uuid); if (!myFriendBean.isInState(FriendStatus.PENDING) || !friendFriendBean.isInState(FriendStatus.INVITED)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "The invitation to connect is not current"); } myFriends.removeFriend(params.friendUuid); friendFriends.removeFriend(params.uuid); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doRejectConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } FriendBean myFriendBean = myFriends.getFriend(params.friendUuid); FriendBean friendFriendBean = friendFriends.getFriend(params.uuid); if (!myFriendBean.isInState(FriendStatus.INVITED) || !friendFriendBean.isInState(FriendStatus.PENDING)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "The invitation to connect is not current"); } myFriends.removeFriend(params.friendUuid); friendFriends.removeFriend(params.uuid); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doIgnoreConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } FriendBean myFriendBean = myFriends.getFriend(params.friendUuid); FriendBean friendFriendBean = friendFriends.getFriend(params.uuid); if (!myFriendBean.isInState(FriendStatus.INVITED) || !friendFriendBean.isInState(FriendStatus.PENDING)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "The invitation to connect is not current"); } myFriends.removeFriend(params.friendUuid); friendFriends.removeFriend(params.uuid); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws IOException * @throws RepositoryException * @throws UnsupportedEncodingException */ private Map<String, Object> doStatus(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); Query query = null; StringBuilder sb = new StringBuilder(); sb.append(FriendsIndexBean.FINDBY_UUID_WITH_SORT); if (params.filterStatus != null) { sb.append(" and ").append(FriendsIndexBean.FRIENDS_STATUS_FIELD).append( " = :").append(FriendsIndexBean.PARAM_FRIENDSTATUS); } if (params.sort != null && params.sort.length > 0) { sb.append(" order by "); for (int i = 0; i < params.sort.length; i++) { if (i != 0) { sb.append(","); } sb.append(" s.").append(params.sort[i]); if (params.sortOrder != null && params.sortOrder.length == params.sort.length) { sb.append(" ").append(params.sortOrder[i]); } } } query = entityManager.createQuery(sb.toString()); query.setFirstResult(params.start); query.setMaxResults(params.end); query.setParameter(FriendsIndexBean.PARAM_UUID, params.uuid); if (params.filterStatus != null ) { query.setParameter(FriendsIndexBean.PARAM_FRIENDSTATUS, params.filterStatus); } List<?> results = query.getResultList(); Map<String, FriendBean> myFriendMap = myFriends.friendsMap(); Map<String, FriendBean> sortedFriendMap = Maps.newLinkedHashMap(); for (Object fio : results) { FriendsIndexBean fi = (FriendsIndexBean) fio; FriendBean fb = myFriendMap.get(fi.getFriendUuid()); if (fb != null) { sortedFriendMap.put(fb.getFriendUuid(), fb); UserProfile profile = profileResolverService .resolve(fb.getFriendUuid()); fb.setProfile(profile.getProperties()); } } return ImmutableMap.of("response", "OK", "status", myFriends); } /** * */ private void doRequestError() { throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST); } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.rest.RestProvider#getDescription() */ public RestDescription getDescription() { return DESC; } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.Provider#getKey() */ public String getKey() { return KEY; } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.Provider#getPriority() */ public int getPriority() { return 0; } }
kernel/src/main/java/org/sakaiproject/kernel/rest/friends/RestFriendsProvider.java
/* * Licensed to the Sakai Foundation (SF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The SF 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.sakaiproject.kernel.rest.friends; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.inject.Inject; import com.google.inject.name.Named; import edu.emory.mathcs.backport.java.util.Arrays; import org.sakaiproject.kernel.api.Registry; import org.sakaiproject.kernel.api.RegistryService; import org.sakaiproject.kernel.api.jcr.support.JCRNodeFactoryServiceException; import org.sakaiproject.kernel.api.rest.RestProvider; import org.sakaiproject.kernel.api.serialization.BeanConverter; import org.sakaiproject.kernel.api.session.SessionManagerService; import org.sakaiproject.kernel.api.social.FriendsResolverService; import org.sakaiproject.kernel.api.user.ProfileResolverService; import org.sakaiproject.kernel.api.user.UserProfile; import org.sakaiproject.kernel.api.userenv.UserEnvironmentResolverService; import org.sakaiproject.kernel.model.FriendBean; import org.sakaiproject.kernel.model.FriendStatus; import org.sakaiproject.kernel.model.FriendsBean; import org.sakaiproject.kernel.model.FriendsIndexBean; import org.sakaiproject.kernel.util.StringUtils; import org.sakaiproject.kernel.util.rest.RestDescription; import org.sakaiproject.kernel.webapp.RestServiceFaultException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Map; import javax.jcr.RepositoryException; import javax.persistence.EntityManager; import javax.persistence.Query; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * The rest friends provider provides management of friends lists. These are * stored in a known place with metadata, as a json file. The service works on * the basis of adding and removing friends records from a json file. */ public class RestFriendsProvider implements RestProvider { private static final RestDescription DESC = new RestDescription(); private static final String KEY = "friend"; static { DESC.setTitle("Friends"); DESC.setShortDescription("Managed Friend Pairs"); DESC.addSection(1, "Introduction", "This service allows the management of a friends list."); DESC .addSection( 2, "Connect ", "A client may request a connection to a friend, with with the connect/request service. This starts a simple workflow" + "between the users. Once requesting, the requesting user may cancel the request. The invited friend may accept, reject or ignore" + "the request. For all these actions the response status code is " + HttpServletResponse.SC_OK + ", if the operation is denied " + "as a result of a conflicting record the response status code is " + HttpServletResponse.SC_CONFLICT); DESC .addSection( 2, "Status ", "Responds with the current users friends records. Super admins may request other users friends records. "); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.status + "/" + "/<userid>", "Accepts GET to remove get the friend list for a user. A super user may specify the user who is performing the " + "accept, otherwise its the current user. "); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.request + "/<userid>", "Accepts POST to invite a friend to this user id. A super user may specify the user who is performing the " + "invite, otherwise its the current user. The post must be accompanied by a text message and a friend to invite."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.accept + "/<userid>", "Accepts POST to accept an earlier invitation. A super user may specify the user who is performing the " + "accept, otherwise its the current user. The post must be accompanied by friend to accept."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.reject + "/<userid>", "Accepts POST to reject an earlier invitation. A super user may specify the user who is performing the " + "reject, otherwise its the current user. The post must be accompanied by friend to reject, the target user will be notified."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.ignore + "/<userid>", "Accepts POST to ignore an earlier invitation. A super user may specify the user who is performing the " + "ignore, otherwise its the current user. The post must be accompanied by friend to reject, the target user will not be notified."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.cancel + "/<userid>", "Accepts POST to cancel an earlier invitation. A super user may specify the user who is performing the " + "accept, otherwise its the current user. The post must be accompanied by friend to cancel."); DESC .addURLTemplate( "/rest/" + KEY + "/" + PathElement.connect + "/" + PathElement.remove + "/<userid>", "Accepts POST to remove an earlier connection. A super user may specify the user who is performing the " + "accept, otherwise its the current user. The post must be accompanied by friend to cancel."); DESC.addSection(2, "POST", ""); DESC.addParameter(FriendsParams.FRIENDUUID, "the UUID of the friend"); DESC.addParameter(FriendsParams.FRIENDTYPE, "the type of the friend, a string associated with the connection."); DESC.addParameter(FriendsParams.FRIENDSTATUS, "filter a status request to only retrune the type requested."); DESC.addParameter(FriendsParams.MESSAGE, "the message associated with the request, required for requests"); DESC.addParameter(FriendsParams.PAGE, "the page of friends to respond with. (optional, default all)"); DESC.addParameter(FriendsParams.NRESUTS_PER_PAGE, "the number of friends per page. (optional, default 10)"); DESC.addParameter(FriendsParams.SORT, "an array of fields to sort on from " + Arrays.toString(FriendsSortField.values()) + " (optional)"); DESC.addParameter(FriendsParams.SORTORDER, "an array of directions to sort, from " + Arrays.toString(FriendsSortOrder.values()) + " (optional)"); DESC.addResponse(String.valueOf(HttpServletResponse.SC_OK), "If the action completed Ok"); DESC.addResponse(String.valueOf(HttpServletResponse.SC_CONFLICT), "If the request could not be compelted at this time"); DESC.addResponse(String.valueOf(HttpServletResponse.SC_FORBIDDEN), "If permission to manage the connection is denied"); DESC.addResponse(String .valueOf(HttpServletResponse.SC_INTERNAL_SERVER_ERROR), " Any other error"); } private BeanConverter beanConverter; private SessionManagerService sessionManagerService; private UserEnvironmentResolverService userEnvironmentResolverService; private Map<String, Object> OK = ImmutableMap.of("response", (Object) "OK"); private EntityManager entityManager; private ProfileResolverService profileResolverService; private FriendsResolverService friendsResolverService; @Inject public RestFriendsProvider(RegistryService registryService, SessionManagerService sessionManagerService, UserEnvironmentResolverService userEnvironmentResolverService, ProfileResolverService profileResolverService, EntityManager entityManager, FriendsResolverService friendsResolverService, @Named(BeanConverter.REPOSITORY_BEANCONVETER) BeanConverter beanConverter) { Registry<String, RestProvider> registry = registryService .getRegistry(RestProvider.REST_REGISTRY); registry.add(this); this.beanConverter = beanConverter; this.sessionManagerService = sessionManagerService; this.userEnvironmentResolverService = userEnvironmentResolverService; this.entityManager = entityManager; this.profileResolverService = profileResolverService; this.friendsResolverService = friendsResolverService; } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.rest.RestProvider#dispatch(java.lang.String[], * javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse) */ public void dispatch(String[] elements, HttpServletRequest request, HttpServletResponse response) { try { FriendsParams params = new FriendsParams(elements, request, sessionManagerService, userEnvironmentResolverService); Map<String, Object> map = Maps.newHashMap(); switch (params.major) { case connect: if (!"POST".equals(request.getMethod())) { throw new RestServiceFaultException( HttpServletResponse.SC_METHOD_NOT_ALLOWED); } switch (params.minor) { case request: map = doRequestConnect(params, request, response); break; case accept: map = doAcceptConnect(params, request, response); break; case cancel: map = doCancelConnect(params, request, response); break; case reject: map = doRejectConnect(params, request, response); break; case ignore: map = doIgnoreConnect(params, request, response); break; case remove: map = doRemoveConnect(params, request, response); break; default: doRequestError(); break; } break; case status: if (!"GET".equals(request.getMethod())) { throw new RestServiceFaultException( HttpServletResponse.SC_METHOD_NOT_ALLOWED); } map = doStatus(params, request, response); break; default: doRequestError(); break; } if (map != null) { String responseBody = beanConverter.convertToString(map); response.setContentType(RestProvider.CONTENT_TYPE); response.getOutputStream().print(responseBody); } } catch (SecurityException ex) { throw ex; } catch (RestServiceFaultException ex) { throw ex; } catch (Exception ex) { throw new RestServiceFaultException(ex.getMessage(), ex); } } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doRemoveConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } myFriends.removeFriend(params.friendUuid); friendFriends.removeFriend(params.uuid); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doRequestConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (myFriends.hasFriend(params.friendUuid) || friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "There is already a connection invited, pending or accepted "); } FriendBean friend = new FriendBean(params.uuid, params.friendUuid, FriendStatus.PENDING); FriendBean me = new FriendBean(params.friendUuid, params.uuid, FriendStatus.INVITED); if (!StringUtils.isEmpty(params.type)) { me.setProperties(ImmutableMap.of("type", params.type, "message", params.message)); friend.setProperties(ImmutableMap.of("type", params.type, "message", params.message)); } myFriends.addFriend(friend); friendFriends.addFriend(me); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doAcceptConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } FriendBean myFriendBean = myFriends.getFriend(params.friendUuid); FriendBean friendFriendBean = friendFriends.getFriend(params.uuid); if (!myFriendBean.isInState(FriendStatus.INVITED) || !friendFriendBean.isInState(FriendStatus.PENDING)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "The invitation to connect is not current"); } myFriendBean.updateStatus(FriendStatus.ACCEPTED); friendFriendBean.updateStatus(FriendStatus.ACCEPTED); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doCancelConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } FriendBean myFriendBean = myFriends.getFriend(params.friendUuid); FriendBean friendFriendBean = friendFriends.getFriend(params.uuid); if (!myFriendBean.isInState(FriendStatus.PENDING) || !friendFriendBean.isInState(FriendStatus.INVITED)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "The invitation to connect is not current"); } myFriends.removeFriend(params.friendUuid); friendFriends.removeFriend(params.uuid); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doRejectConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } FriendBean myFriendBean = myFriends.getFriend(params.friendUuid); FriendBean friendFriendBean = friendFriends.getFriend(params.uuid); if (!myFriendBean.isInState(FriendStatus.INVITED) || !friendFriendBean.isInState(FriendStatus.PENDING)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "The invitation to connect is not current"); } myFriends.removeFriend(params.friendUuid); friendFriends.removeFriend(params.uuid); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws RepositoryException * @throws JCRNodeFactoryServiceException * @throws IOException */ private Map<String, Object> doIgnoreConnect(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws JCRNodeFactoryServiceException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); FriendsBean friendFriends = friendsResolverService .resolve(params.friendUuid); if (!myFriends.hasFriend(params.friendUuid) || !friendFriends.hasFriend(params.uuid)) { throw new RestServiceFaultException(HttpServletResponse.SC_NOT_FOUND, " The friend connection is missing "); } FriendBean myFriendBean = myFriends.getFriend(params.friendUuid); FriendBean friendFriendBean = friendFriends.getFriend(params.uuid); if (!myFriendBean.isInState(FriendStatus.INVITED) || !friendFriendBean.isInState(FriendStatus.PENDING)) { throw new RestServiceFaultException(HttpServletResponse.SC_CONFLICT, "The invitation to connect is not current"); } myFriends.removeFriend(params.friendUuid); friendFriends.removeFriend(params.uuid); myFriends.save(); friendFriends.save(); return OK; } /** * @param params * @param request * @param response * @return * @throws IOException * @throws RepositoryException * @throws UnsupportedEncodingException */ private Map<String, Object> doStatus(FriendsParams params, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, RepositoryException, IOException { FriendsBean myFriends = friendsResolverService.resolve(params.uuid); Query query = null; StringBuilder sb = new StringBuilder(); sb.append(FriendsIndexBean.FINDBY_UUID_WITH_SORT); if (params.filterStatus != null) { sb.append(" and ").append(FriendsIndexBean.FRIENDS_STATUS_FIELD).append( " = :").append(FriendsIndexBean.PARAM_FRIENDSTATUS); } if (params.sort != null && params.sort.length > 0) { sb.append(" order by "); for (int i = 0; i < params.sort.length; i++) { if (i != 0) { sb.append(","); } sb.append(params.sort[i]); if (params.sortOrder != null && params.sortOrder.length == params.sort.length) { sb.append(" ").append(params.sortOrder[i]); } } } query = entityManager.createQuery(sb.toString()); query.setFirstResult(params.start); query.setMaxResults(params.end); query.setParameter(FriendsIndexBean.PARAM_UUID, params.uuid); if (params.filterStatus != null ) { query.setParameter(FriendsIndexBean.PARAM_FRIENDSTATUS, params.filterStatus); } List<?> results = query.getResultList(); Map<String, FriendBean> myFriendMap = myFriends.friendsMap(); Map<String, FriendBean> sortedFriendMap = Maps.newLinkedHashMap(); for (Object fio : results) { FriendsIndexBean fi = (FriendsIndexBean) fio; FriendBean fb = myFriendMap.get(fi.getFriendUuid()); if (fb != null) { sortedFriendMap.put(fb.getFriendUuid(), fb); UserProfile profile = profileResolverService .resolve(fb.getFriendUuid()); fb.setProfile(profile.getProperties()); } } return ImmutableMap.of("response", "OK", "status", myFriends); } /** * */ private void doRequestError() { throw new RestServiceFaultException(HttpServletResponse.SC_BAD_REQUEST); } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.rest.RestProvider#getDescription() */ public RestDescription getDescription() { return DESC; } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.Provider#getKey() */ public String getKey() { return KEY; } /** * {@inheritDoc} * * @see org.sakaiproject.kernel.api.Provider#getPriority() */ public int getPriority() { return 0; } }
KERN-115 Fixed git-svn-id: 81ed41d7d168891742cba5e65a82c2d517ef9008@58097 fdecad78-55fc-0310-b1b2-d7d25cf747c9
kernel/src/main/java/org/sakaiproject/kernel/rest/friends/RestFriendsProvider.java
KERN-115 Fixed
<ide><path>ernel/src/main/java/org/sakaiproject/kernel/rest/friends/RestFriendsProvider.java <ide> if (i != 0) { <ide> sb.append(","); <ide> } <del> sb.append(params.sort[i]); <add> sb.append(" s.").append(params.sort[i]); <ide> if (params.sortOrder != null <ide> && params.sortOrder.length == params.sort.length) { <ide> sb.append(" ").append(params.sortOrder[i]);
Java
apache-2.0
d907daaa820ad88510b65bb01d4f5c01e279e3e7
0
aduprat/james,chibenwa/james,aduprat/james,rouazana/james,rouazana/james,aduprat/james,rouazana/james,aduprat/james,chibenwa/james,chibenwa/james,chibenwa/james,rouazana/james
/**************************************************************** * 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.james.smtpserver; import org.apache.avalon.cornerstone.services.sockets.SocketManager; import org.apache.avalon.cornerstone.services.store.Store; import org.apache.avalon.cornerstone.services.threads.ThreadManager; import org.apache.avalon.framework.container.ContainerUtil; import org.apache.commons.net.smtp.SMTPClient; import org.apache.commons.net.smtp.SMTPReply; import org.apache.james.Constants; import org.apache.james.core.MailImpl; import org.apache.james.services.DNSServer; import org.apache.james.services.JamesConnectionManager; import org.apache.james.services.MailServer; import org.apache.james.services.UsersRepository; import org.apache.james.test.mock.avalon.MockLogger; import org.apache.james.test.mock.avalon.MockServiceManager; import org.apache.james.test.mock.avalon.MockSocketManager; import org.apache.james.test.mock.avalon.MockStore; import org.apache.james.test.mock.avalon.MockThreadManager; import org.apache.james.test.mock.james.InMemorySpoolRepository; import org.apache.james.test.mock.james.MockMailServer; import org.apache.james.test.mock.mailet.MockMailContext; import org.apache.james.test.mock.mailet.MockMailetConfig; import org.apache.james.test.util.Util; import org.apache.james.transport.mailets.RemoteDelivery; import org.apache.james.userrepository.MockUsersRepository; import org.apache.james.util.Base64; import org.apache.james.util.connection.SimpleConnectionManager; import org.apache.mailet.Mail; import org.apache.mailet.MailAddress; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeMessage; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Writer; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Properties; import junit.framework.TestCase; /** * Tests the org.apache.james.smtpserver.SMTPServer unit */ public class SMTPServerTest extends TestCase { private final class AlterableDNSServer implements DNSServer { private InetAddress localhostByName = null; public Collection findMXRecords(String hostname) { List res = new ArrayList(); if (hostname == null) { return res; }; if ("james.apache.org".equals(hostname)) { res.add("nagoya.apache.org"); } return res; } public Iterator getSMTPHostAddresses(String domainName) { throw new UnsupportedOperationException("Unimplemented mock service"); } public InetAddress[] getAllByName(String host) throws UnknownHostException { return new InetAddress[] {getByName(host)}; } public InetAddress getByName(String host) throws UnknownHostException { if (getLocalhostByName() != null) { if ("127.0.0.1".equals(host)) return getLocalhostByName(); } if ("1.0.0.127.bl.spamcop.net.".equals(host)) { return InetAddress.getByName("localhost"); } if ("james.apache.org".equals(host)) { return InetAddress.getByName("james.apache.org"); } if ("abgsfe3rsf.de".equals(host)) { throw new UnknownHostException(); } if ("128.0.0.1".equals(host) || "192.168.0.1".equals(host) || "127.0.0.1".equals(host) || "127.0.0.0".equals(host) || "255.0.0.0".equals(host) || "255.255.255.255".equals(host)) { return InetAddress.getByName(host); } throw new UnsupportedOperationException("getByName not implemented in mock for host: "+host); //return InetAddress.getByName(host); } public Collection findTXTRecords(String hostname) { List res = new ArrayList(); if (hostname == null) { return res; }; if ("2.0.0.127.bl.spamcop.net.".equals(hostname)) { res.add("Blocked - see http://www.spamcop.net/bl.shtml?127.0.0.2"); } return res; } public InetAddress getLocalhostByName() { return localhostByName; } public void setLocalhostByName(InetAddress localhostByName) { this.localhostByName = localhostByName; } public String getHostName(InetAddress addr) { return addr.getHostName(); } } private int m_smtpListenerPort = Util.getNonPrivilegedPort(); private MockMailServer m_mailServer; private SMTPTestConfiguration m_testConfiguration; private SMTPServer m_smtpServer; private MockUsersRepository m_usersRepository = new MockUsersRepository(); public SMTPServerTest() { super("SMTPServerTest"); } public void verifyLastMail(String sender, String recipient, MimeMessage msg) throws IOException, MessagingException { Mail mailData = m_mailServer.getLastMail(); assertNotNull("mail received by mail server", mailData); if (sender == null && recipient == null && msg == null) fail("no verification can be done with all arguments null"); if (sender != null) assertEquals("sender verfication", sender, ((MailAddress)mailData.getSender()).toString()); if (recipient != null) assertTrue("recipient verfication", ((Collection) mailData.getRecipients()).contains(new MailAddress(recipient))); if (msg != null) { ByteArrayOutputStream bo1 = new ByteArrayOutputStream(); msg.writeTo(bo1); ByteArrayOutputStream bo2 = new ByteArrayOutputStream(); ((MimeMessage) mailData.getMessage()).writeTo(bo2); assertEquals(bo1.toString(),bo2.toString()); assertEquals("message verification", msg, ((MimeMessage) mailData.getMessage())); } } protected void setUp() throws Exception { m_smtpServer = new SMTPServer(); ContainerUtil.enableLogging(m_smtpServer,new MockLogger()); m_serviceManager = setUpServiceManager(); ContainerUtil.service(m_smtpServer, m_serviceManager); m_testConfiguration = new SMTPTestConfiguration(m_smtpListenerPort); } protected void tearDown() throws Exception { ContainerUtil.dispose(m_mailServer); super.tearDown(); } private void finishSetUp(SMTPTestConfiguration testConfiguration) throws Exception { testConfiguration.init(); ContainerUtil.configure(m_smtpServer, testConfiguration); ContainerUtil.initialize(m_smtpServer); m_mailServer.setMaxMessageSizeBytes(m_testConfiguration.getMaxMessageSize()*1024); } private MockServiceManager setUpServiceManager() throws Exception { m_serviceManager = new MockServiceManager(); SimpleConnectionManager connectionManager = new SimpleConnectionManager(); ContainerUtil.enableLogging(connectionManager, new MockLogger()); m_serviceManager.put(JamesConnectionManager.ROLE, connectionManager); m_serviceManager.put("org.apache.mailet.MailetContext", new MockMailContext()); m_mailServer = new MockMailServer(); m_serviceManager.put(MailServer.ROLE, m_mailServer); m_serviceManager.put(UsersRepository.ROLE, m_usersRepository); m_serviceManager.put(SocketManager.ROLE, new MockSocketManager(m_smtpListenerPort)); m_serviceManager.put(ThreadManager.ROLE, new MockThreadManager()); m_dnsServer = new AlterableDNSServer(); m_serviceManager.put(DNSServer.ROLE, m_dnsServer); m_serviceManager.put(Store.ROLE, new MockStore()); return m_serviceManager; } public void testSimpleMailSendWithEHLO() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol.sendCommand("EHLO "+InetAddress.getLocalHost()); String[] capabilityRes = smtpProtocol.getReplyStrings(); List capabilitieslist = new ArrayList(); for (int i = 1; i < capabilityRes.length; i++) { capabilitieslist.add(capabilityRes[i].substring(4)); } assertEquals("capabilities", 3, capabilitieslist.size()); assertTrue("capabilities present PIPELINING", capabilitieslist.contains("PIPELINING")); assertTrue("capabilities present ENHANCEDSTATUSCODES", capabilitieslist.contains("ENHANCEDSTATUSCODES")); assertTrue("capabilities present 8BITMIME", capabilitieslist.contains("8BITMIME")); smtpProtocol.setSender("mail@localhost"); smtpProtocol.addRecipient("mail@localhost"); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nBody\r\n\r\n.\r\n"); smtpProtocol.quit(); smtpProtocol.disconnect(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer.getLastMail()); } public void testEmptyMessage() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtp = new SMTPClient(); smtp.connect("127.0.0.1", m_smtpListenerPort); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtp.helo(InetAddress.getLocalHost().toString()); smtp.setSender("mail@localhost"); smtp.addRecipient("mail@localhost"); smtp.sendShortMessageData(""); smtp.quit(); smtp.disconnect(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer.getLastMail()); // added to check a NPE in the test (JAMES-474) due to MockMailServer // not cloning the message (added a MimeMessageCopyOnWriteProxy there) System.gc(); int size = ((MimeMessage) m_mailServer.getLastMail().getMessage()).getSize(); assertEquals(size, 2); } public void testSimpleMailSendWithHELO() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol.helo(InetAddress.getLocalHost().toString()); smtpProtocol.setSender("mail@localhost"); smtpProtocol.addRecipient("mail@localhost"); smtpProtocol.sendShortMessageData("Subject: test mail\r\n\r\nTest body testSimpleMailSendWithHELO\r\n.\r\n"); smtpProtocol.quit(); smtpProtocol.disconnect(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer.getLastMail()); } public void testTwoSimultaneousMails() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); SMTPClient smtpProtocol2 = new SMTPClient(); smtpProtocol2.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken",smtpProtocol1.isConnected()); assertTrue("second connection taken",smtpProtocol2.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); smtpProtocol2.helo(InetAddress.getLocalHost().toString()); String sender1 = "mail_sender1@localhost"; String recipient1 = "mail_recipient1@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(recipient1); String sender2 = "mail_sender2@localhost"; String recipient2 = "mail_recipient2@localhost"; smtpProtocol2.setSender(sender2); smtpProtocol2.addRecipient(recipient2); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoSimultaneousMails1\r\n.\r\n"); verifyLastMail(sender1, recipient1, null); smtpProtocol2.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoSimultaneousMails2\r\n.\r\n"); verifyLastMail(sender2, recipient2, null); smtpProtocol1.quit(); smtpProtocol2.quit(); smtpProtocol1.disconnect(); smtpProtocol2.disconnect(); } public void testTwoMailsInSequence() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "mail_sender1@localhost"; String recipient1 = "mail_recipient1@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(recipient1); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoMailsInSequence1\r\n"); verifyLastMail(sender1, recipient1, null); String sender2 = "mail_sender2@localhost"; String recipient2 = "mail_recipient2@localhost"; smtpProtocol1.setSender(sender2); smtpProtocol1.addRecipient(recipient2); smtpProtocol1.sendShortMessageData("Subject: test2\r\n\r\nTest body2 testTwoMailsInSequence2\r\n"); verifyLastMail(sender2, recipient2, null); smtpProtocol1.quit(); smtpProtocol1.disconnect(); } public void testHeloResolv() throws Exception { m_testConfiguration.setHeloResolv(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1"); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String helo1 = "abgsfe3rsf.de"; String helo2 = "james.apache.org"; String mail = "[email protected]"; String rcpt = "rcpt@localhost"; smtpProtocol1.sendCommand("helo",helo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the helo could not resolved assertEquals("expected error: helo could not resolved", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("helo", helo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // helo is resolvable. so this should give a 250 code assertEquals("Helo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testHeloResolvDefault() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol1.helo("abgsfe3rsf.de"); // helo should not be checked. so this should give a 250 code assertEquals("Helo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testReverseEqualsHelo() throws Exception { m_testConfiguration.setReverseEqualsHelo(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1"); // temporary alter the loopback resolution m_dnsServer.setLocalhostByName(InetAddress.getByName("james.apache.org")); try { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer .getLastMail()); String helo1 = "abgsfe3rsf.de"; String helo2 = "james.apache.org"; String mail = "sender"; String rcpt = "recipient"; smtpProtocol1.sendCommand("helo", helo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the helo not equal reverse of ip assertEquals("expected error: helo not equals reverse of ip", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("helo", helo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // helo is resolvable. so this should give a 250 code assertEquals("Helo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } finally { m_dnsServer.setLocalhostByName(null); } } public void testSenderDomainResolv() throws Exception { m_testConfiguration.setSenderDomainResolv(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1/32"); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; String sender2 = "[email protected]"; smtpProtocol1.setSender(sender1); assertEquals("expected 501 error", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.setSender(sender2); smtpProtocol1.quit(); } public void testSenderDomainResolvDefault() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; smtpProtocol1.setSender(sender1); smtpProtocol1.quit(); } public void testSenderDomainResolvRelayClientDefault() throws Exception { m_testConfiguration.setSenderDomainResolv(); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; // Both mail shold smtpProtocol1.setSender(sender1); smtpProtocol1.quit(); } public void testSenderDomainResolvRelayClient() throws Exception { m_testConfiguration.setSenderDomainResolv(); m_testConfiguration.setCheckAuthClients(true); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; String sender2 = "[email protected]"; smtpProtocol1.setSender(sender1); assertEquals("expected 501 error", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.setSender(sender2); smtpProtocol1.quit(); } public void testMaxRcpt() throws Exception { m_testConfiguration.setMaxRcpt(1); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; String rcpt1 = "test@localhost"; String rcpt2 = "test2@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(rcpt1); smtpProtocol1.addRecipient(rcpt2); assertEquals("expected 452 error", 452, smtpProtocol1.getReplyCode()); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testMaxRcpt1\r\n"); // After the data is send the rcpt count is set back to 0.. So a new mail with rcpt should be accepted smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(rcpt1); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testMaxRcpt2\r\n"); smtpProtocol1.quit(); } public void testMaxRcptDefault() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; String rcpt1 = "test@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(rcpt1); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testMaxRcptDefault\r\n"); smtpProtocol1.quit(); } public void testEhloResolv() throws Exception { m_testConfiguration.setEhloResolv(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1"); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String ehlo1 = "abgsfe3rsf.de"; String ehlo2 = "james.apache.org"; String mail = "test@account"; String rcpt = "test"; smtpProtocol1.sendCommand("ehlo", ehlo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the ehlo could not resolved assertEquals("expected error: ehlo could not resolved", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("ehlo", ehlo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // ehlo is resolvable. so this should give a 250 code assertEquals("ehlo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testEhloResolvDefault() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol1.sendCommand("ehlo","abgsfe3rsf.de"); // ehlo should not be checked. so this should give a 250 code assertEquals("ehlo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testEhloResolvIgnoreClientDisabled() throws Exception { m_testConfiguration.setEhloResolv(); m_testConfiguration.setCheckAuthNetworks(true); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String ehlo1 = "abgsfe3rsf.de"; String ehlo2 = "james.apache.org"; String mail = "sender@localhost"; String rcpt = "test"; smtpProtocol1.sendCommand("ehlo", ehlo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the ehlo could not resolved assertEquals("expected error: ehlo could not resolved", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("ehlo", ehlo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // ehlo is resolvable. so this should give a 250 code assertEquals("ehlo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testReverseEqualsEhlo() throws Exception { m_testConfiguration.setReverseEqualsEhlo(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1"); // temporary alter the loopback resolution m_dnsServer.setLocalhostByName(m_dnsServer.getByName("james.apache.org")); try { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer .getLastMail()); String ehlo1 = "abgsfe3rsf.de"; String ehlo2 = "james.apache.org"; String mail = "sender"; String rcpt = "recipient"; smtpProtocol1.sendCommand("ehlo", ehlo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the ehlo not equals reverse of ip assertEquals("expected error: ehlo not equals reverse of ip", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("ehlo", ehlo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // ehlo is resolvable. so this should give a 250 code assertEquals("ehlo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } finally { m_dnsServer.setLocalhostByName(null); } } public void testHeloEnforcement() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String sender1 = "mail_sender1@localhost"; smtpProtocol1.setSender(sender1); assertEquals("expected 503 error", 503, smtpProtocol1.getReplyCode()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); smtpProtocol1.setSender(sender1); smtpProtocol1.quit(); } public void testHeloEnforcementDisabled() throws Exception { m_testConfiguration.setHeloEhloEnforcement(false); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String sender1 = "mail_sender1@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.quit(); } public void testAuth() throws Exception { m_testConfiguration.setAuthorizedAddresses("128.0.0.1/8"); m_testConfiguration.setAuthorizingAnnounce(); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); String[] capabilityRes = smtpProtocol.getReplyStrings(); List capabilitieslist = new ArrayList(); for (int i = 1; i < capabilityRes.length; i++) { capabilitieslist.add(capabilityRes[i].substring(4)); } assertTrue("anouncing auth required", capabilitieslist.contains("AUTH LOGIN PLAIN")); // is this required or just for compatibility? assertTrue("anouncing auth required", capabilitieslist.contains("AUTH=LOGIN PLAIN")); String userName = "test_user_smtp"; String noexistUserName = "noexist_test_user_smtp"; String sender ="test_user_smtp@localhost"; smtpProtocol.sendCommand("AUTH FOO", null); assertEquals("expected error: unrecognized authentication type", 504, smtpProtocol.getReplyCode()); smtpProtocol.setSender(sender); smtpProtocol.addRecipient("[email protected]"); assertEquals("expected 530 error", 530, smtpProtocol.getReplyCode()); assertFalse("user not existing", m_usersRepository.contains(noexistUserName)); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0"+noexistUserName+"\0pwd\0")); // smtpProtocol.sendCommand(noexistUserName+"pwd".toCharArray()); assertEquals("expected error", 535, smtpProtocol.getReplyCode()); m_usersRepository.addUser(userName, "pwd"); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0"+userName+"\0wrongpwd\0")); assertEquals("expected error", 535, smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0"+userName+"\0pwd\0")); assertEquals("authenticated", 235, smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("AUTH PLAIN"); assertEquals("expected error: User has previously authenticated.", 503, smtpProtocol.getReplyCode()); smtpProtocol.addRecipient("[email protected]"); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nTest body testAuth\r\n"); smtpProtocol.quit(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer.getLastMail()); } public void testAuthWithEmptySender() throws Exception { m_testConfiguration.setAuthorizedAddresses("128.0.0.1/8"); m_testConfiguration.setAuthorizingAnnounce(); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); String userName = "test_user_smtp"; m_usersRepository.addUser(userName, "pwd"); smtpProtocol.setSender(""); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0"+userName+"\0pwd\0")); assertEquals("authenticated", 235, smtpProtocol.getReplyCode()); smtpProtocol.addRecipient("[email protected]"); assertEquals("expected error", 503, smtpProtocol.getReplyCode()); smtpProtocol.quit(); } public void testNoRecepientSpecified() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("[email protected]"); // left out for test smtpProtocol.rcpt(new Address("mail@localhost")); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nTest body testNoRecepientSpecified\r\n"); assertTrue("sending succeeded without recepient", SMTPReply.isNegativePermanent(smtpProtocol.getReplyCode())); smtpProtocol.quit(); // mail was propagated by SMTPServer assertNull("no mail received by mail server", m_mailServer.getLastMail()); } public void testMultipleMailsAndRset() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("[email protected]"); smtpProtocol.reset(); smtpProtocol.setSender("[email protected]"); smtpProtocol.quit(); // mail was propagated by SMTPServer assertNull("no mail received by mail server", m_mailServer.getLastMail()); } public void testRelayingDenied() throws Exception { m_testConfiguration.setAuthorizedAddresses("128.0.0.1/8"); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("[email protected]"); smtpProtocol.addRecipient("[email protected]"); assertEquals("expected 550 error", 550, smtpProtocol.getReplyCode()); } public void testHandleAnnouncedMessageSizeLimitExceeded() throws Exception { m_testConfiguration.setMaxMessageSize(1); // set message limit to 1kb finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.sendCommand("MAIL FROM:<mail@localhost> SIZE=1025", null); assertEquals("expected error: max msg size exceeded", 552, smtpProtocol.getReplyCode()); smtpProtocol.addRecipient("mail@localhost"); assertEquals("expected error", 503, smtpProtocol.getReplyCode()); } public void testHandleMessageSizeLimitExceeded() throws Exception { m_testConfiguration.setMaxMessageSize(1); // set message limit to 1kb finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("mail@localhost"); smtpProtocol.addRecipient("mail@localhost"); Writer wr = smtpProtocol.sendMessageData(); // create Body with more than 1kb . 502 wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100\r\n"); // second line wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("123456781012345678201\r\n"); // 521 + CRLF = 523 + 502 => 1025 wr.close(); assertFalse(smtpProtocol.completePendingCommand()); assertEquals("expected 552 error", 552, smtpProtocol.getReplyCode()); } public void testHandleMessageSizeLimitRespected() throws Exception { m_testConfiguration.setMaxMessageSize(1); // set message limit to 1kb finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("mail@localhost"); smtpProtocol.addRecipient("mail@localhost"); Writer wr = smtpProtocol.sendMessageData(); // create Body with less than 1kb wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012\r\n"); // 1022 + CRLF = 1024 wr.close(); assertTrue(smtpProtocol.completePendingCommand()); assertEquals("expected 250 ok", 250, smtpProtocol.getReplyCode()); } public void testConnectionLimitExceeded() throws Exception { m_testConfiguration.setConnectionLimit(1); // allow no more than one connection at a time finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); SMTPClient smtpProtocol2 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); try { smtpProtocol2.connect("127.0.0.1", m_smtpListenerPort); fail("second connection not taken1"); } catch (Exception e) { } // disconnect the first smtpProtocol1.quit(); smtpProtocol1.disconnect(); Thread.sleep(100); // now the second should be able to connect smtpProtocol2.connect("127.0.0.1", m_smtpListenerPort); assertTrue(smtpProtocol2.isConnected()); } // RemoteDelivery tests. InMemorySpoolRepository outgoingSpool; private MockServiceManager m_serviceManager; private AlterableDNSServer m_dnsServer; private Properties getStandardParameters() { Properties parameters = new Properties(); parameters.put("delayTime", "500 msec, 500 msec, 500 msec"); // msec, sec, minute, hour parameters.put("maxRetries", "3"); parameters.put("deliveryThreads", "1"); parameters.put("debug", "true"); parameters.put("sendpartial", "false"); parameters.put("bounceProcessor", "bounce"); parameters.put("outgoing", "mocked://outgoing/"); return parameters; } /** * This has been created to test javamail 1.4 introduced bug. * http://issues.apache.org/jira/browse/JAMES-490 */ public void testDeliveryToSelfWithGatewayAndBind() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("bind", "127.0.0.1"); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); String sources = "Content-Type: text/plain;\r\nSubject: test\r\n\r\nBody"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } verifyLastMail(sender, recipient, null); assertEquals(((String) mm.getContent()).trim(),((String) ((MimeMessage) m_mailServer.getLastMail().getMessage()).getContent()).trim()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeFromStream() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); //String sources = "Content-Type: text/plain;\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeFromStreamWith8bitContent() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); //String sources = "Content-Type: text/plain;\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeFromStreamWithoutContentTransferEncoding() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); String sources = "Content-Type: text/plain;\r\nSubject: test\r\n\r\nBody\u03B2\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeFromStreamWithoutContentTransferEncodingSentAs8bit() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); String sources = "Content-Type: text/plain;\r\nSubject: test\r\n\r\nBody=32=48\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeWith8bitmimeDisabledInServer() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); mci.setProperty("mail.smtp.allow8bitmime", "false"); rd.init(mci); //String sources = "Content-Type: text/plain;\r\nSubject: test\r\n\r\nBody=32=48\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } // Check if auth users get not rejected cause rbl. See JAMES-566 public void testDNSRBLNotRejectAuthUser() throws Exception { m_testConfiguration.setAuthorizedAddresses("192.168.0.1/32"); m_testConfiguration.setAuthorizingAnnounce(); m_testConfiguration.useRBL(true); finishSetUp(m_testConfiguration); m_dnsServer.setLocalhostByName(InetAddress.getByName("127.0.0.1")); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); String[] capabilityRes = smtpProtocol.getReplyStrings(); List capabilitieslist = new ArrayList(); for (int i = 1; i < capabilityRes.length; i++) { capabilitieslist.add(capabilityRes[i].substring(4)); } assertTrue("anouncing auth required", capabilitieslist .contains("AUTH LOGIN PLAIN")); // is this required or just for compatibility? assertTrue("anouncing // auth required", capabilitieslist.contains("AUTH=LOGIN PLAIN")); String userName = "test_user_smtp"; String sender = "test_user_smtp@localhost"; smtpProtocol.setSender(sender); m_usersRepository.addUser(userName, "pwd"); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0" + userName + "\0pwd\0")); assertEquals("authenticated", 235, smtpProtocol.getReplyCode()); smtpProtocol.addRecipient("[email protected]"); assertEquals("authenticated.. not reject", 250, smtpProtocol .getReplyCode()); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nTest body testDNSRBLNotRejectAuthUser\r\n"); smtpProtocol.quit(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer .getLastMail()); } public void testDNSRBLRejectWorks() throws Exception { m_testConfiguration.setAuthorizedAddresses("192.168.0.1/32"); m_testConfiguration.useRBL(true); finishSetUp(m_testConfiguration); m_dnsServer.setLocalhostByName(InetAddress.getByName("127.0.0.1")); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); String sender = "test_user_smtp@localhost"; smtpProtocol.setSender(sender); smtpProtocol.addRecipient("[email protected]"); assertEquals("reject", 550, smtpProtocol .getReplyCode()); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nTest body testDNSRBLRejectWorks\r\n"); smtpProtocol.quit(); // mail was rejected by SMTPServer assertNull("mail reject by mail server", m_mailServer .getLastMail()); } public void testAddressBracketsEnforcementDisabled() throws Exception { m_testConfiguration.setAddressBracketsEnforcement(false); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); smtpProtocol.sendCommand("mail from:", "test@localhost"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("rcpt to:", "[email protected]"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.quit(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); smtpProtocol.sendCommand("mail from:", "<test@localhost>"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("rcpt to:", "<[email protected]>"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.quit(); } public void testAddressBracketsEnforcementEnabled() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); smtpProtocol.sendCommand("mail from:", "test@localhost"); assertEquals("reject", 501,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("mail from:", "<test@localhost>"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("rcpt to:", "[email protected]"); assertEquals("reject", 501,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("rcpt to:", "<[email protected]>"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.quit(); } // See http://www.ietf.org/rfc/rfc2920.txt 4: Examples public void testPipelining() throws Exception { StringBuffer buf = new StringBuffer(); finishSetUp(m_testConfiguration); Socket client = new Socket("127.0.0.1",m_smtpListenerPort); buf.append("HELO TEST"); buf.append("\r\n"); buf.append("MAIL FROM: <test@localhost>"); buf.append("\r\n"); buf.append("RCPT TO: <test2@localhost>"); buf.append("\r\n"); buf.append("DATA"); buf.append("\r\n"); buf.append("Subject: test"); buf.append("\r\n");; buf.append("\r\n"); buf.append("content"); buf.append("\r\n"); buf.append("."); buf.append("\r\n"); buf.append("quit"); buf.append("\r\n"); OutputStream out = client.getOutputStream(); out.write(buf.toString().getBytes()); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); assertEquals("Connection made" , 220, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("HELO accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("MAIL FROM accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("RCPT TO accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("DATA accepted" , 354, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("Message accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); in.close(); out.close(); client.close(); } // See http://www.ietf.org/rfc/rfc2920.txt 4: Examples public void testRejectAllRCPTPipelining() throws Exception { StringBuffer buf = new StringBuffer(); m_testConfiguration.setAuthorizedAddresses(""); finishSetUp(m_testConfiguration); Socket client = new Socket("127.0.0.1",m_smtpListenerPort); buf.append("HELO TEST"); buf.append("\r\n"); buf.append("MAIL FROM: <test@localhost>"); buf.append("\r\n"); buf.append("RCPT TO: <test@invalid>"); buf.append("\r\n"); buf.append("RCPT TO: <test2@invalid>"); buf.append("\r\n"); buf.append("DATA"); buf.append("\r\n"); buf.append("Subject: test"); buf.append("\r\n");; buf.append("\r\n"); buf.append("content"); buf.append("\r\n"); buf.append("."); buf.append("\r\n"); buf.append("quit"); buf.append("\r\n"); OutputStream out = client.getOutputStream(); out.write(buf.toString().getBytes()); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); assertEquals("Connection made" , 220, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("HELO accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("MAIL FROM accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("RCPT TO rejected" , 550, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("RCPT TO rejected" , 550, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("DATA not accepted" , 503, Integer.parseInt(in.readLine().split(" ")[0])); in.close(); out.close(); client.close(); } public void testRejectOneRCPTPipelining() throws Exception { StringBuffer buf = new StringBuffer(); m_testConfiguration.setAuthorizedAddresses(""); finishSetUp(m_testConfiguration); Socket client = new Socket("127.0.0.1",m_smtpListenerPort); buf.append("HELO TEST"); buf.append("\r\n"); buf.append("MAIL FROM: <test@localhost>"); buf.append("\r\n"); buf.append("RCPT TO: <test@invalid>"); buf.append("\r\n"); buf.append("RCPT TO: <test2@localhost>"); buf.append("\r\n"); buf.append("DATA"); buf.append("\r\n"); buf.append("Subject: test"); buf.append("\r\n");; buf.append("\r\n"); buf.append("content"); buf.append("\r\n"); buf.append("."); buf.append("\r\n"); buf.append("quit"); buf.append("\r\n"); OutputStream out = client.getOutputStream(); out.write(buf.toString().getBytes()); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); assertEquals("Connection made" , 220, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("HELO accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("MAIL FROM accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("RCPT TO rejected" , 550, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("RCPT accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("DATA accepted" , 354, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("Message accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); in.close(); out.close(); client.close(); } }
trunk/src/test/org/apache/james/smtpserver/SMTPServerTest.java
/**************************************************************** * 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.james.smtpserver; import org.apache.avalon.cornerstone.services.sockets.SocketManager; import org.apache.avalon.cornerstone.services.store.Store; import org.apache.avalon.cornerstone.services.threads.ThreadManager; import org.apache.avalon.framework.container.ContainerUtil; import org.apache.commons.net.smtp.SMTPClient; import org.apache.commons.net.smtp.SMTPReply; import org.apache.james.Constants; import org.apache.james.core.MailImpl; import org.apache.james.services.DNSServer; import org.apache.james.services.JamesConnectionManager; import org.apache.james.services.MailServer; import org.apache.james.services.UsersRepository; import org.apache.james.test.mock.avalon.MockLogger; import org.apache.james.test.mock.avalon.MockServiceManager; import org.apache.james.test.mock.avalon.MockSocketManager; import org.apache.james.test.mock.avalon.MockStore; import org.apache.james.test.mock.avalon.MockThreadManager; import org.apache.james.test.mock.james.InMemorySpoolRepository; import org.apache.james.test.mock.james.MockMailServer; import org.apache.james.test.mock.mailet.MockMailContext; import org.apache.james.test.mock.mailet.MockMailetConfig; import org.apache.james.test.util.Util; import org.apache.james.transport.mailets.RemoteDelivery; import org.apache.james.userrepository.MockUsersRepository; import org.apache.james.util.Base64; import org.apache.james.util.connection.SimpleConnectionManager; import org.apache.mailet.Mail; import org.apache.mailet.MailAddress; import javax.mail.MessagingException; import javax.mail.Session; import javax.mail.internet.MimeMessage; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.Writer; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Properties; import junit.framework.TestCase; /** * Tests the org.apache.james.smtpserver.SMTPServer unit */ public class SMTPServerTest extends TestCase { private final class AlterableDNSServer implements DNSServer { private InetAddress localhostByName = null; public Collection findMXRecords(String hostname) { List res = new ArrayList(); if (hostname == null) { return res; }; if ("james.apache.org".equals(hostname)) { res.add("nagoya.apache.org"); } return res; } public Iterator getSMTPHostAddresses(String domainName) { throw new UnsupportedOperationException("Unimplemented mock service"); } public InetAddress[] getAllByName(String host) throws UnknownHostException { return new InetAddress[] {getByName(host)}; } public InetAddress getByName(String host) throws UnknownHostException { if (getLocalhostByName() != null) { if ("127.0.0.1".equals(host)) return getLocalhostByName(); } if ("1.0.0.127.bl.spamcop.net.".equals(host)) { return InetAddress.getByName("localhost"); } if ("james.apache.org".equals(host)) { return InetAddress.getByName("james.apache.org"); } if ("abgsfe3rsf.de".equals(host)) { throw new UnknownHostException(); } if ("128.0.0.1".equals(host) || "192.168.0.1".equals(host) || "127.0.0.1".equals(host) || "127.0.0.0".equals(host) || "255.0.0.0".equals(host) || "255.255.255.255".equals(host)) { return InetAddress.getByName(host); } throw new UnsupportedOperationException("getByName not implemented in mock for host: "+host); //return InetAddress.getByName(host); } public Collection findTXTRecords(String hostname) { List res = new ArrayList(); if (hostname == null) { return res; }; if ("2.0.0.127.bl.spamcop.net.".equals(hostname)) { res.add("Blocked - see http://www.spamcop.net/bl.shtml?127.0.0.2"); } return res; } public InetAddress getLocalhostByName() { return localhostByName; } public void setLocalhostByName(InetAddress localhostByName) { this.localhostByName = localhostByName; } public String getHostName(InetAddress addr) { return addr.getHostName(); } } private int m_smtpListenerPort = Util.getNonPrivilegedPort(); private MockMailServer m_mailServer; private SMTPTestConfiguration m_testConfiguration; private SMTPServer m_smtpServer; private MockUsersRepository m_usersRepository = new MockUsersRepository(); public SMTPServerTest() { super("SMTPServerTest"); } public void verifyLastMail(String sender, String recipient, MimeMessage msg) throws IOException, MessagingException { Mail mailData = m_mailServer.getLastMail(); assertNotNull("mail received by mail server", mailData); if (sender == null && recipient == null && msg == null) fail("no verification can be done with all arguments null"); if (sender != null) assertEquals("sender verfication", sender, ((MailAddress)mailData.getSender()).toString()); if (recipient != null) assertTrue("recipient verfication", ((Collection) mailData.getRecipients()).contains(new MailAddress(recipient))); if (msg != null) { ByteArrayOutputStream bo1 = new ByteArrayOutputStream(); msg.writeTo(bo1); ByteArrayOutputStream bo2 = new ByteArrayOutputStream(); ((MimeMessage) mailData.getMessage()).writeTo(bo2); assertEquals(bo1.toString(),bo2.toString()); assertEquals("message verification", msg, ((MimeMessage) mailData.getMessage())); } } protected void setUp() throws Exception { m_smtpServer = new SMTPServer(); ContainerUtil.enableLogging(m_smtpServer,new MockLogger()); m_serviceManager = setUpServiceManager(); ContainerUtil.service(m_smtpServer, m_serviceManager); m_testConfiguration = new SMTPTestConfiguration(m_smtpListenerPort); } protected void tearDown() throws Exception { ContainerUtil.dispose(m_mailServer); super.tearDown(); } private void finishSetUp(SMTPTestConfiguration testConfiguration) throws Exception { testConfiguration.init(); ContainerUtil.configure(m_smtpServer, testConfiguration); ContainerUtil.initialize(m_smtpServer); m_mailServer.setMaxMessageSizeBytes(m_testConfiguration.getMaxMessageSize()*1024); } private MockServiceManager setUpServiceManager() throws Exception { m_serviceManager = new MockServiceManager(); SimpleConnectionManager connectionManager = new SimpleConnectionManager(); ContainerUtil.enableLogging(connectionManager, new MockLogger()); m_serviceManager.put(JamesConnectionManager.ROLE, connectionManager); m_serviceManager.put("org.apache.mailet.MailetContext", new MockMailContext()); m_mailServer = new MockMailServer(); m_serviceManager.put(MailServer.ROLE, m_mailServer); m_serviceManager.put(UsersRepository.ROLE, m_usersRepository); m_serviceManager.put(SocketManager.ROLE, new MockSocketManager(m_smtpListenerPort)); m_serviceManager.put(ThreadManager.ROLE, new MockThreadManager()); m_dnsServer = new AlterableDNSServer(); m_serviceManager.put(DNSServer.ROLE, m_dnsServer); m_serviceManager.put(Store.ROLE, new MockStore()); return m_serviceManager; } public void testSimpleMailSendWithEHLO() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol.sendCommand("EHLO "+InetAddress.getLocalHost()); String[] capabilityRes = smtpProtocol.getReplyStrings(); List capabilitieslist = new ArrayList(); for (int i = 1; i < capabilityRes.length; i++) { capabilitieslist.add(capabilityRes[i].substring(4)); } assertEquals("capabilities", 3, capabilitieslist.size()); assertTrue("capabilities present PIPELINING", capabilitieslist.contains("PIPELINING")); assertTrue("capabilities present ENHANCEDSTATUSCODES", capabilitieslist.contains("ENHANCEDSTATUSCODES")); assertTrue("capabilities present 8BITMIME", capabilitieslist.contains("8BITMIME")); smtpProtocol.setSender("mail@localhost"); smtpProtocol.addRecipient("mail@localhost"); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nBody\r\n\r\n.\r\n"); smtpProtocol.quit(); smtpProtocol.disconnect(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer.getLastMail()); } public void testEmptyMessage() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtp = new SMTPClient(); smtp.connect("127.0.0.1", m_smtpListenerPort); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtp.helo(InetAddress.getLocalHost().toString()); smtp.setSender("mail@localhost"); smtp.addRecipient("mail@localhost"); smtp.sendShortMessageData(""); smtp.quit(); smtp.disconnect(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer.getLastMail()); // added to check a NPE in the test (JAMES-474) due to MockMailServer // not cloning the message (added a MimeMessageCopyOnWriteProxy there) System.gc(); int size = ((MimeMessage) m_mailServer.getLastMail().getMessage()).getSize(); assertEquals(size, 2); } public void testSimpleMailSendWithHELO() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol.helo(InetAddress.getLocalHost().toString()); smtpProtocol.setSender("mail@localhost"); smtpProtocol.addRecipient("mail@localhost"); smtpProtocol.sendShortMessageData("Subject: test mail\r\n\r\nTest body testSimpleMailSendWithHELO\r\n.\r\n"); smtpProtocol.quit(); smtpProtocol.disconnect(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer.getLastMail()); } public void testTwoSimultaneousMails() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); SMTPClient smtpProtocol2 = new SMTPClient(); smtpProtocol2.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken",smtpProtocol1.isConnected()); assertTrue("second connection taken",smtpProtocol2.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); smtpProtocol2.helo(InetAddress.getLocalHost().toString()); String sender1 = "mail_sender1@localhost"; String recipient1 = "mail_recipient1@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(recipient1); String sender2 = "mail_sender2@localhost"; String recipient2 = "mail_recipient2@localhost"; smtpProtocol2.setSender(sender2); smtpProtocol2.addRecipient(recipient2); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoSimultaneousMails1\r\n.\r\n"); verifyLastMail(sender1, recipient1, null); smtpProtocol2.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoSimultaneousMails2\r\n.\r\n"); verifyLastMail(sender2, recipient2, null); smtpProtocol1.quit(); smtpProtocol2.quit(); smtpProtocol1.disconnect(); smtpProtocol2.disconnect(); } public void testTwoMailsInSequence() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "mail_sender1@localhost"; String recipient1 = "mail_recipient1@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(recipient1); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testTwoMailsInSequence1\r\n"); verifyLastMail(sender1, recipient1, null); String sender2 = "mail_sender2@localhost"; String recipient2 = "mail_recipient2@localhost"; smtpProtocol1.setSender(sender2); smtpProtocol1.addRecipient(recipient2); smtpProtocol1.sendShortMessageData("Subject: test2\r\n\r\nTest body2 testTwoMailsInSequence2\r\n"); verifyLastMail(sender2, recipient2, null); smtpProtocol1.quit(); smtpProtocol1.disconnect(); } public void testHeloResolv() throws Exception { m_testConfiguration.setHeloResolv(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1"); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String helo1 = "abgsfe3rsf.de"; String helo2 = "james.apache.org"; String mail = "[email protected]"; String rcpt = "rcpt@localhost"; smtpProtocol1.sendCommand("helo",helo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the helo could not resolved assertEquals("expected error: helo could not resolved", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("helo", helo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // helo is resolvable. so this should give a 250 code assertEquals("Helo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testHeloResolvDefault() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol1.helo("abgsfe3rsf.de"); // helo should not be checked. so this should give a 250 code assertEquals("Helo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testReverseEqualsHelo() throws Exception { m_testConfiguration.setReverseEqualsHelo(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1"); // temporary alter the loopback resolution m_dnsServer.setLocalhostByName(InetAddress.getByName("james.apache.org")); try { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer .getLastMail()); String helo1 = "abgsfe3rsf.de"; String helo2 = "james.apache.org"; String mail = "sender"; String rcpt = "recipient"; smtpProtocol1.sendCommand("helo", helo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the helo not equal reverse of ip assertEquals("expected error: helo not equals reverse of ip", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("helo", helo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // helo is resolvable. so this should give a 250 code assertEquals("Helo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } finally { m_dnsServer.setLocalhostByName(null); } } public void testSenderDomainResolv() throws Exception { m_testConfiguration.setSenderDomainResolv(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1/32"); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; String sender2 = "[email protected]"; smtpProtocol1.setSender(sender1); assertEquals("expected 501 error", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.setSender(sender2); smtpProtocol1.quit(); } public void testSenderDomainResolvDefault() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; smtpProtocol1.setSender(sender1); smtpProtocol1.quit(); } public void testSenderDomainResolvRelayClientDefault() throws Exception { m_testConfiguration.setSenderDomainResolv(); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; // Both mail shold smtpProtocol1.setSender(sender1); smtpProtocol1.quit(); } public void testSenderDomainResolvRelayClient() throws Exception { m_testConfiguration.setSenderDomainResolv(); m_testConfiguration.setCheckAuthClients(true); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; String sender2 = "[email protected]"; smtpProtocol1.setSender(sender1); assertEquals("expected 501 error", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.setSender(sender2); smtpProtocol1.quit(); } public void testMaxRcpt() throws Exception { m_testConfiguration.setMaxRcpt(1); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; String rcpt1 = "test@localhost"; String rcpt2 = "test2@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(rcpt1); smtpProtocol1.addRecipient(rcpt2); assertEquals("expected 452 error", 452, smtpProtocol1.getReplyCode()); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testMaxRcpt1\r\n"); // After the data is send the rcpt count is set back to 0.. So a new mail with rcpt should be accepted smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(rcpt1); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testMaxRcpt2\r\n"); smtpProtocol1.quit(); } public void testMaxRcptDefault() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); String sender1 = "[email protected]"; String rcpt1 = "test@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.addRecipient(rcpt1); smtpProtocol1.sendShortMessageData("Subject: test\r\n\r\nTest body testMaxRcptDefault\r\n"); smtpProtocol1.quit(); } public void testEhloResolv() throws Exception { m_testConfiguration.setEhloResolv(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1"); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String ehlo1 = "abgsfe3rsf.de"; String ehlo2 = "james.apache.org"; String mail = "test@account"; String rcpt = "test"; smtpProtocol1.sendCommand("ehlo", ehlo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the ehlo could not resolved assertEquals("expected error: ehlo could not resolved", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("ehlo", ehlo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // ehlo is resolvable. so this should give a 250 code assertEquals("ehlo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testEhloResolvDefault() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol1.sendCommand("ehlo","abgsfe3rsf.de"); // ehlo should not be checked. so this should give a 250 code assertEquals("ehlo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testEhloResolvIgnoreClientDisabled() throws Exception { m_testConfiguration.setEhloResolv(); m_testConfiguration.setCheckAuthNetworks(true); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String ehlo1 = "abgsfe3rsf.de"; String ehlo2 = "james.apache.org"; String mail = "sender@localhost"; String rcpt = "test"; smtpProtocol1.sendCommand("ehlo", ehlo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the ehlo could not resolved assertEquals("expected error: ehlo could not resolved", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("ehlo", ehlo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // ehlo is resolvable. so this should give a 250 code assertEquals("ehlo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } public void testReverseEqualsEhlo() throws Exception { m_testConfiguration.setReverseEqualsEhlo(); m_testConfiguration.setAuthorizedAddresses("192.168.0.1"); // temporary alter the loopback resolution m_dnsServer.setLocalhostByName(m_dnsServer.getByName("james.apache.org")); try { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer .getLastMail()); String ehlo1 = "abgsfe3rsf.de"; String ehlo2 = "james.apache.org"; String mail = "sender"; String rcpt = "recipient"; smtpProtocol1.sendCommand("ehlo", ehlo1); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // this should give a 501 code cause the ehlo not equals reverse of ip assertEquals("expected error: ehlo not equals reverse of ip", 501, smtpProtocol1.getReplyCode()); smtpProtocol1.sendCommand("ehlo", ehlo2); smtpProtocol1.setSender(mail); smtpProtocol1.addRecipient(rcpt); // ehlo is resolvable. so this should give a 250 code assertEquals("ehlo accepted", 250, smtpProtocol1.getReplyCode()); smtpProtocol1.quit(); } finally { m_dnsServer.setLocalhostByName(null); } } public void testHeloEnforcement() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String sender1 = "mail_sender1@localhost"; smtpProtocol1.setSender(sender1); assertEquals("expected 503 error", 503, smtpProtocol1.getReplyCode()); smtpProtocol1.helo(InetAddress.getLocalHost().toString()); smtpProtocol1.setSender(sender1); smtpProtocol1.quit(); } public void testHeloEnforcementDisabled() throws Exception { m_testConfiguration.setHeloEhloEnforcement(false); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); // no message there, yet assertNull("no mail received by mail server", m_mailServer.getLastMail()); String sender1 = "mail_sender1@localhost"; smtpProtocol1.setSender(sender1); smtpProtocol1.quit(); } public void testAuth() throws Exception { m_testConfiguration.setAuthorizedAddresses("128.0.0.1/8"); m_testConfiguration.setAuthorizingAnnounce(); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); String[] capabilityRes = smtpProtocol.getReplyStrings(); List capabilitieslist = new ArrayList(); for (int i = 1; i < capabilityRes.length; i++) { capabilitieslist.add(capabilityRes[i].substring(4)); } assertTrue("anouncing auth required", capabilitieslist.contains("AUTH LOGIN PLAIN")); // is this required or just for compatibility? assertTrue("anouncing auth required", capabilitieslist.contains("AUTH=LOGIN PLAIN")); String userName = "test_user_smtp"; String noexistUserName = "noexist_test_user_smtp"; String sender ="test_user_smtp@localhost"; smtpProtocol.sendCommand("AUTH FOO", null); assertEquals("expected error: unrecognized authentication type", 504, smtpProtocol.getReplyCode()); smtpProtocol.setSender(sender); smtpProtocol.addRecipient("[email protected]"); assertEquals("expected 530 error", 530, smtpProtocol.getReplyCode()); assertFalse("user not existing", m_usersRepository.contains(noexistUserName)); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0"+noexistUserName+"\0pwd\0")); // smtpProtocol.sendCommand(noexistUserName+"pwd".toCharArray()); assertEquals("expected error", 535, smtpProtocol.getReplyCode()); m_usersRepository.addUser(userName, "pwd"); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0"+userName+"\0wrongpwd\0")); assertEquals("expected error", 535, smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0"+userName+"\0pwd\0")); assertEquals("authenticated", 235, smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("AUTH PLAIN"); assertEquals("expected error: User has previously authenticated.", 503, smtpProtocol.getReplyCode()); smtpProtocol.addRecipient("[email protected]"); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nTest body testAuth\r\n"); smtpProtocol.quit(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer.getLastMail()); } public void testAuthWithEmptySender() throws Exception { m_testConfiguration.setAuthorizedAddresses("128.0.0.1/8"); m_testConfiguration.setAuthorizingAnnounce(); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); String userName = "test_user_smtp"; m_usersRepository.addUser(userName, "pwd"); smtpProtocol.setSender(""); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0"+userName+"\0pwd\0")); assertEquals("authenticated", 235, smtpProtocol.getReplyCode()); smtpProtocol.addRecipient("[email protected]"); assertEquals("expected error", 503, smtpProtocol.getReplyCode()); smtpProtocol.quit(); } public void testNoRecepientSpecified() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("[email protected]"); // left out for test smtpProtocol.rcpt(new Address("mail@localhost")); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nTest body testNoRecepientSpecified\r\n"); assertTrue("sending succeeded without recepient", SMTPReply.isNegativePermanent(smtpProtocol.getReplyCode())); smtpProtocol.quit(); // mail was propagated by SMTPServer assertNull("no mail received by mail server", m_mailServer.getLastMail()); } public void testMultipleMailsAndRset() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("[email protected]"); smtpProtocol.reset(); smtpProtocol.setSender("[email protected]"); smtpProtocol.quit(); // mail was propagated by SMTPServer assertNull("no mail received by mail server", m_mailServer.getLastMail()); } public void testRelayingDenied() throws Exception { m_testConfiguration.setAuthorizedAddresses("128.0.0.1/8"); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("[email protected]"); smtpProtocol.addRecipient("[email protected]"); assertEquals("expected 550 error", 550, smtpProtocol.getReplyCode()); } public void testHandleAnnouncedMessageSizeLimitExceeded() throws Exception { m_testConfiguration.setMaxMessageSize(1); // set message limit to 1kb finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.sendCommand("MAIL FROM:<mail@localhost> SIZE=1025", null); assertEquals("expected error: max msg size exceeded", 552, smtpProtocol.getReplyCode()); smtpProtocol.addRecipient("mail@localhost"); assertEquals("expected error", 503, smtpProtocol.getReplyCode()); } public void testHandleMessageSizeLimitExceeded() throws Exception { m_testConfiguration.setMaxMessageSize(1); // set message limit to 1kb finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("mail@localhost"); smtpProtocol.addRecipient("mail@localhost"); Writer wr = smtpProtocol.sendMessageData(); // create Body with more than 1kb . 502 wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100\r\n"); // second line wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("123456781012345678201\r\n"); // 521 + CRLF = 523 + 502 => 1025 wr.close(); assertFalse(smtpProtocol.completePendingCommand()); assertEquals("expected 552 error", 552, smtpProtocol.getReplyCode()); } public void testHandleMessageSizeLimitRespected() throws Exception { m_testConfiguration.setMaxMessageSize(1); // set message limit to 1kb finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo "+InetAddress.getLocalHost()); smtpProtocol.setSender("mail@localhost"); smtpProtocol.addRecipient("mail@localhost"); Writer wr = smtpProtocol.sendMessageData(); // create Body with less than 1kb wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012345678301234567840123456785012345678601234567870123456788012345678901234567100"); wr.write("1234567810123456782012\r\n"); // 1022 + CRLF = 1024 wr.close(); assertTrue(smtpProtocol.completePendingCommand()); assertEquals("expected 250 ok", 250, smtpProtocol.getReplyCode()); } public void testConnectionLimitExceeded() throws Exception { m_testConfiguration.setConnectionLimit(1); // allow no more than one connection at a time finishSetUp(m_testConfiguration); SMTPClient smtpProtocol1 = new SMTPClient(); SMTPClient smtpProtocol2 = new SMTPClient(); smtpProtocol1.connect("127.0.0.1", m_smtpListenerPort); assertTrue("first connection taken", smtpProtocol1.isConnected()); try { smtpProtocol2.connect("127.0.0.1", m_smtpListenerPort); fail("second connection not taken1"); } catch (Exception e) { } // disconnect the first smtpProtocol1.quit(); smtpProtocol1.disconnect(); Thread.sleep(100); // now the second should be able to connect smtpProtocol2.connect("127.0.0.1", m_smtpListenerPort); assertTrue(smtpProtocol2.isConnected()); } // RemoteDelivery tests. InMemorySpoolRepository outgoingSpool; private MockServiceManager m_serviceManager; private AlterableDNSServer m_dnsServer; private Properties getStandardParameters() { Properties parameters = new Properties(); parameters.put("delayTime", "500 msec, 500 msec, 500 msec"); // msec, sec, minute, hour parameters.put("maxRetries", "3"); parameters.put("deliveryThreads", "1"); parameters.put("debug", "true"); parameters.put("sendpartial", "false"); parameters.put("bounceProcessor", "bounce"); parameters.put("outgoing", "mocked://outgoing/"); return parameters; } /** * This has been created to test javamail 1.4 introduced bug. * http://issues.apache.org/jira/browse/JAMES-490 */ public void testDeliveryToSelfWithGatewayAndBind() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("bind", "127.0.0.1"); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); String sources = "Content-Type: text/plain;\r\nSubject: test\r\n\r\nBody"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } verifyLastMail(sender, recipient, null); assertEquals(((String) mm.getContent()).trim(),((String) ((MimeMessage) m_mailServer.getLastMail().getMessage()).getContent()).trim()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeFromStream() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); //String sources = "Content-Type: text/plain;\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeFromStreamWith8bitContent() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); //String sources = "Content-Type: text/plain;\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeFromStreamWithoutContentTransferEncoding() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); String sources = "Content-Type: text/plain;\r\nSubject: test\r\n\r\nBody\u03B2\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeFromStreamWithoutContentTransferEncodingSentAs8bit() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); rd.init(mci); String sources = "Content-Type: text/plain;\r\nSubject: test\r\n\r\nBody=32=48\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } /** * This is useful code to run tests on javamail bugs * http://issues.apache.org/jira/browse/JAMES-52 * * This one passes with javamail 1.4.1EA * @throws Exception */ public void test8bitmimeWith8bitmimeDisabledInServer() throws Exception { finishSetUp(m_testConfiguration); outgoingSpool = new InMemorySpoolRepository(); ((MockStore) m_serviceManager.lookup(Store.ROLE)).add("outgoing", outgoingSpool); RemoteDelivery rd = new RemoteDelivery(); MockMailContext mmc = new MockMailContext(); mmc.setAttribute(Constants.AVALON_COMPONENT_MANAGER,m_serviceManager); mmc.setAttribute(Constants.HELLO_NAME,"localhost"); MockMailetConfig mci = new MockMailetConfig("Test",mmc,getStandardParameters()); mci.setProperty("gateway","127.0.0.1"); mci.setProperty("gatewayPort",""+m_smtpListenerPort); mci.setProperty("mail.smtp.allow8bitmime", "false"); rd.init(mci); //String sources = "Content-Type: text/plain;\r\nSubject: test\r\n\r\nBody=32=48\r\n"; //String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: quoted-printable\r\nSubject: test\r\n\r\nBody=80\r\n"; String sources = "Content-Type: text/plain; charset=iso-8859-15\r\nContent-Transfer-Encoding: 8bit\r\nSubject: test\r\n\r\nBody\u20AC\r\n"; String sender = "test@localhost"; String recipient = "test@localhost"; MimeMessage mm = new MimeMessage(Session.getDefaultInstance(new Properties()),new ByteArrayInputStream(sources.getBytes())); MailImpl mail = new MailImpl("name",new MailAddress(sender),Arrays.asList(new MailAddress[] {new MailAddress(recipient)}),mm); rd.service(mail); while (outgoingSpool.size() > 0) { Thread.sleep(1000); } // verifyLastMail(sender, recipient, mm); verifyLastMail(sender, recipient, null); // THIS WOULD FAIL BECAUSE OF THE JAVAMAIL BUG assertEquals(mm.getContent(),m_mailServer.getLastMail().getMessage().getContent()); mail.dispose(); } // Check if auth users get not rejected cause rbl. See JAMES-566 public void testDNSRBLNotRejectAuthUser() throws Exception { m_testConfiguration.setAuthorizedAddresses("192.168.0.1/32"); m_testConfiguration.setAuthorizingAnnounce(); m_testConfiguration.useRBL(true); finishSetUp(m_testConfiguration); m_dnsServer.setLocalhostByName(InetAddress.getByName("127.0.0.1")); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); String[] capabilityRes = smtpProtocol.getReplyStrings(); List capabilitieslist = new ArrayList(); for (int i = 1; i < capabilityRes.length; i++) { capabilitieslist.add(capabilityRes[i].substring(4)); } assertTrue("anouncing auth required", capabilitieslist .contains("AUTH LOGIN PLAIN")); // is this required or just for compatibility? assertTrue("anouncing // auth required", capabilitieslist.contains("AUTH=LOGIN PLAIN")); String userName = "test_user_smtp"; String sender = "test_user_smtp@localhost"; smtpProtocol.setSender(sender); m_usersRepository.addUser(userName, "pwd"); smtpProtocol.sendCommand("AUTH PLAIN"); smtpProtocol.sendCommand(Base64.encodeAsString("\0" + userName + "\0pwd\0")); assertEquals("authenticated", 235, smtpProtocol.getReplyCode()); smtpProtocol.addRecipient("[email protected]"); assertEquals("authenticated.. not reject", 250, smtpProtocol .getReplyCode()); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nTest body testDNSRBLNotRejectAuthUser\r\n"); smtpProtocol.quit(); // mail was propagated by SMTPServer assertNotNull("mail received by mail server", m_mailServer .getLastMail()); } public void testDNSRBLRejectWorks() throws Exception { m_testConfiguration.setAuthorizedAddresses("192.168.0.1/32"); m_testConfiguration.useRBL(true); finishSetUp(m_testConfiguration); m_dnsServer.setLocalhostByName(InetAddress.getByName("127.0.0.1")); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); String sender = "test_user_smtp@localhost"; smtpProtocol.setSender(sender); smtpProtocol.addRecipient("[email protected]"); assertEquals("reject", 550, smtpProtocol .getReplyCode()); smtpProtocol.sendShortMessageData("Subject: test\r\n\r\nTest body testDNSRBLRejectWorks\r\n"); smtpProtocol.quit(); // mail was rejected by SMTPServer assertNull("mail reject by mail server", m_mailServer .getLastMail()); } public void testAddressBracketsEnforcementDisabled() throws Exception { m_testConfiguration.setAddressBracketsEnforcement(false); finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); smtpProtocol.sendCommand("mail from:", "test@localhost"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("rcpt to:", "[email protected]"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.quit(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); smtpProtocol.sendCommand("mail from:", "<test@localhost>"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("rcpt to:", "<[email protected]>"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.quit(); } public void testAddressBracketsEnforcementEnabled() throws Exception { finishSetUp(m_testConfiguration); SMTPClient smtpProtocol = new SMTPClient(); smtpProtocol.connect("127.0.0.1", m_smtpListenerPort); smtpProtocol.sendCommand("ehlo", InetAddress.getLocalHost().toString()); smtpProtocol.sendCommand("mail from:", "test@localhost"); assertEquals("reject", 501,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("mail from:", "<test@localhost>"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("rcpt to:", "[email protected]"); assertEquals("reject", 501,smtpProtocol.getReplyCode()); smtpProtocol.sendCommand("rcpt to:", "<[email protected]>"); assertEquals("accept", 250,smtpProtocol.getReplyCode()); smtpProtocol.quit(); } public void testPipelining() throws Exception { StringBuffer buf = new StringBuffer(); finishSetUp(m_testConfiguration); Socket client = new Socket("127.0.0.1",m_smtpListenerPort); buf.append("HELO TEST"); buf.append("\r\n"); buf.append("MAIL FROM: <test@localhost>"); buf.append("\r\n"); buf.append("RCPT TO: <test2@localhost>"); buf.append("\r\n"); buf.append("DATA"); buf.append("\r\n"); buf.append("Subject: test"); buf.append("\r\n");; buf.append("\r\n"); buf.append("content"); buf.append("\r\n"); buf.append("."); buf.append("\r\n"); buf.append("quit"); buf.append("\r\n"); OutputStream out = client.getOutputStream(); out.write(buf.toString().getBytes()); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); assertEquals("Connection made" , 220, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("HELO accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("MAIL FROM accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("RCPT TO accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("DATA accepted" , 354, Integer.parseInt(in.readLine().split(" ")[0])); assertEquals("Message accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); in.close(); out.close(); client.close(); } }
Add 2 more junit tests for pipeling git-svn-id: 88158f914d5603334254b4adf21dfd50ec107162@464486 13f79535-47bb-0310-9956-ffa450edef68
trunk/src/test/org/apache/james/smtpserver/SMTPServerTest.java
Add 2 more junit tests for pipeling
<ide><path>runk/src/test/org/apache/james/smtpserver/SMTPServerTest.java <ide> import javax.mail.Session; <ide> import javax.mail.internet.MimeMessage; <ide> <del>import java.io.BufferedInputStream; <ide> import java.io.BufferedReader; <ide> import java.io.ByteArrayInputStream; <ide> import java.io.ByteArrayOutputStream; <ide> smtpProtocol.quit(); <ide> } <ide> <add> // See http://www.ietf.org/rfc/rfc2920.txt 4: Examples <ide> public void testPipelining() throws Exception { <ide> StringBuffer buf = new StringBuffer(); <ide> finishSetUp(m_testConfiguration); <ide> out.close(); <ide> client.close(); <ide> } <add> <add> // See http://www.ietf.org/rfc/rfc2920.txt 4: Examples <add> public void testRejectAllRCPTPipelining() throws Exception { <add> StringBuffer buf = new StringBuffer(); <add> m_testConfiguration.setAuthorizedAddresses(""); <add> finishSetUp(m_testConfiguration); <add> Socket client = new Socket("127.0.0.1",m_smtpListenerPort); <add> <add> buf.append("HELO TEST"); <add> buf.append("\r\n"); <add> buf.append("MAIL FROM: <test@localhost>"); <add> buf.append("\r\n"); <add> buf.append("RCPT TO: <test@invalid>"); <add> buf.append("\r\n"); <add> buf.append("RCPT TO: <test2@invalid>"); <add> buf.append("\r\n"); <add> buf.append("DATA"); <add> buf.append("\r\n"); <add> buf.append("Subject: test"); <add> buf.append("\r\n");; <add> buf.append("\r\n"); <add> buf.append("content"); <add> buf.append("\r\n"); <add> buf.append("."); <add> buf.append("\r\n"); <add> buf.append("quit"); <add> buf.append("\r\n"); <add> <add> OutputStream out = client.getOutputStream(); <add> <add> out.write(buf.toString().getBytes()); <add> out.flush(); <add> <add> BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); <add> <add> assertEquals("Connection made" , 220, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("HELO accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("MAIL FROM accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("RCPT TO rejected" , 550, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("RCPT TO rejected" , 550, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("DATA not accepted" , 503, Integer.parseInt(in.readLine().split(" ")[0])); <add> in.close(); <add> out.close(); <add> client.close(); <add> } <add> <add> public void testRejectOneRCPTPipelining() throws Exception { <add> StringBuffer buf = new StringBuffer(); <add> m_testConfiguration.setAuthorizedAddresses(""); <add> finishSetUp(m_testConfiguration); <add> Socket client = new Socket("127.0.0.1",m_smtpListenerPort); <add> <add> buf.append("HELO TEST"); <add> buf.append("\r\n"); <add> buf.append("MAIL FROM: <test@localhost>"); <add> buf.append("\r\n"); <add> buf.append("RCPT TO: <test@invalid>"); <add> buf.append("\r\n"); <add> buf.append("RCPT TO: <test2@localhost>"); <add> buf.append("\r\n"); <add> buf.append("DATA"); <add> buf.append("\r\n"); <add> buf.append("Subject: test"); <add> buf.append("\r\n");; <add> buf.append("\r\n"); <add> buf.append("content"); <add> buf.append("\r\n"); <add> buf.append("."); <add> buf.append("\r\n"); <add> buf.append("quit"); <add> buf.append("\r\n"); <add> <add> OutputStream out = client.getOutputStream(); <add> <add> out.write(buf.toString().getBytes()); <add> out.flush(); <add> <add> BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); <add> <add> assertEquals("Connection made" , 220, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("HELO accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("MAIL FROM accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("RCPT TO rejected" , 550, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("RCPT accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("DATA accepted" , 354, Integer.parseInt(in.readLine().split(" ")[0])); <add> assertEquals("Message accepted" , 250, Integer.parseInt(in.readLine().split(" ")[0])); <add> in.close(); <add> out.close(); <add> client.close(); <add> } <ide> }
Java
agpl-3.0
6ca816dec71fb99f56b96108267911971549503d
0
OPEN-ENT-NG/collaborative-editor,OPEN-ENT-NG/collaborative-editor,OPEN-ENT-NG/collaborative-editor,OPEN-ENT-NG/collaborative-editor,OPEN-ENT-NG/collaborative-editor
/* * Copyright © Région Nord Pas de Calais-Picardie, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.collaborativeeditor.helpers; import fr.wseduc.webutils.Either; import fr.wseduc.webutils.I18n; import fr.wseduc.webutils.http.Renders; import fr.wseduc.webutils.request.CookieHelper; import fr.wseduc.webutils.request.RequestUtils; import org.entcore.common.mongodb.MongoDbControllerHelper; import org.entcore.common.service.CrudService; import org.entcore.common.service.VisibilityFilter; import org.entcore.common.service.impl.MongoDbCrudService; import org.entcore.common.user.UserInfos; import org.entcore.common.user.UserUtils; import org.etherpad_lite_client.EPLiteClient; import org.vertx.java.core.Handler; import org.vertx.java.core.Vertx; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import org.vertx.java.core.logging.Logger; import org.vertx.java.core.logging.impl.LoggerFactory; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.UUID; import java.util.concurrent.atomic.AtomicInteger; import static org.entcore.common.http.response.DefaultResponseHandler.notEmptyResponseHandler; public class EtherpadHelper extends MongoDbControllerHelper { /** * Class logger */ private static final Logger log = LoggerFactory.getLogger(EtherpadHelper.class); /** * Etherpad client */ private final EPLiteClient client; /** * Etherpad public URL */ private final String etherpadPublicUrl; /** * Etherpad domain for authentication cookie into collaborative-editor and pad service */ private final String domain; /** * Mongo CRUD service */ private final CrudService etherpadCrudService; /** * Constructor * @param collection Mongo collection to request * @param etherpadUrl Etherpad service internal URL * @param etherpadApiKey Etherpad API key * @param etherpadPublicUrl Etherpad service public URL */ public EtherpadHelper(Vertx vertx, String collection, String etherpadUrl, String etherpadApiKey, String etherpadPublicUrl, Boolean trustAll, String domain) { super(collection); this.etherpadCrudService = new MongoDbCrudService(collection); if (null == etherpadUrl || etherpadUrl.trim().isEmpty()) { log.error("[Collaborative Editor] Error : Module property 'etherpad-url' must be defined"); } if (null == etherpadApiKey || etherpadApiKey.trim().isEmpty()) { log.error("[Collaborative Editor] Error : Module property 'etherpad-api-key' must be defined"); } if (null == etherpadPublicUrl || etherpadPublicUrl.trim().isEmpty()) { this.etherpadPublicUrl = etherpadUrl; log.error("[Collaborative Editor] Warning : Module property 'etherpad-public-url' is not defined. Using 'etherpad-url'..."); } else { this.etherpadPublicUrl = etherpadPublicUrl; } if (null == domain || domain.trim().isEmpty()) { log.error("[Collaborative Editor] Error : Module property 'etherpad-domain' must be defined"); } this.domain = domain; this.client = new EPLiteClient(vertx, etherpadUrl, etherpadApiKey, trustAll); } @Override public void create(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { if (user != null) { final String randomName = UUID.randomUUID().toString(); client.createGroup(new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String groupID = event.getString("groupID"); client.createGroupPad(groupID, randomName, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String padName = event.getString("padID"); RequestUtils.bodyToJson(request, new Handler<JsonObject>() { @Override public void handle(JsonObject object) { object.putString("epName", padName); object.putString("epGroupID", groupID); object.putString("locale", I18n.acceptLanguage(request)); etherpadCrudService.create(object, user, notEmptyResponseHandler(request)); } }); } else { Renders.renderError(request, event); } } }); } else { Renders.renderError(request, event); } } }); } else { log.debug("User not found in session."); Renders.unauthorized(request); } } }); } @Override public void retrieve(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { String id = request.params().get("id"); etherpadCrudService.retrieve(id, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isRight()) { if (event.right().getValue() != null && event.right().getValue().size() > 0) { final JsonObject object = event.right().getValue(); // Create author if he doesn't exists client.createAuthorIfNotExistsFor(user.getLogin(), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String authorID = event.getString("authorID"); // Create session for the user on the pad group Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris")); Date now = calendar.getTime(); final long validUntil = (now.getTime() + (2 * 60L * 60L * 1000L)) / 1000L; client.createSession(object.getString("epGroupID"), authorID, validUntil, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String session = event.getString("sessionID"); request.response().putHeader("Set-Cookie", "sessionID=" + session + ";max-age=" + 2 * 360 * 1000 + ";path=/;domain=" + domain); object.putString("url", etherpadPublicUrl + "/p/" + object.getString("epName")); object.removeField("epGroupID"); object.removeField("epName"); Renders.renderJson(request, object, 200); } else { Renders.renderError(request, event); } } }); } else { Renders.renderError(request, event); } } }); } else { request.response().setStatusCode(404).end(); } } else { JsonObject error = new JsonObject().putString("error", event.left().getValue()); Renders.renderJson(request, error, 400); } } }); } }); } @Override public void list(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { final String filter = request.params().get("filter"); VisibilityFilter v = VisibilityFilter.ALL; if (filter != null) { try { v = VisibilityFilter.valueOf(filter.toUpperCase()); } catch (IllegalArgumentException | NullPointerException e) { v = VisibilityFilter.ALL; if (log.isDebugEnabled()) { log.debug("Invalid filter " + filter); } } } final String userDisplayName = user.getUsername(); etherpadCrudService.list(v, user, new Handler<Either<String, JsonArray>>() { @Override public void handle(Either<String, JsonArray> event) { if (event.isRight()) { final JsonArray objects = event.right().getValue(); final AtomicInteger callCount = new AtomicInteger(objects.size()); for (int i=0;i<objects.size();i++) { final JsonObject jsonObject = (JsonObject) objects.get(i); client.getReadOnlyID(jsonObject.getString("epName"), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getString("status"))) { final String readOnlyId = event.getString("readOnlyID"); try { final String urlReadOnlyStr = etherpadPublicUrl + "/p/" + readOnlyId + "?userName=" + userDisplayName; final URL urlReadOnly = new URL(urlReadOnlyStr); final URI uriReadOnly = new URI(urlReadOnly.getProtocol(), urlReadOnly.getUserInfo(), urlReadOnly.getHost(), urlReadOnly.getPort(), urlReadOnly.getPath(), urlReadOnly.getQuery(), urlReadOnly.getRef()); jsonObject.putString("readOnlyUrl", uriReadOnly.toASCIIString()); final String urlStr = etherpadPublicUrl + "/p/" + jsonObject.getString("epName") + "?userName=" + userDisplayName; final URL url = new URL(urlStr); final URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); jsonObject.putString("url", uri.toASCIIString()); } catch (MalformedURLException | URISyntaxException e) { log.error("Can't generate etherpad-lite url", e); } jsonObject.removeField("epName"); jsonObject.removeField("epGroupID"); if (callCount.decrementAndGet() == 0) { Renders.renderJson(request, objects); return; } } else { //only log the error if the mongo entry don't link with a real pad log.error(event.getString("message")); if (callCount.decrementAndGet() == 0) { Renders.renderJson(request, objects); return; } } } }); } } else { JsonObject error = new JsonObject().putString("error", event.left().getValue()); Renders.renderJson(request, error, 400); } } }); } }); } /** * Create a user session on a collaborative editor * @param request HTTP request */ public void createSession(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { String id = request.params().get("id"); etherpadCrudService.retrieve(id, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isRight()) { if (event.right().getValue() != null && event.right().getValue().size() > 0) { final JsonObject object = event.right().getValue(); // Create author if he doesn't exists client.createAuthorIfNotExistsFor(user.getLogin(), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String authorID = event.getString("authorID"); // Create session for the user on the pad group Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris")); calendar.setTime(new Date()); Date now = calendar.getTime(); long validUntil = (now.getTime() + (1 * 60L * 60L * 1000L)) / 1000L; client.createSession(object.getString("epGroupID"), authorID, validUntil, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String session = event.getString("sessionID"); request.response().putHeader("Set-Cookie", "sessionID=" + session + ";max-age=" + 360 * 1000 + ";path=/;domain=" + domain).setStatusCode(200).end(); } else { Renders.renderError(request, event); } } }); } else { Renders.renderError(request, event); } } }); } else { request.response().setStatusCode(404).end(); } } else { JsonObject error = new JsonObject().putString("error", event.left().getValue()); Renders.renderJson(request, error, 400); } } }); } }); } /** * Delete a user session on a collaborative editor * @param request HTTP request */ public void deleteSession(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { String sessionID = CookieHelper.get("sessionID", request); if (sessionID != null) { client.deleteSession(sessionID, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { request.response().putHeader("Set-Cookie", "sessionID=deleted;max-age=-1;path=/;domain=" + domain).setStatusCode(200).end(); } else { //TODO check if render error because there is a redmine ticket about error log on session doesn't exist !!!!! Renders.renderError(request, event); } } }); } else { request.response().setStatusCode(200).end(); } } }); } @Override public void delete(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { if (user != null) { final String id = request.params().get("id"); etherpadCrudService.retrieve(id, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isRight()) { if (event.right().getValue() != null && event.right().getValue().size() > 0) { final JsonObject object = event.right().getValue(); etherpadCrudService.delete(id, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isRight()) { client.deletePad(object.getString("epName"), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if (!"ok".equals(event.getString("status"))) { log.error("Fail to delete a pad on backend " + event.getString("message")); } } }); client.deleteGroup(object.getString("epGroupID"), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if (!"ok".equals(event.getString("status"))) { log.error("Fail to delete a group on backend " + event.getString("message")); } } }); Renders.renderJson(request, event.right().getValue(), 200); } else { log.error("Fail to delete a pad on mongo backend from id : " + id + ", error : " + event.left().getValue()); Renders.renderError(request, new JsonObject().putString("error", event.left().getValue())); } } }); } else { Renders.renderError(request, new JsonObject().putString("error", "Empty result from id : " + id)); } } else { Renders.renderError(request, new JsonObject().putString("error", event.left().getValue())); } } }); } else { log.debug("User not found in session."); Renders.unauthorized(request); } } }); } }
src/main/java/net/atos/entng/collaborativeeditor/helpers/EtherpadHelper.java
/* * Copyright © Région Nord Pas de Calais-Picardie, 2016. * * This file is part of OPEN ENT NG. OPEN ENT NG is a versatile ENT Project based on the JVM and ENT Core Project. * * 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 (version 3 of the License). * * For the sake of explanation, any module that communicate over native * Web protocols, such as HTTP, with OPEN ENT NG is outside the scope of this * license and could be license under its own terms. This is merely considered * normal use of OPEN ENT NG, and does not fall under the heading of "covered work". * * 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. */ package net.atos.entng.collaborativeeditor.helpers; import fr.wseduc.webutils.Either; import fr.wseduc.webutils.I18n; import fr.wseduc.webutils.http.Renders; import fr.wseduc.webutils.request.CookieHelper; import fr.wseduc.webutils.request.RequestUtils; import org.entcore.common.mongodb.MongoDbControllerHelper; import org.entcore.common.service.CrudService; import org.entcore.common.service.VisibilityFilter; import org.entcore.common.service.impl.MongoDbCrudService; import org.entcore.common.user.UserInfos; import org.entcore.common.user.UserUtils; import org.etherpad_lite_client.EPLiteClient; import org.vertx.java.core.Handler; import org.vertx.java.core.Vertx; import org.vertx.java.core.http.HttpServerRequest; import org.vertx.java.core.json.JsonArray; import org.vertx.java.core.json.JsonObject; import org.vertx.java.core.logging.Logger; import org.vertx.java.core.logging.impl.LoggerFactory; import java.net.MalformedURLException; import java.net.URI; import java.net.URISyntaxException; import java.net.URL; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.util.UUID; import static org.entcore.common.http.response.DefaultResponseHandler.notEmptyResponseHandler; public class EtherpadHelper extends MongoDbControllerHelper { /** * Class logger */ private static final Logger log = LoggerFactory.getLogger(EtherpadHelper.class); /** * Etherpad client */ private final EPLiteClient client; /** * Etherpad public URL */ private final String etherpadPublicUrl; /** * Etherpad domain for authentication cookie into collaborative-editor and pad service */ private final String domain; /** * Mongo CRUD service */ private final CrudService etherpadCrudService; /** * Constructor * @param collection Mongo collection to request * @param etherpadUrl Etherpad service internal URL * @param etherpadApiKey Etherpad API key * @param etherpadPublicUrl Etherpad service public URL */ public EtherpadHelper(Vertx vertx, String collection, String etherpadUrl, String etherpadApiKey, String etherpadPublicUrl, Boolean trustAll, String domain) { super(collection); this.etherpadCrudService = new MongoDbCrudService(collection); if (null == etherpadUrl || etherpadUrl.trim().isEmpty()) { log.error("[Collaborative Editor] Error : Module property 'etherpad-url' must be defined"); } if (null == etherpadApiKey || etherpadApiKey.trim().isEmpty()) { log.error("[Collaborative Editor] Error : Module property 'etherpad-api-key' must be defined"); } if (null == etherpadPublicUrl || etherpadPublicUrl.trim().isEmpty()) { this.etherpadPublicUrl = etherpadUrl; log.error("[Collaborative Editor] Warning : Module property 'etherpad-public-url' is not defined. Using 'etherpad-url'..."); } else { this.etherpadPublicUrl = etherpadPublicUrl; } if (null == domain || domain.trim().isEmpty()) { log.error("[Collaborative Editor] Error : Module property 'etherpad-domain' must be defined"); } this.domain = domain; this.client = new EPLiteClient(vertx, etherpadUrl, etherpadApiKey, trustAll); } @Override public void create(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { if (user != null) { final String randomName = UUID.randomUUID().toString(); client.createGroup(new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String groupID = event.getString("groupID"); client.createGroupPad(groupID, randomName, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String padName = event.getString("padID"); RequestUtils.bodyToJson(request, new Handler<JsonObject>() { @Override public void handle(JsonObject object) { object.putString("epName", padName); object.putString("epGroupID", groupID); object.putString("locale", I18n.acceptLanguage(request)); etherpadCrudService.create(object, user, notEmptyResponseHandler(request)); } }); } else { Renders.renderError(request, event); } } }); } else { Renders.renderError(request, event); } } }); } else { log.debug("User not found in session."); Renders.unauthorized(request); } } }); } @Override public void retrieve(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { String id = request.params().get("id"); etherpadCrudService.retrieve(id, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isRight()) { if (event.right().getValue() != null && event.right().getValue().size() > 0) { final JsonObject object = event.right().getValue(); // Create author if he doesn't exists client.createAuthorIfNotExistsFor(user.getLogin(), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String authorID = event.getString("authorID"); // Create session for the user on the pad group Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris")); Date now = calendar.getTime(); final long validUntil = (now.getTime() + (2 * 60L * 60L * 1000L)) / 1000L; client.createSession(object.getString("epGroupID"), authorID, validUntil, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String session = event.getString("sessionID"); request.response().putHeader("Set-Cookie", "sessionID=" + session + ";max-age=" + 2 * 360 * 1000 + ";path=/;domain=" + domain); object.putString("url", etherpadPublicUrl + "/p/" + object.getString("epName")); object.removeField("epGroupID"); object.removeField("epName"); Renders.renderJson(request, object, 200); } else { Renders.renderError(request, event); } } }); } else { Renders.renderError(request, event); } } }); } else { request.response().setStatusCode(404).end(); } } else { JsonObject error = new JsonObject().putString("error", event.left().getValue()); Renders.renderJson(request, error, 400); } } }); } }); } @Override public void list(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { String filter = request.params().get("filter"); VisibilityFilter v = VisibilityFilter.ALL; if (filter != null) { try { v = VisibilityFilter.valueOf(filter.toUpperCase()); } catch (IllegalArgumentException | NullPointerException e) { v = VisibilityFilter.ALL; if (log.isDebugEnabled()) { log.debug("Invalid filter " + filter); } } } etherpadCrudService.list(v, user, new Handler<Either<String, JsonArray>>() { @Override public void handle(Either<String, JsonArray> event) { if (event.isRight()) { final JsonArray objects = event.right().getValue(); final int count = objects.size(); for (int i=0;i<count;i++) { final JsonObject jsonObject = (JsonObject) objects.get(i); final int current = i+1; client.getReadOnlyID(jsonObject.getString("epName"), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getString("status"))) { final String readOnlyId = event.getString("readOnlyID"); String userDisplayName = user.getUsername(); try { String urlReadOnlyStr = etherpadPublicUrl + "/p/" + readOnlyId + "?userName=" + userDisplayName; URL urlReadOnly = new URL(urlReadOnlyStr); URI uriReadOnly = new URI(urlReadOnly.getProtocol(), urlReadOnly.getUserInfo(), urlReadOnly.getHost(), urlReadOnly.getPort(), urlReadOnly.getPath(), urlReadOnly.getQuery(), urlReadOnly.getRef()); jsonObject.putString("readOnlyUrl", uriReadOnly.toASCIIString()); String urlStr = etherpadPublicUrl + "/p/" + jsonObject.getString("epName") + "?userName=" + userDisplayName; URL url = new URL(urlStr); URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); jsonObject.putString("url", uri.toASCIIString()); if (current == objects.size()) { Renders.renderJson(request, objects); return; } } catch (MalformedURLException | URISyntaxException e) { log.error(e); request.response().setStatusCode(500).end(); } jsonObject.removeField("epName"); jsonObject.removeField("epGroupID"); } else { //only log the error if the mongo entry don't link with a real pad log.error(event.getString("message")); if (current == objects.size()) { Renders.renderJson(request, objects); return; } } } }); } } else { JsonObject error = new JsonObject().putString("error", event.left().getValue()); Renders.renderJson(request, error, 400); } } }); } }); } /** * Create a user session on a collaborative editor * @param request HTTP request */ public void createSession(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { String id = request.params().get("id"); etherpadCrudService.retrieve(id, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isRight()) { if (event.right().getValue() != null && event.right().getValue().size() > 0) { final JsonObject object = event.right().getValue(); // Create author if he doesn't exists client.createAuthorIfNotExistsFor(user.getLogin(), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String authorID = event.getString("authorID"); // Create session for the user on the pad group Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Paris")); calendar.setTime(new Date()); Date now = calendar.getTime(); long validUntil = (now.getTime() + (1 * 60L * 60L * 1000L)) / 1000L; client.createSession(object.getString("epGroupID"), authorID, validUntil, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { final String session = event.getString("sessionID"); request.response().putHeader("Set-Cookie", "sessionID=" + session + ";max-age=" + 360 * 1000 + ";path=/;domain=" + domain).setStatusCode(200).end(); } else { Renders.renderError(request, event); } } }); } else { Renders.renderError(request, event); } } }); } else { request.response().setStatusCode(404).end(); } } else { JsonObject error = new JsonObject().putString("error", event.left().getValue()); Renders.renderJson(request, error, 400); } } }); } }); } /** * Delete a user session on a collaborative editor * @param request HTTP request */ public void deleteSession(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { String sessionID = CookieHelper.get("sessionID", request); if (sessionID != null) { client.deleteSession(sessionID, new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if ("ok".equals(event.getField("status"))) { request.response().putHeader("Set-Cookie", "sessionID=deleted;max-age=-1;path=/;domain=" + domain).setStatusCode(200).end(); } else { //TODO check if render error because there is a redmine ticket about error log on session doesn't exist !!!!! Renders.renderError(request, event); } } }); } else { request.response().setStatusCode(200).end(); } } }); } @Override public void delete(final HttpServerRequest request) { UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { @Override public void handle(final UserInfos user) { if (user != null) { final String id = request.params().get("id"); etherpadCrudService.retrieve(id, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isRight()) { if (event.right().getValue() != null && event.right().getValue().size() > 0) { final JsonObject object = event.right().getValue(); etherpadCrudService.delete(id, user, new Handler<Either<String, JsonObject>>() { @Override public void handle(Either<String, JsonObject> event) { if (event.isRight()) { client.deletePad(object.getString("epName"), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if (!"ok".equals(event.getString("status"))) { log.error("Fail to delete a pad on backend " + event.getString("message")); } } }); client.deleteGroup(object.getString("epGroupID"), new Handler<JsonObject>() { @Override public void handle(JsonObject event) { if (!"ok".equals(event.getString("status"))) { log.error("Fail to delete a group on backend " + event.getString("message")); } } }); Renders.renderJson(request, event.right().getValue(), 200); } else { log.error("Fail to delete a pad on mongo backend from id : " + id + ", error : " + event.left().getValue()); Renders.renderError(request, new JsonObject().putString("error", event.left().getValue())); } } }); } else { Renders.renderError(request, new JsonObject().putString("error", "Empty result from id : " + id)); } } else { Renders.renderError(request, new JsonObject().putString("error", event.left().getValue())); } } }); } else { log.debug("User not found in session."); Renders.unauthorized(request); } } }); } }
[Fix] #16254 : url generation on the pad list
src/main/java/net/atos/entng/collaborativeeditor/helpers/EtherpadHelper.java
[Fix] #16254 : url generation on the pad list
<ide><path>rc/main/java/net/atos/entng/collaborativeeditor/helpers/EtherpadHelper.java <ide> import java.util.Date; <ide> import java.util.TimeZone; <ide> import java.util.UUID; <add>import java.util.concurrent.atomic.AtomicInteger; <ide> <ide> import static org.entcore.common.http.response.DefaultResponseHandler.notEmptyResponseHandler; <ide> <ide> UserUtils.getUserInfos(eb, request, new Handler<UserInfos>() { <ide> @Override <ide> public void handle(final UserInfos user) { <del> String filter = request.params().get("filter"); <add> final String filter = request.params().get("filter"); <ide> VisibilityFilter v = VisibilityFilter.ALL; <ide> if (filter != null) { <ide> try { <ide> } <ide> } <ide> <add> final String userDisplayName = user.getUsername(); <add> <ide> etherpadCrudService.list(v, user, new Handler<Either<String, JsonArray>>() { <ide> @Override <ide> public void handle(Either<String, JsonArray> event) { <ide> if (event.isRight()) { <ide> final JsonArray objects = event.right().getValue(); <del> final int count = objects.size(); <del> <del> for (int i=0;i<count;i++) { <add> final AtomicInteger callCount = new AtomicInteger(objects.size()); <add> <add> for (int i=0;i<objects.size();i++) { <ide> final JsonObject jsonObject = (JsonObject) objects.get(i); <del> final int current = i+1; <add> <ide> client.getReadOnlyID(jsonObject.getString("epName"), new Handler<JsonObject>() { <ide> @Override <ide> public void handle(JsonObject event) { <ide> if ("ok".equals(event.getString("status"))) { <ide> final String readOnlyId = event.getString("readOnlyID"); <del> String userDisplayName = user.getUsername(); <add> <ide> try { <del> String urlReadOnlyStr = etherpadPublicUrl + "/p/" + readOnlyId + "?userName=" + userDisplayName; <del> URL urlReadOnly = new URL(urlReadOnlyStr); <del> URI uriReadOnly = new URI(urlReadOnly.getProtocol(), urlReadOnly.getUserInfo(), urlReadOnly.getHost(), urlReadOnly.getPort(), urlReadOnly.getPath(), urlReadOnly.getQuery(), urlReadOnly.getRef()); <add> final String urlReadOnlyStr = etherpadPublicUrl + "/p/" + readOnlyId + "?userName=" + userDisplayName; <add> final URL urlReadOnly = new URL(urlReadOnlyStr); <add> final URI uriReadOnly = new URI(urlReadOnly.getProtocol(), urlReadOnly.getUserInfo(), urlReadOnly.getHost(), urlReadOnly.getPort(), urlReadOnly.getPath(), urlReadOnly.getQuery(), urlReadOnly.getRef()); <ide> jsonObject.putString("readOnlyUrl", uriReadOnly.toASCIIString()); <ide> <del> String urlStr = etherpadPublicUrl + "/p/" + jsonObject.getString("epName") + "?userName=" + userDisplayName; <del> URL url = new URL(urlStr); <del> URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); <del> <add> final String urlStr = etherpadPublicUrl + "/p/" + jsonObject.getString("epName") + "?userName=" + userDisplayName; <add> final URL url = new URL(urlStr); <add> final URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef()); <ide> jsonObject.putString("url", uri.toASCIIString()); <del> if (current == objects.size()) { <del> Renders.renderJson(request, objects); <del> return; <del> } <ide> } catch (MalformedURLException | URISyntaxException e) { <del> log.error(e); <del> request.response().setStatusCode(500).end(); <add> log.error("Can't generate etherpad-lite url", e); <ide> } <ide> jsonObject.removeField("epName"); <ide> jsonObject.removeField("epGroupID"); <add> <add> if (callCount.decrementAndGet() == 0) { <add> Renders.renderJson(request, objects); <add> return; <add> } <ide> } else { <ide> //only log the error if the mongo entry don't link with a real pad <ide> log.error(event.getString("message")); <del> if (current == objects.size()) { <add> if (callCount.decrementAndGet() == 0) { <ide> Renders.renderJson(request, objects); <ide> return; <ide> }
Java
bsd-3-clause
af6939f912a2e459c2080b099d68e9cd8bf1ec0f
0
pecko/jcabi-log,simonjenga/jcabi-log,prondzyn/jcabi-log
/** * Copyright (c) 2012-2013, JCabi.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) 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. 3) Neither the name of the jcabi.com 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 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. */ package com.jcabi.log; import java.util.Formattable; import java.util.FormattableFlags; import java.util.Formatter; import java.util.Locale; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; /** * Abstract test case for all decors in the package. * @author Marina Kosenko ([email protected]) * @author Yegor Bugayenko ([email protected]) * @version $Id$ */ public abstract class AbstractDecorTest { /** * Object/system under test. */ private final transient Object sut; /** * The text to expect as an output. */ private final transient String text; /** * Formatting flas. */ private final transient int flags; /** * Formatting width. */ private final transient int width; /** * Formatting precision. */ private final transient int precision; /** * Public ctor. * @param obj The object * @param txt Expected text * @param flgs Flags * @param wdt Width * @param prcs Precission * @checkstyle ParameterNumber (3 lines) */ public AbstractDecorTest(final Object obj, final String txt, final int flgs, final int wdt, final int prcs) { this.sut = obj; this.text = txt; this.flags = flgs; this.width = wdt; this.precision = prcs; Locale.setDefault(Locale.US); } /** * AbstractDecor can convert object to text. * @throws Exception If some problem inside */ @Test public final void convertsDifferentFormats() throws Exception { final Formattable decor = this.decor(); final Appendable dest = Mockito.mock(Appendable.class); final Formatter fmt = new Formatter(dest); decor.formatTo(fmt, this.flags, this.width, this.precision); Mockito.verify(dest).append(this.text); } /** * AbstractDecor can convert object to text, via Logger. * @throws Exception If some problem inside */ @Test public final void convertsDifferentFormatsViaLogger() throws Exception { final StringBuilder format = new StringBuilder(); format.append('%'); if ((this.flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags .LEFT_JUSTIFY) { format.append('-'); } if (this.width > 0) { format.append(Integer.toString(this.width)); } if (this.precision > 0) { format.append('.').append(Integer.toString(this.precision)); } if ((this.flags & FormattableFlags.UPPERCASE) == FormattableFlags .UPPERCASE) { format.append('S'); } else { format.append('s'); } MatcherAssert.assertThat( Logger.format(format.toString(), this.decor()), Matchers.equalTo(this.text) ); } /** * Get decor with the object. * @return The decor to test * @throws Exception If some problem */ protected abstract Formattable decor() throws Exception; /** * Get object under test. * @return The object */ protected final Object object() { return this.sut; } }
src/test/java/com/jcabi/log/AbstractDecorTest.java
/** * Copyright (c) 2012-2013, JCabi.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) 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. 3) Neither the name of the jcabi.com 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 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. */ package com.jcabi.log; import java.util.Formattable; import java.util.FormattableFlags; import java.util.Formatter; import org.hamcrest.MatcherAssert; import org.hamcrest.Matchers; import org.junit.Test; import org.mockito.Mockito; /** * Abstract test case for all decors in the package. * @author Marina Kosenko ([email protected]) * @author Yegor Bugayenko ([email protected]) * @version $Id$ */ public abstract class AbstractDecorTest { /** * Object/system under test. */ private final transient Object sut; /** * The text to expect as an output. */ private final transient String text; /** * Formatting flas. */ private final transient int flags; /** * Formatting width. */ private final transient int width; /** * Formatting precision. */ private final transient int precision; /** * Public ctor. * @param obj The object * @param txt Expected text * @param flgs Flags * @param wdt Width * @param prcs Precission * @checkstyle ParameterNumber (3 lines) */ public AbstractDecorTest(final Object obj, final String txt, final int flgs, final int wdt, final int prcs) { this.sut = obj; this.text = txt; this.flags = flgs; this.width = wdt; this.precision = prcs; } /** * AbstractDecor can convert object to text. * @throws Exception If some problem inside */ @Test public final void convertsDifferentFormats() throws Exception { final Formattable decor = this.decor(); final Appendable dest = Mockito.mock(Appendable.class); final Formatter fmt = new Formatter(dest); decor.formatTo(fmt, this.flags, this.width, this.precision); Mockito.verify(dest).append(this.text); } /** * AbstractDecor can convert object to text, via Logger. * @throws Exception If some problem inside */ @Test public final void convertsDifferentFormatsViaLogger() throws Exception { final StringBuilder format = new StringBuilder(); format.append('%'); if ((this.flags & FormattableFlags.LEFT_JUSTIFY) == FormattableFlags .LEFT_JUSTIFY) { format.append('-'); } if (this.width > 0) { format.append(Integer.toString(this.width)); } if (this.precision > 0) { format.append('.').append(Integer.toString(this.precision)); } if ((this.flags & FormattableFlags.UPPERCASE) == FormattableFlags .UPPERCASE) { format.append('S'); } else { format.append('s'); } MatcherAssert.assertThat( Logger.format(format.toString(), this.decor()), Matchers.equalTo(this.text) ); } /** * Get decor with the object. * @return The decor to test * @throws Exception If some problem */ protected abstract Formattable decor() throws Exception; /** * Get object under test. * @return The object */ protected final Object object() { return this.sut; } }
fix assertion fail because of different decimal separator symbols in different locales
src/test/java/com/jcabi/log/AbstractDecorTest.java
fix assertion fail because of different decimal separator symbols in different locales
<ide><path>rc/test/java/com/jcabi/log/AbstractDecorTest.java <ide> import java.util.Formattable; <ide> import java.util.FormattableFlags; <ide> import java.util.Formatter; <add>import java.util.Locale; <ide> import org.hamcrest.MatcherAssert; <ide> import org.hamcrest.Matchers; <ide> import org.junit.Test; <ide> this.flags = flgs; <ide> this.width = wdt; <ide> this.precision = prcs; <add> Locale.setDefault(Locale.US); <ide> } <ide> <ide> /**
JavaScript
mit
879313a42cf3e3699224b34c6a8374a313e80ea1
0
CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web
'use strict'; angular.module('confRegistrationWebApp') .controller('ReviewRegistrationCtrl', function ($scope, $rootScope, $location, $route, modalMessage, $http, registration, conference, RegistrationCache, validateRegistrant, $filter) { $rootScope.globalPage = { type: 'registration', mainClass: 'container front-form', bodyClass: 'frontend', title: conference.name, confId: conference.id, footer: false }; if(_.isEmpty(registration.registrants)) { $location.path('/' + ($rootScope.registerMode || 'register') + '/' + conference.id + '/page/'); } $scope.conference = conference; $scope.currentRegistration = registration; $scope.blocks = []; $scope.regValidate = []; //check if group registration is allowed based on registrants already in registration if(!_.isEmpty(registration.registrants)){ $scope.allowGroupRegistration = false; angular.forEach(registration.registrants, function(r){ if($scope.allowGroupRegistration){ return; } var regType = _.find(conference.registrantTypes, { 'id': r.registrantTypeId }); $scope.allowGroupRegistration = regType.allowGroupRegistrations; }); } if (angular.isUndefined($scope.currentPayment)) { var paymentType; if(conference.acceptCreditCards) { paymentType = 'CREDIT_CARD'; }else if(conference.acceptChecks){ paymentType = 'CHECK'; }else if(conference.acceptTransfers){ paymentType = 'TRANSFER'; }else if(conference.acceptScholarships){ paymentType = 'SCHOLARSHIP'; } $scope.currentPayment = { amount: $scope.currentRegistration.remainingBalance, paymentType: paymentType, creditCard: {}, transfer: {}, scholarship: {} }; } angular.forEach(_.flatten(conference.registrationPages, 'blocks'), function (block) { if (block.type.indexOf('Content') === -1) { $scope.blocks.push(block); } }); angular.forEach(registration.registrants, function (r) { $scope.regValidate[r.id] = validateRegistrant.validate(conference, r); }); $scope.findAnswer = function (blockId) { return _.find($scope.answers, {blockId: blockId}); }; $scope.getBlock = function (blockId) { return _.find($scope.blocks, {id: blockId}); }; $scope.confirmRegistration = function () { $scope.submittingRegistration = true; /*if the totalPaid (previously) AND the amount of this payment are less than the minimum required deposit, then show and error message. the first payment must be at least the minimum deposit amount. subsequent payments can be less than the amount. this is confirmed by making sure the total previously paid is above the min deposit amount. */ if ($scope.currentRegistration.totalPaid < $scope.currentRegistration.calculatedMinimumDeposit && ($scope.currentPayment.amount + $scope.currentRegistration.totalPaid) < $scope.currentRegistration.calculatedMinimumDeposit) { $scope.currentPayment.errors.push('You are required to pay at least the minimum deposit of ' + $filter('moneyFormat')(registration.calculatedMinimumDeposit) + ' to register for this event.'); } if($scope.currentPayment.amount > $scope.currentRegistration.remainingBalance) { $scope.currentPayment.errors.push('You are paying more than the total due of ' + $filter('moneyFormat')(registration.remainingBalance) + ' to register for this event.'); } if ($scope.currentPayment.amount === 0 || !$scope.anyPaymentMethodAccepted()) { setRegistrationAsCompleted(); return; } if (!_.isEmpty($scope.currentPayment.errors)) { modalMessage.error($scope.currentPayment.errors, false, 'Please correct the following errors:'); $scope.submittingRegistration = false; return; } if($scope.currentPayment.paymentType === 'CHECK'){ if(!$scope.currentRegistration.completed){ setRegistrationAsCompleted(); }else{ $scope.submittingRegistration = false; } return; } var currentPayment = angular.copy($scope.currentPayment); currentPayment.readyToProcess = true; currentPayment.registrationId = registration.id; delete currentPayment.errors; if(currentPayment.paymentType === 'CREDIT_CARD'){ $http.get('payments/ccp-client-encryption-key').success(function(ccpClientEncryptionKey) { ccp.initialize(ccpClientEncryptionKey); currentPayment.creditCard.lastFourDigits = ccp.getAbbreviatedNumber(currentPayment.creditCard.number); currentPayment.creditCard.number = ccp.encrypt(currentPayment.creditCard.number); currentPayment.creditCard.cvvNumber = ccp.encrypt(currentPayment.creditCard.cvvNumber); postPayment(currentPayment); }).error(function() { modalMessage.error('An error occurred while requesting the ccp encryption key. Please try your payment again.'); }); }else{ postPayment(currentPayment); } }; var postPayment = function(currentPayment){ $http.post('payments/', currentPayment).success(function () { delete $scope.currentPayment; if(!$scope.currentRegistration.completed) { setRegistrationAsCompleted(); } else { $route.reload(); } }).error(function () { $scope.submittingRegistration = false; modalMessage.error('Your payment was declined, please verify your details or use a different payment method.', true); }); }; var setRegistrationAsCompleted = function() { registration.completed = true; RegistrationCache.update('registrations/' + registration.id, registration, function () { RegistrationCache.emptyCache(); $route.reload(); }, function (data) { $scope.currentRegistration.completed = false; $scope.submittingRegistration = false; modalMessage.error('An error occurred while submitting your registration. ' + (data.data.msg ? data.data.msg : '')); }); }; $scope.editRegistrant = function (id) { $location.path('/' + ($rootScope.registerMode || 'register') + '/' + conference.id + '/page/' + conference.registrationPages[0].id).search('reg', id); }; $scope.removeRegistrant = function (id) { modalMessage.confirm('Delete registrant?', 'Are you sure you want to delete this registrant?').then(function(){ _.remove($scope.currentRegistration.registrants, function(r) { return r.id === id; }); RegistrationCache.update('registrations/' + $scope.currentRegistration.id, $scope.currentRegistration, function() { $route.reload(); }); }); }; $scope.getRegistrantType = function(id){ return _.find(conference.registrantTypes, { 'id': id }); }; $scope.isBlockInvalid = function(rId, bId){ return _.contains($scope.regValidate[rId], bId); }; $scope.allRegistrantsValid = function(){ var returnVal = true; angular.forEach(registration.registrants, function (r) { if (angular.isUndefined($scope.regValidate[r.id])) { returnVal = false; }else{ if($scope.regValidate[r.id].length){ returnVal = false; } } }); return returnVal; }; $scope.blockInRegType = function(block, regTypeId){ return !_.contains(block.registrantTypes, regTypeId); }; $scope.anyPaymentMethodAccepted = function(){ return conference.acceptCreditCards || conference.acceptChecks || conference.acceptTransfers || conference.acceptScholarships; }; $scope.registrantDeletable = function(r){ if(registration.completed){ return false; } var groupRegistrants = 0, noGroupRegistrants = 0; angular.forEach(registration.registrants, function(r){ var regType = _.find(conference.registrantTypes, { 'id': r.registrantTypeId }); if(regType.allowGroupRegistrations){ groupRegistrants++; }else{ noGroupRegistrants++; } }); var regType = _.find(conference.registrantTypes, { 'id': r.registrantTypeId }); if(regType.allowGroupRegistrations && groupRegistrants === 1 && noGroupRegistrants){ return false; } return true; }; });
app/scripts/controllers/reviewRegistration.js
'use strict'; angular.module('confRegistrationWebApp') .controller('ReviewRegistrationCtrl', function ($scope, $rootScope, $location, $route, modalMessage, $http, registration, conference, RegistrationCache, validateRegistrant, $filter) { $rootScope.globalPage = { type: 'registration', mainClass: 'container front-form', bodyClass: 'frontend', title: conference.name, confId: conference.id, footer: false }; if(_.isEmpty(registration.registrants)) { $location.path('/' + ($rootScope.registerMode || 'register') + '/' + conference.id + '/page/'); } $scope.conference = conference; $scope.currentRegistration = registration; $scope.blocks = []; $scope.regValidate = []; //check if group registration is allowed based on registrants already in registration if(!_.isEmpty(registration.registrants)){ $scope.allowGroupRegistration = false; angular.forEach(registration.registrants, function(r){ if($scope.allowGroupRegistration){ return; } var regType = _.find(conference.registrantTypes, { 'id': r.registrantTypeId }); $scope.allowGroupRegistration = regType.allowGroupRegistrations; }); } if (angular.isUndefined($scope.currentPayment)) { var paymentType; if(conference.acceptCreditCards) { paymentType = 'CREDIT_CARD'; }else if(conference.acceptChecks){ paymentType = 'CHECK'; }else if(conference.acceptTransfers){ paymentType = 'TRANSFER'; }else if(conference.acceptScholarships){ paymentType = 'SCHOLARSHIP'; } $scope.currentPayment = { amount: $scope.currentRegistration.remainingBalance, paymentType: paymentType, creditCard: {}, transfer: {}, scholarship: {} }; } angular.forEach(_.flatten(conference.registrationPages, 'blocks'), function (block) { if (block.type.indexOf('Content') === -1) { $scope.blocks.push(block); } }); angular.forEach(registration.registrants, function (r) { $scope.regValidate[r.id] = validateRegistrant.validate(conference, r); }); $scope.findAnswer = function (blockId) { return _.find($scope.answers, {blockId: blockId}); }; $scope.getBlock = function (blockId) { return _.find($scope.blocks, {id: blockId}); }; $scope.confirmRegistration = function () { $scope.submittingRegistration = true; /*if the totalPaid (previously) AND the amount of this payment are less than the minimum required deposit, then show and error message. the first payment must be at least the minimum deposit amount. subsequent payments can be less than the amount. this is confirmed by making sure the total previously paid is above the min deposit amount. */ if ($scope.currentRegistration.totalPaid < $scope.currentRegistration.calculatedMinimumDeposit && ($scope.currentPayment.amount + $scope.currentRegistration.totalPaid) < $scope.currentRegistration.calculatedMinimumDeposit) { $scope.currentPayment.errors.push('You are required to pay at least the minimum deposit of ' + $filter('moneyFormat')(registration.calculatedMinimumDeposit) + ' to register for this event.'); } if($scope.currentPayment.amount > $scope.currentRegistration.remainingBalance) { $scope.currentPayment.errors.push('You are paying more than the total due of ' + $filter('moneyFormat')(registration.remainingBalance) + ' to register for this event.'); } if ($scope.currentPayment.amount === 0 || !$scope.anyPaymentMethodAccepted()) { setRegistrationAsCompleted(); return; } if (!_.isEmpty($scope.currentPayment.errors)) { modalMessage.error($scope.currentPayment.errors, false, 'Please correct the following errors:'); $scope.submittingRegistration = false; return; } if($scope.currentPayment.paymentType === 'CHECK'){ if(!$scope.currentRegistration.completed){ setRegistrationAsCompleted(); }else{ $scope.submittingRegistration = false; } return; } var currentPayment = angular.copy($scope.currentPayment); currentPayment.readyToProcess = true; currentPayment.registrationId = registration.id; delete currentPayment.errors; if(currentPayment.paymentType === 'CREDIT_CARD'){ $http.get('payments/ccp-client-encryption-key').success(function(ccpClientEncryptionKey) { ccp.initialize(ccpClientEncryptionKey); currentPayment.creditCard.lastFourDigits = ccp.getAbbreviatedNumber(currentPayment.creditCard.number); currentPayment.creditCard.number = ccp.encrypt(currentPayment.creditCard.number); currentPayment.creditCard.cvvNumber = ccp.encrypt(currentPayment.creditCard.cvvNumber); postPayment(currentPayment); }).error(function() { modalMessage.error('An error occurred while requesting the ccp encryption key. Please try your payment again.'); }); }else{ postPayment(currentPayment); } }; var postPayment = function(currentPayment){ $http.post('payments/', currentPayment).success(function () { delete $scope.currentPayment; if(!$scope.currentRegistration.completed) { setRegistrationAsCompleted(); } else { $route.reload(); } }).error(function () { $scope.submittingRegistration = false; modalMessage.error('Your payment was declined, please verify your details or use a different payment method.', true); }); }; var setRegistrationAsCompleted = function() { registration.completed = true; RegistrationCache.update('registrations/' + registration.id, registration, function () { RegistrationCache.emptyCache(); $route.reload(); }, function () { $scope.currentRegistration.completed = false; $scope.submittingRegistration = false; modalMessage.error('An error occurred while submitting your registration.'); }); }; $scope.editRegistrant = function (id) { $location.path('/' + ($rootScope.registerMode || 'register') + '/' + conference.id + '/page/' + conference.registrationPages[0].id).search('reg', id); }; $scope.removeRegistrant = function (id) { modalMessage.confirm('Delete registrant?', 'Are you sure you want to delete this registrant?').then(function(){ _.remove($scope.currentRegistration.registrants, function(r) { return r.id === id; }); RegistrationCache.update('registrations/' + $scope.currentRegistration.id, $scope.currentRegistration, function() { $route.reload(); }); }); }; $scope.getRegistrantType = function(id){ return _.find(conference.registrantTypes, { 'id': id }); }; $scope.isBlockInvalid = function(rId, bId){ return _.contains($scope.regValidate[rId], bId); }; $scope.allRegistrantsValid = function(){ var returnVal = true; angular.forEach(registration.registrants, function (r) { if (angular.isUndefined($scope.regValidate[r.id])) { returnVal = false; }else{ if($scope.regValidate[r.id].length){ returnVal = false; } } }); return returnVal; }; $scope.blockInRegType = function(block, regTypeId){ return !_.contains(block.registrantTypes, regTypeId); }; $scope.anyPaymentMethodAccepted = function(){ return conference.acceptCreditCards || conference.acceptChecks || conference.acceptTransfers || conference.acceptScholarships; }; $scope.registrantDeletable = function(r){ if(registration.completed){ return false; } var groupRegistrants = 0, noGroupRegistrants = 0; angular.forEach(registration.registrants, function(r){ var regType = _.find(conference.registrantTypes, { 'id': r.registrantTypeId }); if(regType.allowGroupRegistrations){ groupRegistrants++; }else{ noGroupRegistrants++; } }); var regType = _.find(conference.registrantTypes, { 'id': r.registrantTypeId }); if(regType.allowGroupRegistrations && groupRegistrants === 1 && noGroupRegistrants){ return false; } return true; }; });
Display custom error message if registration submission fails
app/scripts/controllers/reviewRegistration.js
Display custom error message if registration submission fails
<ide><path>pp/scripts/controllers/reviewRegistration.js <ide> RegistrationCache.update('registrations/' + registration.id, registration, function () { <ide> RegistrationCache.emptyCache(); <ide> $route.reload(); <del> }, function () { <add> }, function (data) { <ide> $scope.currentRegistration.completed = false; <ide> $scope.submittingRegistration = false; <del> modalMessage.error('An error occurred while submitting your registration.'); <add> modalMessage.error('An error occurred while submitting your registration. ' + (data.data.msg ? data.data.msg : '')); <ide> }); <ide> }; <ide>
Java
agpl-3.0
db97de4a4d72ef2448aac8c96dbd7dea95e91540
0
hjeeves/cadc-vosui,hjeeves/cadc-vosui,opencadc/vosui,hjeeves/cadc-vosui,canfar/vosui,opencadc/vosui,opencadc/vosui,opencadc/vosui,hjeeves/cadc-vosui,opencadc/cadc-vosui,canfar/vosui,opencadc/cadc-vosui,opencadc/cadc-vosui,opencadc/cadc-vosui
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2016. (c) 2016. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * best ide for debugging gradle projects <http://www.gnu.org/licenses/>. * * ************************************************************************ */ package ca.nrc.cadc; import org.openqa.selenium.*; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import ca.nrc.cadc.web.selenium.AbstractTestWebPage; import ca.nrc.cadc.util.StringUtil; import java.util.List; import static org.openqa.selenium.By.xpath; public class UserStorageBrowserPage extends AbstractTestWebPage { private static final String ROOT_FOLDER_NAME = "ROOT"; // Strings for matching against prompt messages and buttons private static final String DELETE_CONFIRMATION_TEXT = "Are you sure you wish to delete the selected items?"; private static final String SUCCESSFUL = "successful"; private static final String ALREADY_EXISTS = "already exists"; private static final String CONFIRMATION_MSG = "New folder added successfully"; private static final String OK = "Ok"; private static final String YES = "Yes"; private static final String CLOSE = "Close"; private static final String SAVE = "Save"; private static final By NAVBAR_ELEMENTS_BY = xpath("//*[@id=\"navbar-functions\"]/ul"); // Define in here what elements are mode indicators public static final String READ_GROUP_DIV = "readGroupDiv"; public static final String WRITE_GROUP_DIV = "writeGroupDiv"; public static final String READ_GROUP_INPUT = "readGroup"; public static final String WRITE_GROUP_INPUT = "writeGroup"; // Elements always on the page @FindBy(id = "beacon_filter") private WebElement searchFilter; @FindBy(id = "beacon") private WebElement beaconTable; // element 'Showing x to y of z entries' line @FindBy(id = "beacon_info") private WebElement statusMessage; @FindBy(className = "beacon-progress") private WebElement progressBar; // header displaying name of current folder @FindBy(xpath = "//h2[@property='name']") private WebElement folderNameHeader; @FindBy(xpath = "//*[@id=\"navbar-functions\"]/ul") private WebElement navbarButtonList; @FindBy(xpath = "//*[@id=\"beacon\"]/tbody/tr[1]") private WebElement firstTableRow; // Elements present once user has navigated away from ROOT folder // Toobar buttons @FindBy(id = "level-up") private WebElement leveUpButton; @FindBy(id = "root") private WebElement rootButton; // class has 'disabled' in it for base case. @FindBy(id = "newdropdown") private WebElement newdropdownButton; // element of the list under newdropdown @FindBy(id = "newfolder") private WebElement newFolder; @FindBy(id = "download") private WebElement downloadButton; @FindBy(id = "delete") private WebElement deleteButton; @FindBy(id = "more_details") private WebElement moredetailsButton; // Login Form elements @FindBy(id = "username") private WebElement loginUsername; @FindBy(id = "password") private WebElement loginPassword; @FindBy(id = "submitLogin") private WebElement submitLoginButton; @FindBy(id = "logout") private WebElement logoutButton; private WebDriver driver = null; public UserStorageBrowserPage(final WebDriver driver) throws Exception { super(driver); this.driver = driver; waitForStorageLoad(); PageFactory.initElements(driver, this); } // Transition functions public void clickButton(String promptText) throws Exception { WebElement button = waitUntil(ExpectedConditions.elementToBeClickable( xpath("//button[contains(text(),\"" + promptText + "\")]"))); click(button); } public void clickButtonWithClass(String promptText, String className) throws Exception { WebElement button = waitUntil(ExpectedConditions.elementToBeClickable( xpath("//button[contains(@class, '" + className + "') and contains(text(),'" + promptText + "')]"))); click(button); } public void enterSearch(final String searchString) throws Exception { sendKeys(searchFilter, searchString); waitForStorageLoad(); } public UserStorageBrowserPage doLogin(String username, String password) throws Exception { sendKeys(loginUsername, username); sendKeys(loginPassword, password); click(submitLoginButton); waitForElementPresent(By.id("logout")); return new UserStorageBrowserPage(driver); } public UserStorageBrowserPage doLogout() throws Exception { click(logoutButton); return new UserStorageBrowserPage(driver); } // Folder Related Transition functions public UserStorageBrowserPage clickFolder(String folderName) { WebElement folder = waitUntil(ExpectedConditions.elementToBeClickable( xpath("//*[@id=\"beacon\"]/tbody/tr/td/a[text()[contains(.,'" + folderName + "')]]"))); System.out.println("Folder to be clicked: " + folder.getText()); folder.click(); return new UserStorageBrowserPage(driver); } public void clickFolderForRow(int rowNum) throws Exception { WebElement firstCheckbox = waitUntil(ExpectedConditions.elementToBeClickable( xpath("//*[@id=\"beacon\"]/tbody/tr[" + rowNum + "]/td[2]/a"))); click(firstCheckbox); } public int getNextAvailabileFolderRow(int startRow) throws Exception { // not all folders are clickable, go down the rows to find one boolean found = false; int rowNum = startRow; WebElement firstCheckbox = null; while (!found) { // This method throws an exception if the element is not found try { firstCheckbox = beaconTable.findElement( xpath("//*[@id=\"beacon\"]/tbody/tr[" + rowNum + "]/td[2]/a")); } catch (Exception e) { rowNum++; continue; } found = true; } return rowNum; } // CRUD for folders public void createNewFolder(String foldername) throws Exception { newdropdownButton.click(); newFolder.click(); WebElement newfolderInput = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( By.id("fname"))); sendKeys(newfolderInput, foldername); WebElement createFolderButton = find(xpath("//button[contains(text(),\"Create Folder\")]")); createFolderButton.click(); try { confirmJqiMsg(CONFIRMATION_MSG); } catch (Exception e) { throw new Exception("Could not create folder " + foldername); } } public void deleteFolder(String foldername) throws Exception { if (!isDisabled(deleteButton)) { deleteButton.click(); } // locate folder, select checkbox, select delete button if (isJqiMsgShowing(DELETE_CONFIRMATION_TEXT)) { clickButtonWithClass(YES, "btn-danger"); } else { throw new Exception("Could not delete folder " + foldername); } // confirm folder delete if (isJqiColourMsgShowing(SUCCESSFUL)) { clickButton(CLOSE); } else { throw new Exception("Folder delete not successful: " + foldername); } } // Permissions functions public void clickEditIconForFirstRow() throws Exception { WebElement editIcon = find(xpath("//span[contains(@class, 'glyphicon-pencil')]")); editIcon.click(); } public void setGroup(String idToFind, String newGroup, boolean isPublic) throws Exception { String currentPermission = ""; clickEditIconForFirstRow(); WebElement permissionCheckbox = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( By.id("publicPermission"))); WebElement groupInput = find(By.id(idToFind)); if (isPublic == true) { if (currentPermission == null) { // toggle checkbox // read group field should clear automatically click(permissionCheckbox); } } else { currentPermission = permissionCheckbox.getAttribute("checked"); if (currentPermission != null) { // clear checkbox // read group field should be enabled click(permissionCheckbox); } sendKeys(groupInput, newGroup); } waitForAjaxFinished(); clickButton(SAVE); confirmJqiMsg(SUCCESSFUL); } /** * Convenience function to click through most of the impromptu .prompt * confirmation patterns. * * @param messageType * @throws Exception */ public void confirmJqiMsg(String messageType) throws Exception { if (isJqiMsgShowing(messageType)) { clickButton(OK); } else { throw new Exception("Could not confirm JqiMsg"); } } public void setGroupOnly(String idToFind, String newGroup, boolean confirm) throws Exception { String currentPermission = ""; WebElement permissionCheckbox = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( By.id("publicPermission"))); WebElement groupInput = find(By.id(idToFind)); currentPermission = permissionCheckbox.getAttribute("checked"); if (currentPermission != null) { // clear checkbox // read group field should be enabled click(permissionCheckbox); } sendKeys(groupInput, newGroup); clickButton(SAVE); // read/writeGroupDiv should have 'has-error' class // confirm here is conditional because it won't // show up if an invalid group has been sent in. if (confirm == true) { confirmJqiMsg(SUCCESSFUL); } } public String togglePublicAttributeForRow(int rowNum) throws Exception { String currentPermission = ""; clickEditIconForFirstRow(); WebElement permissionCheckbox = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( By.id("publicPermission"))); click(permissionCheckbox); currentPermission = permissionCheckbox.getAttribute("checked"); waitForAjaxFinished(); clickButton(SAVE); confirmJqiMsg(SUCCESSFUL); return currentPermission; } /** * Gets row number for next row that has an edit icon after the row passed in. * Using this kind of function instead of a specific row tends to leave the * functions working even when the underlying data changes. * * @param startRow * @return int: row of first edit icon * @throws Exception */ public int getNextAvailableEditIconRow(int startRow) throws Exception { // not all folders have editable data for currently logged in user boolean found = false; int rowNum = startRow; while (!found) { // This method throws an exception if the element is not found try { beaconTable.findElement( xpath("//*[@id='beacon']/tbody/tr[" + rowNum + "]/td[2]/span[contains(@class, 'glyphicon-pencil']")); } catch (Exception e) { rowNum++; continue; } found = true; } return rowNum; } // Row Checkbox related public void clickCheckboxForRow(int rowNum) throws Exception { WebElement firstCheckbox = waitUntil(ExpectedConditions.elementToBeClickable( xpath("//*[@id=\"beacon\"]/tbody/tr[" + rowNum + "]/td[1]"))); click(firstCheckbox); } public void clickCheckboxForFolder(String folderName) throws Exception { WebElement folder = find( xpath("//*[@id=\"beacon\"]/tbody/tr/td/a[contains(text()," + folderName + ")]")); WebElement folderParent = folder.findElement(xpath("..")); WebElement folderCheckbox = folderParent .findElement(xpath("//div[contains(@class=\"select-checkbox\")]")); folderCheckbox.click(); } // Navigation functions public UserStorageBrowserPage navToRoot() throws Exception { // opting for sendKeys because chromedriver // doesn't work for click() function for some reason. :( // rootButton.sendKeys(Keys.ENTER); click(By.id("root")); return new UserStorageBrowserPage(driver); } public UserStorageBrowserPage navUpLevel() throws Exception { click(leveUpButton); return new UserStorageBrowserPage(driver); } // Inspection functions public WebElement getProgressBar() throws Exception { System.out.println(progressBar.getText()); return progressBar; } int getTableRowCount() throws Exception { List<WebElement> tableRows = beaconTable.findElements(By.tagName("tr")); return tableRows.size(); } boolean verifyFolderName(int rowNum, String expectedValue) throws Exception { List<WebElement> tableRows = beaconTable.findElements(By.tagName("tr")); WebElement selectedRow = tableRows.get(rowNum); WebElement namecolumn = selectedRow .findElement(By.cssSelector("a:nth-of-type(1)")); System.out.println(namecolumn.getText()); return expectedValue.equals(namecolumn.getText()); } boolean verifyFolderSize(int rowNum) throws Exception { List<WebElement> tableRows = beaconTable.findElements(By.tagName("tr")); WebElement selectedRow = tableRows.get(rowNum); List<WebElement> columns = selectedRow.findElements(By.tagName("td")); String sizeString = columns.get(2).getText(); return sizeString != null; } public String getFolderName(int rowNum) throws Exception { List<WebElement> tableRows = beaconTable.findElements(By.tagName("tr")); WebElement selectedRow = tableRows.get(rowNum); WebElement namecolumn = selectedRow .findElement(By.cssSelector("a:nth-of-type(1)")); System.out .println("Foldername to be returned: " + namecolumn.getText()); return namecolumn.getText(); } public String getHeaderText() throws Exception { System.out.println("Header text: " + folderNameHeader.getText()); return folderNameHeader.getText(); } public String getValueForRowCol(int rowNum, int colNum) { String val; try { WebElement el = find(xpath("//*[@id='beacon']/tbody/tr[" + rowNum + "]/td[" + colNum + "]")); val = el.getText(); } catch (Exception e) { // element not found, return empty string val = ""; } return val; } boolean isLoggedIn() throws Exception { try { logoutButton.isDisplayed(); return true; } catch (NoSuchElementException e) { return false; } } private boolean isDisabled(WebElement webEl) { return webEl.getAttribute("class").contains("disabled"); } public boolean isReadAccess() { // need to check class of these buttons, look for 'disabled' in there return isDisabled(downloadButton) && isDisabled(newdropdownButton) && !isDisabled(searchFilter) && !isDisabled(leveUpButton) && !isDisabled(rootButton); } public boolean isSubFolder(String folderName) throws Exception { // Check number of elements in button bar // Check state of buttons final List<WebElement> navbarElements = navbarButtonList .findElements(By.xpath("*")); System.out.println(String.format("Navbar has %d elements.", navbarElements.size())); return getHeaderText().contains(folderName) && (navbarElements.size() == 6) && leveUpButton.isDisplayed() && deleteButton.isDisplayed() && rootButton.isDisplayed() && newdropdownButton.isDisplayed() && moredetailsButton.isDisplayed(); } public boolean isRootFolder() throws Exception { // navigation buttons are NOT displayed in root // folder. This will change as functionality is added // Currently the navbar only has one child, and it's ID is return getHeaderText().contains(ROOT_FOLDER_NAME) && navbarButtonList.findElements( xpath("//*[@id=\"navbar-functions\"]/ul")).size() == 1; } public boolean isFileSelectedMode(int rowNumber) throws Exception { // Class of selected row is different: // visually it will be different, but for now the change // in css class is enough to check //*[@id="beacon"]/tbody/tr[1] WebElement selectedRow = beaconTable.findElement( xpath("//*[@id=\"beacon\"]/tbody/tr[" + rowNumber + "]")); if (!selectedRow.getAttribute("class").contains("selected")) { return false; } // Behaviour is different if person is logged in or not if (isLoggedIn()) { if (!(isDisabled(deleteButton) && isDisabled(downloadButton))) { return true; } } else { // There will need to be a check for publicly available for download or not? if (isDisabled(deleteButton) && !isDisabled(downloadButton)) { return true; } } return false; } public boolean isDefaultSort() { // Name column asc is default sort when page loads WebElement nameColHeader = beaconTable.findElement( xpath("//*[@id=\"beacon_wrapper\"]/div[2]/div/div[1]/div[1]/div/table/thead/tr/th[2]")); return nameColHeader.getAttribute("class").equals("sorting_asc"); } // Impromptu convenience functions public boolean isJqiMsgShowing(String message) { try { waitUntil(ExpectedConditions.elementToBeClickable( xpath("//div[contains(@class, \"jqimessage\") and contains(text(), \"" + message + "\")]"))); return true; } catch (Exception e) { return false; } } public boolean isJqiColourMsgShowing(String message) { try { WebElement jqiMsg = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( xpath("//div[contains(@class, 'jqimessage')]/span[contains(text(), '" + message + "')]"))); return true; } catch (Exception e) { return false; } } public boolean isTableEmpty() { //*[@id="beacon"]/tbody/tr[6] List<WebElement> rowList = beaconTable .findElements(By.xpath("//*/tbody/tr")); if (rowList.size() > 0) { // Value is different if the entire table is empty, as compared to a list shorted to a particular value if (rowList.get(0).findElement(By.xpath("//*/td")) .getAttribute("class").equals("dataTables_empty")) { return true; } return false; } else { return true; } } /** * Verify that the given row has the values passed in * * @param readGroup * @param isPublic * @return * @throws Exception */ public boolean isPermissionDataForRow(int row, String writeGroup, String readGroup, boolean isPublic) throws Exception { // readGroup is the last column (#5) // isPublic defines what might be in that row: text should say 'Public' if isPublic is true String rowReadGroup = getValueForRowCol(row, 6); String rowWriteGroup = getValueForRowCol(row, 5); boolean isPermissionSetCorrect = false; if (isPublic) { if (rowReadGroup.equals("Public") && rowWriteGroup .equals(writeGroup)) { isPermissionSetCorrect = true; } } else if (rowReadGroup.equals(readGroup) && rowWriteGroup .equals(writeGroup)) { isPermissionSetCorrect = true; } return isPermissionSetCorrect; } public boolean isGroupError(String idToFind) throws Exception { WebElement readGroupDiv = waitUntil(ExpectedConditions.elementToBeClickable(By.id(idToFind))); return readGroupDiv.getAttribute("class").contains("has-error"); } public boolean quotaIsDisplayed() { boolean isDisplayed = false; try { WebElement quota = find(xpath("//div[contains(@class, 'quota')]")); // isDisplayed = !quota.getText().isEmpty(); isDisplayed = StringUtil.hasText(quota.getText()); } catch (Exception e) { isDisplayed = false; } return isDisplayed; } // --------- Page state wait methods public void waitForAjaxFinished() throws Exception { waitUntil(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { JavascriptExecutor js = (JavascriptExecutor) driver; return (Boolean) js.executeScript("return jQuery.active == 0"); } }); } public void waitForStorageLoad() throws Exception { // The beacon-progress bar state changes while it's loading // the page. Firefox doesn't display whole list until the bar is green // instead of striped. Could be this test isn't sufficient but it works // to have intTestFirefox not fail. waitUntil(ExpectedConditions.attributeContains( By.className("beacon-progress"), "class", "progress-bar-success")); waitForElementPresent(NAVBAR_ELEMENTS_BY); } }
src/intTest/java/ca/nrc/cadc/UserStorageBrowserPage.java
/* ************************************************************************ ******************* CANADIAN ASTRONOMY DATA CENTRE ******************* ************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES ************** * * (c) 2016. (c) 2016. * Government of Canada Gouvernement du Canada * National Research Council Conseil national de recherches * Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6 * All rights reserved Tous droits réservés * * NRC disclaims any warranties, Le CNRC dénie toute garantie * expressed, implied, or énoncée, implicite ou légale, * statutory, of any kind with de quelque nature que ce * respect to the software, soit, concernant le logiciel, * including without limitation y compris sans restriction * any warranty of merchantability toute garantie de valeur * or fitness for a particular marchande ou de pertinence * purpose. NRC shall not be pour un usage particulier. * liable in any event for any Le CNRC ne pourra en aucun cas * damages, whether direct or être tenu responsable de tout * indirect, special or general, dommage, direct ou indirect, * consequential or incidental, particulier ou général, * arising from the use of the accessoire ou fortuit, résultant * software. Neither the name de l'utilisation du logiciel. Ni * of the National Research le nom du Conseil National de * Council of Canada nor the Recherches du Canada ni les noms * names of its contributors may de ses participants ne peuvent * be used to endorse or promote être utilisés pour approuver ou * products derived from this promouvoir les produits dérivés * software without specific prior de ce logiciel sans autorisation * written permission. préalable et particulière * par écrit. * * This file is part of the Ce fichier fait partie du projet * OpenCADC project. OpenCADC. * * OpenCADC is free software: OpenCADC est un logiciel libre ; * you can redistribute it and/or vous pouvez le redistribuer ou le * modify it under the terms of modifier suivant les termes de * the GNU Affero General Public la “GNU Affero General Public * License as published by the License” telle que publiée * Free Software Foundation, par la Free Software Foundation * either version 3 of the : soit la version 3 de cette * License, or (at your option) licence, soit (à votre gré) * any later version. toute version ultérieure. * * OpenCADC is distributed in the OpenCADC est distribué * hope that it will be useful, dans l’espoir qu’il vous * but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE * without even the implied GARANTIE : sans même la garantie * warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ * or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF * PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence * General Public License for Générale Publique GNU Affero * more details. pour plus de détails. * * You should have received Vous devriez avoir reçu une * a copy of the GNU Affero copie de la Licence Générale * General Public License along Publique GNU Affero avec * with OpenCADC. If not, see OpenCADC ; si ce n’est * <http://www.gnu.org/licenses/>. pas le cas, consultez : * best ide for debugging gradle projects <http://www.gnu.org/licenses/>. * * ************************************************************************ */ package ca.nrc.cadc; import org.openqa.selenium.*; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import org.openqa.selenium.support.ui.ExpectedCondition; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import ca.nrc.cadc.web.selenium.AbstractTestWebPage; import ca.nrc.cadc.util.StringUtil; import java.util.List; import static org.openqa.selenium.By.xpath; public class UserStorageBrowserPage extends AbstractTestWebPage { private static final String ROOT_FOLDER_NAME = "ROOT"; // Strings for matching against prompt messages and buttons private static final String DELETE_CONFIRMATION_TEXT = "Are you sure you wish to delete the selected items?"; private static final String SUCCESSFUL = "successful"; private static final String ALREADY_EXISTS = "already exists"; private static final String CONFIRMATION_MSG = "New folder added successfully"; private static final String OK = "Ok"; private static final String YES = "Yes"; private static final String CLOSE = "Close"; private static final String SAVE = "Save"; private static final By NAVBAR_ELEMENTS_BY = xpath("//*[@id=\"navbar-functions\"]/ul"); // Define in here what elements are mode indicators public static final String READ_GROUP_DIV = "readGroupDiv"; public static final String WRITE_GROUP_DIV = "writeGroupDiv"; public static final String READ_GROUP_INPUT = "readGroup"; public static final String WRITE_GROUP_INPUT = "writeGroup"; // Elements always on the page @FindBy(id = "beacon_filter") private WebElement searchFilter; @FindBy(id = "beacon") private WebElement beaconTable; // element 'Showing x to y of z entries' line @FindBy(id = "beacon_info") private WebElement statusMessage; @FindBy(className = "beacon-progress") private WebElement progressBar; // header displaying name of current folder @FindBy(xpath = "//h2[@property='name']") private WebElement folderNameHeader; @FindBy(xpath = "//*[@id=\"navbar-functions\"]/ul") private WebElement navbarButtonList; @FindBy(xpath = "//*[@id=\"beacon\"]/tbody/tr[1]") private WebElement firstTableRow; // Elements present once user has navigated away from ROOT folder // Toobar buttons @FindBy(id = "level-up") private WebElement leveUpButton; @FindBy(id = "root") private WebElement rootButton; // class has 'disabled' in it for base case. @FindBy(id = "newdropdown") private WebElement newdropdownButton; // element of the list under newdropdown @FindBy(id = "newfolder") private WebElement newFolder; @FindBy(id = "download") private WebElement downloadButton; @FindBy(id = "delete") private WebElement deleteButton; @FindBy(id = "more_details") private WebElement moredetailsButton; // Login Form elements @FindBy(id = "username") private WebElement loginUsername; @FindBy(id = "password") private WebElement loginPassword; @FindBy(id = "submitLogin") private WebElement submitLoginButton; @FindBy(id = "logout") private WebElement logoutButton; private WebDriver driver = null; public UserStorageBrowserPage(final WebDriver driver) throws Exception { super(driver); this.driver = driver; waitForStorageLoad(); PageFactory.initElements(driver, this); } // Transition functions public void clickButton(String promptText) throws Exception { WebElement button = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( xpath("//button[contains(text(),\"" + promptText + "\")]"))); button.click(); } public void clickButtonWithClass(String promptText, String className) throws Exception { WebElement button = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( xpath("//button[contains(@class, '" + className + "') and contains(text(),'" + promptText + "')]"))); button.click(); } public void enterSearch(final String searchString) throws Exception { sendKeys(searchFilter, searchString); waitForStorageLoad(); } public UserStorageBrowserPage doLogin(String username, String password) throws Exception { sendKeys(loginUsername, username); sendKeys(loginPassword, password); click(submitLoginButton); waitForElementPresent(By.id("logout")); return new UserStorageBrowserPage(driver); } public UserStorageBrowserPage doLogout() throws Exception { click(logoutButton); return new UserStorageBrowserPage(driver); } // Folder Related Transition functions public UserStorageBrowserPage clickFolder(String folderName) { WebElement folder = waitUntil(ExpectedConditions.elementToBeClickable( xpath("//*[@id=\"beacon\"]/tbody/tr/td/a[text()[contains(.,'" + folderName + "')]]"))); System.out.println("Folder to be clicked: " + folder.getText()); folder.click(); return new UserStorageBrowserPage(driver); } public void clickFolderForRow(int rowNum) throws Exception { WebElement firstCheckbox = waitUntil(ExpectedConditions.elementToBeClickable( xpath("//*[@id=\"beacon\"]/tbody/tr[" + rowNum + "]/td[2]/a"))); click(firstCheckbox); } public int getNextAvailabileFolderRow(int startRow) throws Exception { // not all folders are clickable, go down the rows to find one boolean found = false; int rowNum = startRow; WebElement firstCheckbox = null; while (!found) { // This method throws an exception if the element is not found try { firstCheckbox = beaconTable.findElement( xpath("//*[@id=\"beacon\"]/tbody/tr[" + rowNum + "]/td[2]/a")); } catch (Exception e) { rowNum++; continue; } found = true; } return rowNum; } // CRUD for folders public void createNewFolder(String foldername) throws Exception { newdropdownButton.click(); newFolder.click(); WebElement newfolderInput = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( By.id("fname"))); sendKeys(newfolderInput, foldername); WebElement createFolderButton = find(xpath("//button[contains(text(),\"Create Folder\")]")); createFolderButton.click(); try { confirmJqiMsg(CONFIRMATION_MSG); } catch (Exception e) { throw new Exception("Could not create folder " + foldername); } } public void deleteFolder(String foldername) throws Exception { if (!isDisabled(deleteButton)) { deleteButton.click(); } // locate folder, select checkbox, select delete button if (isJqiMsgShowing(DELETE_CONFIRMATION_TEXT)) { clickButtonWithClass(YES, "btn-danger"); } else { throw new Exception("Could not delete folder " + foldername); } // confirm folder delete if (isJqiColourMsgShowing(SUCCESSFUL)) { clickButton(CLOSE); } else { throw new Exception("Folder delete not successful: " + foldername); } } // Permissions functions public void clickEditIconForFirstRow() throws Exception { WebElement editIcon = find(xpath("//span[contains(@class, 'glyphicon-pencil')]")); editIcon.click(); } public void setGroup(String idToFind, String newGroup, boolean isPublic) throws Exception { String currentPermission = ""; clickEditIconForFirstRow(); WebElement permissionCheckbox = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( By.id("publicPermission"))); WebElement groupInput = find(By.id(idToFind)); if (isPublic == true) { if (currentPermission == null) { // toggle checkbox // read group field should clear automatically click(permissionCheckbox); } } else { currentPermission = permissionCheckbox.getAttribute("checked"); if (currentPermission != null) { // clear checkbox // read group field should be enabled click(permissionCheckbox); } sendKeys(groupInput, newGroup); } waitForAjaxFinished(); clickButton(SAVE); confirmJqiMsg(SUCCESSFUL); } /** * Convenience function to click through most of the impromptu .prompt * confirmation patterns. * * @param messageType * @throws Exception */ public void confirmJqiMsg(String messageType) throws Exception { if (isJqiMsgShowing(messageType)) { clickButton(OK); } else { throw new Exception("Could not confirm JqiMsg"); } } public void setGroupOnly(String idToFind, String newGroup, boolean confirm) throws Exception { String currentPermission = ""; WebElement permissionCheckbox = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( By.id("publicPermission"))); WebElement groupInput = find(By.id(idToFind)); currentPermission = permissionCheckbox.getAttribute("checked"); if (currentPermission != null) { // clear checkbox // read group field should be enabled click(permissionCheckbox); } sendKeys(groupInput, newGroup); clickButton(SAVE); // read/writeGroupDiv should have 'has-error' class // confirm here is conditional because it won't // show up if an invalid group has been sent in. if (confirm == true) { confirmJqiMsg(SUCCESSFUL); } } public String togglePublicAttributeForRow(int rowNum) throws Exception { String currentPermission = ""; clickEditIconForFirstRow(); WebElement permissionCheckbox = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( By.id("publicPermission"))); click(permissionCheckbox); currentPermission = permissionCheckbox.getAttribute("checked"); waitForAjaxFinished(); clickButton(SAVE); confirmJqiMsg(SUCCESSFUL); return currentPermission; } /** * Gets row number for next row that has an edit icon after the row passed in. * Using this kind of function instead of a specific row tends to leave the * functions working even when the underlying data changes. * * @param startRow * @return int: row of first edit icon * @throws Exception */ public int getNextAvailableEditIconRow(int startRow) throws Exception { // not all folders have editable data for currently logged in user boolean found = false; int rowNum = startRow; while (!found) { // This method throws an exception if the element is not found try { beaconTable.findElement( xpath("//*[@id='beacon']/tbody/tr[" + rowNum + "]/td[2]/span[contains(@class, 'glyphicon-pencil']")); } catch (Exception e) { rowNum++; continue; } found = true; } return rowNum; } // Row Checkbox related public void clickCheckboxForRow(int rowNum) throws Exception { WebElement firstCheckbox = waitUntil(ExpectedConditions.elementToBeClickable( xpath("//*[@id=\"beacon\"]/tbody/tr[" + rowNum + "]/td[1]"))); click(firstCheckbox); } public void clickCheckboxForFolder(String folderName) throws Exception { WebElement folder = find( xpath("//*[@id=\"beacon\"]/tbody/tr/td/a[contains(text()," + folderName + ")]")); WebElement folderParent = folder.findElement(xpath("..")); WebElement folderCheckbox = folderParent .findElement(xpath("//div[contains(@class=\"select-checkbox\")]")); folderCheckbox.click(); } // Navigation functions public UserStorageBrowserPage navToRoot() throws Exception { // opting for sendKeys because chromedriver // doesn't work for click() function for some reason. :( // rootButton.sendKeys(Keys.ENTER); click(By.id("root")); return new UserStorageBrowserPage(driver); } public UserStorageBrowserPage navUpLevel() throws Exception { click(leveUpButton); return new UserStorageBrowserPage(driver); } // Inspection functions public WebElement getProgressBar() throws Exception { System.out.println(progressBar.getText()); return progressBar; } int getTableRowCount() throws Exception { List<WebElement> tableRows = beaconTable.findElements(By.tagName("tr")); return tableRows.size(); } boolean verifyFolderName(int rowNum, String expectedValue) throws Exception { List<WebElement> tableRows = beaconTable.findElements(By.tagName("tr")); WebElement selectedRow = tableRows.get(rowNum); WebElement namecolumn = selectedRow .findElement(By.cssSelector("a:nth-of-type(1)")); System.out.println(namecolumn.getText()); return expectedValue.equals(namecolumn.getText()); } boolean verifyFolderSize(int rowNum) throws Exception { List<WebElement> tableRows = beaconTable.findElements(By.tagName("tr")); WebElement selectedRow = tableRows.get(rowNum); List<WebElement> columns = selectedRow.findElements(By.tagName("td")); String sizeString = columns.get(2).getText(); return sizeString != null; } public String getFolderName(int rowNum) throws Exception { List<WebElement> tableRows = beaconTable.findElements(By.tagName("tr")); WebElement selectedRow = tableRows.get(rowNum); WebElement namecolumn = selectedRow .findElement(By.cssSelector("a:nth-of-type(1)")); System.out .println("Foldername to be returned: " + namecolumn.getText()); return namecolumn.getText(); } public String getHeaderText() throws Exception { System.out.println("Header text: " + folderNameHeader.getText()); return folderNameHeader.getText(); } public String getValueForRowCol(int rowNum, int colNum) { String val; try { WebElement el = find(xpath("//*[@id='beacon']/tbody/tr[" + rowNum + "]/td[" + colNum + "]")); val = el.getText(); } catch (Exception e) { // element not found, return empty string val = ""; } return val; } boolean isLoggedIn() throws Exception { try { logoutButton.isDisplayed(); return true; } catch (NoSuchElementException e) { return false; } } private boolean isDisabled(WebElement webEl) { return webEl.getAttribute("class").contains("disabled"); } public boolean isReadAccess() { // need to check class of these buttons, look for 'disabled' in there return isDisabled(downloadButton) && isDisabled(newdropdownButton) && !isDisabled(searchFilter) && !isDisabled(leveUpButton) && !isDisabled(rootButton); } public boolean isSubFolder(String folderName) throws Exception { // Check number of elements in button bar // Check state of buttons final List<WebElement> navbarElements = navbarButtonList .findElements(By.xpath("*")); System.out.println(String.format("Navbar has %d elements.", navbarElements.size())); return getHeaderText().contains(folderName) && (navbarElements.size() == 6) && leveUpButton.isDisplayed() && deleteButton.isDisplayed() && rootButton.isDisplayed() && newdropdownButton.isDisplayed() && moredetailsButton.isDisplayed(); } public boolean isRootFolder() throws Exception { // navigation buttons are NOT displayed in root // folder. This will change as functionality is added // Currently the navbar only has one child, and it's ID is return getHeaderText().contains(ROOT_FOLDER_NAME) && navbarButtonList.findElements( xpath("//*[@id=\"navbar-functions\"]/ul")).size() == 1; } public boolean isFileSelectedMode(int rowNumber) throws Exception { // Class of selected row is different: // visually it will be different, but for now the change // in css class is enough to check //*[@id="beacon"]/tbody/tr[1] WebElement selectedRow = beaconTable.findElement( xpath("//*[@id=\"beacon\"]/tbody/tr[" + rowNumber + "]")); if (!selectedRow.getAttribute("class").contains("selected")) { return false; } // Behaviour is different if person is logged in or not if (isLoggedIn()) { if (!(isDisabled(deleteButton) && isDisabled(downloadButton))) { return true; } } else { // There will need to be a check for publicly available for download or not? if (isDisabled(deleteButton) && !isDisabled(downloadButton)) { return true; } } return false; } public boolean isDefaultSort() { // Name column asc is default sort when page loads WebElement nameColHeader = beaconTable.findElement( xpath("//*[@id=\"beacon_wrapper\"]/div[2]/div/div[1]/div[1]/div/table/thead/tr/th[2]")); return nameColHeader.getAttribute("class").equals("sorting_asc"); } // Impromptu convenience functions public boolean isJqiMsgShowing(String message) { try { waitUntil(ExpectedConditions.elementToBeClickable( xpath("//div[contains(@class, \"jqimessage\") and contains(text(), \"" + message + "\")]"))); return true; } catch (Exception e) { return false; } } public boolean isJqiColourMsgShowing(String message) { try { WebElement jqiMsg = (new WebDriverWait(driver, 10)) .until(ExpectedConditions.elementToBeClickable( xpath("//div[contains(@class, 'jqimessage')]/span[contains(text(), '" + message + "')]"))); return true; } catch (Exception e) { return false; } } public boolean isTableEmpty() { //*[@id="beacon"]/tbody/tr[6] List<WebElement> rowList = beaconTable .findElements(By.xpath("//*/tbody/tr")); if (rowList.size() > 0) { // Value is different if the entire table is empty, as compared to a list shorted to a particular value if (rowList.get(0).findElement(By.xpath("//*/td")) .getAttribute("class").equals("dataTables_empty")) { return true; } return false; } else { return true; } } /** * Verify that the given row has the values passed in * * @param readGroup * @param isPublic * @return * @throws Exception */ public boolean isPermissionDataForRow(int row, String writeGroup, String readGroup, boolean isPublic) throws Exception { // readGroup is the last column (#5) // isPublic defines what might be in that row: text should say 'Public' if isPublic is true String rowReadGroup = getValueForRowCol(row, 6); String rowWriteGroup = getValueForRowCol(row, 5); boolean isPermissionSetCorrect = false; if (isPublic) { if (rowReadGroup.equals("Public") && rowWriteGroup .equals(writeGroup)) { isPermissionSetCorrect = true; } } else if (rowReadGroup.equals(readGroup) && rowWriteGroup .equals(writeGroup)) { isPermissionSetCorrect = true; } return isPermissionSetCorrect; } public boolean isGroupError(String idToFind) throws Exception { WebElement readGroupDiv = waitUntil(ExpectedConditions.elementToBeClickable(By.id(idToFind))); return readGroupDiv.getAttribute("class").contains("has-error"); } public boolean quotaIsDisplayed() { boolean isDisplayed = false; try { WebElement quota = find(xpath("//div[contains(@class, 'quota')]")); // isDisplayed = !quota.getText().isEmpty(); isDisplayed = StringUtil.hasText(quota.getText()); } catch (Exception e) { isDisplayed = false; } return isDisplayed; } // --------- Page state wait methods public void waitForAjaxFinished() throws Exception { waitUntil(new ExpectedCondition<Boolean>() { public Boolean apply(WebDriver driver) { JavascriptExecutor js = (JavascriptExecutor) driver; return (Boolean) js.executeScript("return jQuery.active == 0"); } }); } public void waitForStorageLoad() throws Exception { // The beacon-progress bar state changes while it's loading // the page. Firefox doesn't display whole list until the bar is green // instead of striped. Could be this test isn't sufficient but it works // to have intTestFirefox not fail. waitUntil(ExpectedConditions.attributeContains( By.className("beacon-progress"), "class", "progress-bar-success")); waitForElementPresent(NAVBAR_ELEMENTS_BY); } }
Trying to fix browser tests on Travis.
src/intTest/java/ca/nrc/cadc/UserStorageBrowserPage.java
Trying to fix browser tests on Travis.
<ide><path>rc/intTest/java/ca/nrc/cadc/UserStorageBrowserPage.java <ide> // Transition functions <ide> public void clickButton(String promptText) throws Exception <ide> { <del> WebElement button = (new WebDriverWait(driver, 10)) <del> .until(ExpectedConditions.elementToBeClickable( <del> xpath("//button[contains(text(),\"" + promptText + "\")]"))); <del> button.click(); <add> WebElement button = waitUntil(ExpectedConditions.elementToBeClickable( <add> xpath("//button[contains(text(),\"" + promptText + "\")]"))); <add> click(button); <ide> } <ide> <ide> public void clickButtonWithClass(String promptText, String className) throws <ide> Exception <ide> { <del> WebElement button = (new WebDriverWait(driver, 10)) <del> .until(ExpectedConditions.elementToBeClickable( <del> xpath("//button[contains(@class, '" + className + "') and contains(text(),'" + promptText + "')]"))); <del> button.click(); <add> WebElement button = waitUntil(ExpectedConditions.elementToBeClickable( <add> xpath("//button[contains(@class, '" + className <add> + "') and contains(text(),'" + promptText + "')]"))); <add> click(button); <ide> } <ide> <ide> public void enterSearch(final String searchString) throws Exception
JavaScript
mit
37a322a68f9287f5f1fb9da483007249e294563e
0
alcedo-ui/alcedo-ui
/** * @file List component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import isArray from 'lodash/isArray'; import classNames from 'classnames'; import ListItem from '../_ListItem'; import Tip from '../Tip'; import Theme from '../Theme'; import SelectMode from '../_statics/SelectMode'; import LIST_SEPARATOR from '../_statics/ListSeparator'; import Util from '../_vendors/Util'; import Event from '../_vendors/Event'; import Calculation from '../_vendors/Calculation'; import ComponentUtil from '../_vendors/ComponentUtil'; class List extends Component { static SelectMode = SelectMode; static LIST_SEPARATOR = LIST_SEPARATOR; static Theme = Theme; constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { value: Calculation.getInitValue(props) }; } /** * public */ adjustScroll = () => { const {data} = this.props, {value} = this.state, index = data.indexOf(value); if (index < 0) { return; } const listHeight = this.listEl.clientHeight, listScrollTop = this.listEl.scrollTop, itemEl = this.listEl.childNodes[index], itemHeight = itemEl.clientHeight, itemTop = itemEl.offsetTop; if (itemTop < listScrollTop) { this.listEl.scrollTop = itemTop; } else if (itemTop + itemHeight > listScrollTop + listHeight) { this.listEl.scrollTop = itemTop + itemHeight - listHeight; } }; listItemSelectHandler = (item, index) => { const {selectMode} = this.props, {value} = this.state, state = {}; if (selectMode === SelectMode.MULTI_SELECT) { let result = value ? value.slice() : value; if (!result || !isArray(result)) { result = []; } result.push(item); state.value = result; } else if (selectMode === SelectMode.SINGLE_SELECT) { state.value = item; } this.setState(state, () => { const {onItemSelect, onChange} = this.props; onItemSelect && onItemSelect(item, index); onChange && onChange(state.value, index); }); }; listItemDeselectHandler = (item, index) => { const {selectMode} = this.props; if (selectMode !== SelectMode.MULTI_SELECT) { return; } const {valueField, displayField} = this.props, {value: stateValue} = this.state; let value = stateValue ? stateValue.slice() : stateValue; if (!value || !isArray(value)) { value = []; } else { value = value.filter(valueItem => { return Util.getValueByValueField(valueItem, valueField, displayField) != Util.getValueByValueField(item, valueField, displayField); }); } this.setState({ value }, () => { const {onItemDeselect, onChange} = this.props; onItemDeselect && onItemDeselect(item, index); onChange && onChange(value, index); }); }; isListDisabled = listDisabled => { const {data} = this.props, {value} = this.state; return (typeof listDisabled === 'function' ? listDisabled(value, data) : listDisabled); }; isItemDisabled = (listItemDisabled, item, itemDisabled) => { const {data} = this.props, {value} = this.state; return ( listItemDisabled != undefined && (typeof listItemDisabled === 'function' ? listItemDisabled(item, value, data) : listItemDisabled) ) || ( itemDisabled != undefined && (typeof itemDisabled === 'function' ? itemDisabled(item, value, data) : itemDisabled) ); }; componentDidMount() { this.listEl = this.refs.list; } static getDerivedStateFromProps(props, state) { return { prevProps: props, value: Calculation.getInitValue({ value: ComponentUtil.getDerivedState(props, state, 'value'), selectMode: props.selectMode }) }; } renderListItem = (item, index) => { if (!item) { return; } const { theme, itemHeight, idField, valueField, displayField, descriptionField, disabled, itemDisabled, isLoading, renderer, autoSelect, disableTouchRipple, selectTheme, selectMode, indeterminateCallback, radioUncheckedIconCls, radioCheckedIconCls, checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls, onItemClick } = this.props, {value} = this.state; return typeof item === 'object' ? <ListItem key={(idField in item && item[idField]) || index} {...item} index={index} style={{height: itemHeight}} theme={item.theme || theme} selectTheme={item.selectTheme || selectTheme} radioUncheckedIconCls={item.radioUncheckedIconCls || radioUncheckedIconCls} radioCheckedIconCls={item.radioCheckedIconCls || radioCheckedIconCls} checkboxUncheckedIconCls={item.checkboxUncheckedIconCls || checkboxUncheckedIconCls} checkboxCheckedIconCls={item.checkboxCheckedIconCls || checkboxCheckedIconCls} checkboxIndeterminateIconCls={item.checkboxIndeterminateIconCls || checkboxIndeterminateIconCls} data={item} checked={Calculation.isItemChecked(item, value, this.props)} value={Util.getValueByValueField(item, valueField, displayField)} text={Util.getTextByDisplayField(item, displayField, valueField)} desc={item[descriptionField] || null} disabled={this.isListDisabled(disabled) || this.isItemDisabled(itemDisabled, item, item.disabled)} isLoading={isLoading || item.isLoading} selectMode={selectMode} renderer={renderer} autoSelect={autoSelect} disableTouchRipple={item.disableTouchRipple || disableTouchRipple} indeterminateCallback={indeterminateCallback} onClick={e => { onItemClick && onItemClick(item, index, e); item.onClick && item.onClick(e); }} onSelect={() => this.listItemSelectHandler(item, index)} onDeselect={() => this.listItemDeselectHandler(item, index)}/> : <ListItem key={index} index={index} style={{height: itemHeight}} theme={theme} selectTheme={selectTheme} radioUncheckedIconCls={radioUncheckedIconCls} radioCheckedIconCls={radioCheckedIconCls} checkboxUncheckedIconCls={checkboxUncheckedIconCls} checkboxCheckedIconCls={checkboxCheckedIconCls} checkboxIndeterminateIconCls={checkboxIndeterminateIconCls} data={item} checked={Calculation.isItemChecked(item, value, this.props)} value={item} text={item} disabled={this.isListDisabled(disabled) || this.isItemDisabled(itemDisabled, item)} isLoading={isLoading} selectMode={selectMode} renderer={renderer} autoSelect={autoSelect} disableTouchRipple={disableTouchRipple} indeterminateCallback={indeterminateCallback} onClick={e => onItemClick && onItemClick(item, index, e)} onSelect={() => this.listItemSelectHandler(item, index)} onDeselect={() => this.listItemDeselectHandler(item, index)}/>; }; render() { const {children, className, style, data, disabled} = this.props, listClassName = classNames('list', { [className]: className }); return ( <div ref="list" className={listClassName} disabled={this.isListDisabled(disabled)} style={style} onWheel={e => Event.wheelHandler(e, this.props)}> { data && data.map((item, index) => item === LIST_SEPARATOR ? <div key={index} className="list-separator"></div> : this.renderListItem(item, index) ) } {children} </div> ); } } List.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The theme of the list item. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The theme of the list item select radio or checkbox. */ selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The mode of listItem. */ selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)), /** * Children passed into the ListItem. */ data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({ /** * The CSS class name of the list button. */ className: PropTypes.string, /** * Override the styles of the list button. */ style: PropTypes.object, /** * The theme of the list button. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The text value of the list button.Type can be string or number. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The list item's display text. Type can be string, number or bool. */ text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The desc value of the list button. Type can be string or number. */ desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The title value of the list button. */ title: PropTypes.string, /** * If true, the list item will be disabled. */ disabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * If true, the button will be have loading effect. */ isLoading: PropTypes.bool, /** * If true, the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * Use this property to display an icon. It will display on the left. */ iconCls: PropTypes.string, /** * Use this property to display an icon. It will display on the right. */ rightIconCls: PropTypes.string, /** * The message of tip. */ tip: PropTypes.string, /** * The position of tip. */ tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)), /** * If true, the item will have center displayed ripple effect. */ rippleDisplayCenter: PropTypes.bool, /** * You can create a complicated renderer callback instead of value and desc prop. */ itemRenderer: PropTypes.func, /** * Callback function fired when a list item touch-tapped. */ onClick: PropTypes.func }), PropTypes.string, PropTypes.number, PropTypes.symbol])), value: PropTypes.any, /** * The id field name in data. (default: "id") */ idField: PropTypes.string, /** * The value field name in data. (default: "value") */ valueField: PropTypes.string, /** * The display field name in data. (default: "text") */ displayField: PropTypes.string, /** * The description field name in data. (default: "desc") */ descriptionField: PropTypes.string, /** * If true, the list will be disabled. */ disabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * List item disabled callback. */ itemDisabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * If true,the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * If true, the list will be at loading status. */ isLoading: PropTypes.bool, /** * Whether select when item clicked. */ autoSelect: PropTypes.bool, indeterminateCallback: PropTypes.func, shouldPreventContainerScroll: PropTypes.bool, radioUncheckedIconCls: PropTypes.string, radioCheckedIconCls: PropTypes.string, checkboxUncheckedIconCls: PropTypes.string, checkboxCheckedIconCls: PropTypes.string, checkboxIndeterminateIconCls: PropTypes.string, /** * You can create a complicated renderer callback instead of value and desc prop. */ renderer: PropTypes.func, /** * Callback function fired when the list-item touch tap. */ onItemClick: PropTypes.func, /** * Callback function fired when the list-item select. */ onItemSelect: PropTypes.func, /** * Callback function fired when the list-item deselect. */ onItemDeselect: PropTypes.func, /** * Callback function fired when the list changed. */ onChange: PropTypes.func, /** * Callback function fired when wrapper wheeled. */ onWheel: PropTypes.func }; List.defaultProps = { theme: Theme.DEFAULT, selectTheme: Theme.DEFAULT, selectMode: SelectMode.SINGLE_SELECT, idField: 'id', valueField: 'value', displayField: 'text', descriptionField: 'desc', disabled: false, itemDisabled: false, disableTouchRipple: false, autoSelect: true, shouldPreventContainerScroll: true, checkboxUncheckedIconCls: 'far fa-square', checkboxCheckedIconCls: 'fas fa-check-square', checkboxIndeterminateIconCls: 'fas fa-minus-square' }; export default List;
src/List/List.js
/** * @file List component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import isArray from 'lodash/isArray'; import classNames from 'classnames'; import ListItem from '../_ListItem'; import Tip from '../Tip'; import Theme from '../Theme'; import SelectMode from '../_statics/SelectMode'; import LIST_SEPARATOR from '../_statics/ListSeparator'; import Util from '../_vendors/Util'; import Event from '../_vendors/Event'; import Calculation from '../_vendors/Calculation'; class List extends Component { static SelectMode = SelectMode; static LIST_SEPARATOR = LIST_SEPARATOR; static Theme = Theme; constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { value: Calculation.getInitValue(props) }; } /** * public */ adjustScroll = () => { const {data} = this.props, {value} = this.state, index = data.indexOf(value); if (index < 0) { return; } const listHeight = this.listEl.clientHeight, listScrollTop = this.listEl.scrollTop, itemEl = this.listEl.childNodes[index], itemHeight = itemEl.clientHeight, itemTop = itemEl.offsetTop; if (itemTop < listScrollTop) { this.listEl.scrollTop = itemTop; } else if (itemTop + itemHeight > listScrollTop + listHeight) { this.listEl.scrollTop = itemTop + itemHeight - listHeight; } }; listItemSelectHandler = (item, index) => { const {selectMode} = this.props, {value} = this.state, state = {}; if (selectMode === SelectMode.MULTI_SELECT) { let result = value ? value.slice() : value; if (!result || !isArray(result)) { result = []; } result.push(item); state.value = result; } else if (selectMode === SelectMode.SINGLE_SELECT) { state.value = item; } this.setState(state, () => { const {onItemSelect, onChange} = this.props; onItemSelect && onItemSelect(item, index); onChange && onChange(state.value, index); }); }; listItemDeselectHandler = (item, index) => { const {selectMode} = this.props; if (selectMode !== SelectMode.MULTI_SELECT) { return; } const {valueField, displayField} = this.props, {value: stateValue} = this.state; let value = stateValue ? stateValue.slice() : stateValue; if (!value || !isArray(value)) { value = []; } else { value = value.filter(valueItem => { return Util.getValueByValueField(valueItem, valueField, displayField) != Util.getValueByValueField(item, valueField, displayField); }); } this.setState({ value }, () => { const {onItemDeselect, onChange} = this.props; onItemDeselect && onItemDeselect(item, index); onChange && onChange(value, index); }); }; isListDisabled = listDisabled => { const {data} = this.props, {value} = this.state; return (typeof listDisabled === 'function' ? listDisabled(value, data) : listDisabled); }; isItemDisabled = (listItemDisabled, item, itemDisabled) => { const {data} = this.props, {value} = this.state; return ( listItemDisabled != undefined && (typeof listItemDisabled === 'function' ? listItemDisabled(item, value, data) : listItemDisabled) ) || ( itemDisabled != undefined && (typeof itemDisabled === 'function' ? itemDisabled(item, value, data) : itemDisabled) ); }; componentDidMount() { this.listEl = this.refs.list; } componentWillReceiveProps(nextProps) { if (nextProps.value !== this.state.value) { this.setState({ value: Calculation.getInitValue(nextProps) }); } } renderListItem = (item, index) => { if (!item) { return; } const { theme, itemHeight, idField, valueField, displayField, descriptionField, disabled, itemDisabled, isLoading, renderer, autoSelect, disableTouchRipple, selectTheme, selectMode, indeterminateCallback, radioUncheckedIconCls, radioCheckedIconCls, checkboxUncheckedIconCls, checkboxCheckedIconCls, checkboxIndeterminateIconCls, onItemClick } = this.props, {value} = this.state; return typeof item === 'object' ? <ListItem key={(idField in item && item[idField]) || index} {...item} index={index} style={{height: itemHeight}} theme={item.theme || theme} selectTheme={item.selectTheme || selectTheme} radioUncheckedIconCls={item.radioUncheckedIconCls || radioUncheckedIconCls} radioCheckedIconCls={item.radioCheckedIconCls || radioCheckedIconCls} checkboxUncheckedIconCls={item.checkboxUncheckedIconCls || checkboxUncheckedIconCls} checkboxCheckedIconCls={item.checkboxCheckedIconCls || checkboxCheckedIconCls} checkboxIndeterminateIconCls={item.checkboxIndeterminateIconCls || checkboxIndeterminateIconCls} data={item} checked={Calculation.isItemChecked(item, value, this.props)} value={Util.getValueByValueField(item, valueField, displayField)} text={Util.getTextByDisplayField(item, displayField, valueField)} desc={item[descriptionField] || null} disabled={this.isListDisabled(disabled) || this.isItemDisabled(itemDisabled, item, item.disabled)} isLoading={isLoading || item.isLoading} selectMode={selectMode} renderer={renderer} autoSelect={autoSelect} disableTouchRipple={item.disableTouchRipple || disableTouchRipple} indeterminateCallback={indeterminateCallback} onClick={e => { onItemClick && onItemClick(item, index, e); item.onClick && item.onClick(e); }} onSelect={() => this.listItemSelectHandler(item, index)} onDeselect={() => this.listItemDeselectHandler(item, index)}/> : <ListItem key={index} index={index} style={{height: itemHeight}} theme={theme} selectTheme={selectTheme} radioUncheckedIconCls={radioUncheckedIconCls} radioCheckedIconCls={radioCheckedIconCls} checkboxUncheckedIconCls={checkboxUncheckedIconCls} checkboxCheckedIconCls={checkboxCheckedIconCls} checkboxIndeterminateIconCls={checkboxIndeterminateIconCls} data={item} checked={Calculation.isItemChecked(item, value, this.props)} value={item} text={item} disabled={this.isListDisabled(disabled) || this.isItemDisabled(itemDisabled, item)} isLoading={isLoading} selectMode={selectMode} renderer={renderer} autoSelect={autoSelect} disableTouchRipple={disableTouchRipple} indeterminateCallback={indeterminateCallback} onClick={e => onItemClick && onItemClick(item, index, e)} onSelect={() => this.listItemSelectHandler(item, index)} onDeselect={() => this.listItemDeselectHandler(item, index)}/>; }; render() { const {children, className, style, data, disabled} = this.props, listClassName = classNames('list', { [className]: className }); return ( <div ref="list" className={listClassName} disabled={this.isListDisabled(disabled)} style={style} onWheel={e => Event.wheelHandler(e, this.props)}> { data && data.map((item, index) => item === LIST_SEPARATOR ? <div key={index} className="list-separator"></div> : this.renderListItem(item, index) ) } {children} </div> ); } } List.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * The theme of the list item. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The theme of the list item select radio or checkbox. */ selectTheme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The mode of listItem. */ selectMode: PropTypes.oneOf(Util.enumerateValue(SelectMode)), /** * Children passed into the ListItem. */ data: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.shape({ /** * The CSS class name of the list button. */ className: PropTypes.string, /** * Override the styles of the list button. */ style: PropTypes.object, /** * The theme of the list button. */ theme: PropTypes.oneOf(Util.enumerateValue(Theme)), /** * The text value of the list button.Type can be string or number. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The list item's display text. Type can be string, number or bool. */ text: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The desc value of the list button. Type can be string or number. */ desc: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The title value of the list button. */ title: PropTypes.string, /** * If true, the list item will be disabled. */ disabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * If true, the button will be have loading effect. */ isLoading: PropTypes.bool, /** * If true, the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * Use this property to display an icon. It will display on the left. */ iconCls: PropTypes.string, /** * Use this property to display an icon. It will display on the right. */ rightIconCls: PropTypes.string, /** * The message of tip. */ tip: PropTypes.string, /** * The position of tip. */ tipPosition: PropTypes.oneOf(Util.enumerateValue(Tip.Position)), /** * If true, the item will have center displayed ripple effect. */ rippleDisplayCenter: PropTypes.bool, /** * You can create a complicated renderer callback instead of value and desc prop. */ itemRenderer: PropTypes.func, /** * Callback function fired when a list item touch-tapped. */ onClick: PropTypes.func }), PropTypes.string, PropTypes.number, PropTypes.symbol])), value: PropTypes.any, /** * The id field name in data. (default: "id") */ idField: PropTypes.string, /** * The value field name in data. (default: "value") */ valueField: PropTypes.string, /** * The display field name in data. (default: "text") */ displayField: PropTypes.string, /** * The description field name in data. (default: "desc") */ descriptionField: PropTypes.string, /** * If true, the list will be disabled. */ disabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * List item disabled callback. */ itemDisabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]), /** * If true,the element's ripple effect will be disabled. */ disableTouchRipple: PropTypes.bool, /** * If true, the list will be at loading status. */ isLoading: PropTypes.bool, /** * Whether select when item clicked. */ autoSelect: PropTypes.bool, indeterminateCallback: PropTypes.func, shouldPreventContainerScroll: PropTypes.bool, radioUncheckedIconCls: PropTypes.string, radioCheckedIconCls: PropTypes.string, checkboxUncheckedIconCls: PropTypes.string, checkboxCheckedIconCls: PropTypes.string, checkboxIndeterminateIconCls: PropTypes.string, /** * You can create a complicated renderer callback instead of value and desc prop. */ renderer: PropTypes.func, /** * Callback function fired when the list-item touch tap. */ onItemClick: PropTypes.func, /** * Callback function fired when the list-item select. */ onItemSelect: PropTypes.func, /** * Callback function fired when the list-item deselect. */ onItemDeselect: PropTypes.func, /** * Callback function fired when the list changed. */ onChange: PropTypes.func, /** * Callback function fired when wrapper wheeled. */ onWheel: PropTypes.func }; List.defaultProps = { theme: Theme.DEFAULT, selectTheme: Theme.DEFAULT, selectMode: SelectMode.SINGLE_SELECT, idField: 'id', valueField: 'value', displayField: 'text', descriptionField: 'desc', disabled: false, itemDisabled: false, disableTouchRipple: false, autoSelect: true, shouldPreventContainerScroll: true, checkboxUncheckedIconCls: 'far fa-square', checkboxCheckedIconCls: 'fas fa-check-square', checkboxIndeterminateIconCls: 'fas fa-minus-square' }; export default List;
update List
src/List/List.js
update List
<ide><path>rc/List/List.js <ide> import Util from '../_vendors/Util'; <ide> import Event from '../_vendors/Event'; <ide> import Calculation from '../_vendors/Calculation'; <add>import ComponentUtil from '../_vendors/ComponentUtil'; <ide> <ide> class List extends Component { <ide> <ide> this.listEl = this.refs.list; <ide> } <ide> <del> componentWillReceiveProps(nextProps) { <del> if (nextProps.value !== this.state.value) { <del> this.setState({ <del> value: Calculation.getInitValue(nextProps) <del> }); <del> } <add> static getDerivedStateFromProps(props, state) { <add> return { <add> prevProps: props, <add> value: Calculation.getInitValue({ <add> value: ComponentUtil.getDerivedState(props, state, 'value'), <add> selectMode: props.selectMode <add> }) <add> }; <ide> } <ide> <ide> renderListItem = (item, index) => {
Java
bsd-2-clause
9d72f30c6e14029e3c0408682fb49af6c4baf55d
0
samynk/DArtE
package dae.gui; import com.google.common.eventbus.Subscribe; import com.jme3.app.SimpleApplication; import com.jme3.asset.DesktopAssetManager; import com.jme3.asset.ModelKey; import com.jme3.asset.plugins.FileLocator; import com.jme3.bounding.BoundingBox; import com.jme3.bounding.BoundingVolume; import com.jme3.bounding.BoundingVolume.Type; import com.jme3.bullet.BulletAppState; import com.jme3.bullet.PhysicsSpace; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.cursors.plugins.JmeCursor; import com.jme3.input.FlyByCamera; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.RawInputListener; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.AnalogListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseAxisTrigger; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.input.event.JoyAxisEvent; import com.jme3.input.event.JoyButtonEvent; import com.jme3.input.event.KeyInputEvent; import com.jme3.input.event.MouseButtonEvent; import com.jme3.input.event.MouseMotionEvent; import com.jme3.input.event.TouchEvent; import com.jme3.light.AmbientLight; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Matrix4f; import com.jme3.math.Quaternion; import com.jme3.math.Ray; import com.jme3.math.Transform; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.debug.WireBox; import com.jme3.shadow.AbstractShadowRenderer; import dae.DAECamAppState; import dae.GlobalObjects; import dae.animation.rig.Rig; import dae.animation.rig.io.RigLoader; import dae.animation.rig.timing.Behaviour; import dae.animation.rig.timing.TimeLine; import dae.components.ComponentType; import dae.components.MeshComponent; import dae.components.PrefabComponent; import dae.controller.ControllerLoader; import dae.gui.tools.BrushTool; import dae.gui.tools.IdleTool; import dae.gui.tools.InsertionTool; import dae.gui.tools.LinkTool; import dae.gui.tools.PickTool; import dae.gui.tools.RotateTool; import dae.gui.tools.TranslateTool; import dae.gui.tools.ViewportTool; import dae.io.AnimationReader; import dae.io.ComponentReader; import dae.io.ObjectTypeReader; import dae.io.SceneLoader; import dae.io.game.GameBuilder; import dae.io.game.GameWriter; import dae.io.readers.OVMReader; import dae.prefabs.AxisEnum; import dae.prefabs.Klatch; import dae.prefabs.Prefab; import dae.prefabs.gizmos.Axis; import dae.prefabs.gizmos.RotateGizmo; import dae.prefabs.gizmos.events.AutoGridEvent; import dae.prefabs.parameters.Parameter; import dae.prefabs.prefab.undo.AddPrefabEdit; import dae.prefabs.prefab.undo.DeletePrefabEdit; import dae.prefabs.standard.CameraFrame; import dae.prefabs.standard.MeshObject; import dae.prefabs.types.ObjectType; import dae.prefabs.types.ObjectTypeCategory; import dae.prefabs.ui.classpath.FileNode; import dae.prefabs.ui.events.AnimationEvent; import dae.prefabs.ui.events.AnimationEventType; import dae.prefabs.ui.events.AssetEvent; import dae.prefabs.ui.events.AssetEventType; import dae.prefabs.ui.events.ComponentEvent; import dae.prefabs.ui.events.CreateObjectEvent; import dae.prefabs.ui.events.CutCopyPasteEvent; import dae.prefabs.ui.events.GizmoEvent; import dae.prefabs.ui.events.GizmoType; import static dae.prefabs.ui.events.GizmoType.ROTATE; import static dae.prefabs.ui.events.GizmoType.TRANSLATE; import dae.prefabs.ui.events.InsertObjectEvent; import dae.prefabs.ui.events.LevelEvent; import dae.prefabs.ui.events.LevelEvent.EventType; import dae.prefabs.ui.events.PlayEvent; import dae.prefabs.ui.events.ProjectEvent; import dae.prefabs.ui.events.SelectionEvent; import dae.prefabs.ui.events.ShadowEvent; import dae.prefabs.ui.events.ViewportReshapeEvent; import dae.prefabs.ui.events.ZoomEvent; import dae.project.AssetLevel; import dae.project.Layer; import dae.project.Project; import dae.project.ProjectTreeNode; import dae.util.MathUtil; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; /** * * @author Koen Samyn */ public class SandboxViewport extends SimpleApplication implements RawInputListener { /** * The available object types. */ private ObjectTypeCategory objectsToCreate; /** * The default layer for all elements that are added to the scene. */ private Node sceneElements = new Node("scene"); /** * The elements to insert. */ private Node insertionElements = new Node("insertion"); private Prefab insertionElement; /** * The current gizmo type */ private GizmoType gizmoType = GizmoType.NONE; private GizmoType newGizmoType = GizmoType.NONE; /** * The editor state. */ private enum EditorState { IDLE, INSERTIONEVENT, ADDTOSCENE, LEVELCHANGED, SELECTION }; /** * The current editor state. */ private EditorState editorState = EditorState.IDLE; /** * Shift key is used for copying of items */ private boolean shiftIsDown = false; private ArrayList<Node> currentSelection = new ArrayList<>(); private CreateObjectEvent objectCreationEvent; /** * The current level. */ private dae.project.Level level; /** * The current project. */ private Project project; /** * Code that has to be executed on the JMonkey thread. */ private final ArrayList<Runnable> viewportTasks = new ArrayList<>(); /** * Selection from other thread (such as user interface). */ private final ArrayList<Node> selectionFromOutside = new ArrayList<>(); /** * Copy and cut buffer */ private final ArrayList<Node> copyBuffer = new ArrayList<>(); /** * shows the selected object. */ private final WireBox wireBox = new WireBox(); private Geometry wireBoxGeometry; private Material wireBoxMaterial; /** * Cursor */ private JmeCursor cursorConnect1; private JmeCursor cursorConnect2; private JmeCursor cursorSelect; private JmeCursor cursorMove; private JmeCursor cursorRotate; private JmeCursor cursorScale; /** * Tool support */ private IdleTool idleTool; private ViewportTool currentTool; private TranslateTool translateTool; private RotateTool rotateTool; private BrushTool brushTool; private PickTool pickTool; private LinkTool linkTool; private InsertionTool insertionTool; /** * Autogrid functionality */ private boolean autoGridEnabled = false; private AxisEnum autoGridAxis = AxisEnum.Y; public SandboxViewport() { super(new DAECamAppState()); } @Override public void simpleInitApp() { assetManager.registerLoader(ObjectTypeReader.class, "types"); assetManager.registerLoader(ControllerLoader.class, "fcl"); assetManager.registerLoader(SceneLoader.class, "klatch"); assetManager.registerLoader(RigLoader.class, "rig"); assetManager.registerLoader(AnimationReader.class, "animset"); assetManager.registerLoader(ComponentReader.class, "components"); assetManager.registerLoader(OVMReader.class, "ovm"); objectsToCreate = (ObjectTypeCategory) assetManager.loadAsset("Objects/ObjectTypes.types"); GlobalObjects.getInstance().setObjectTypeCategory(objectsToCreate); GlobalObjects.getInstance().registerListener(this); setPauseOnLostFocus(false); translateTool = new TranslateTool(); translateTool.initialize(assetManager, inputManager); rotateTool = new RotateTool(); rotateTool.initialize(assetManager, inputManager); brushTool = new BrushTool(); brushTool.initialize(assetManager, inputManager); pickTool = new PickTool(); pickTool.initialize(assetManager, inputManager); linkTool = new LinkTool(); linkTool.initialize(assetManager, inputManager); idleTool = new IdleTool(); idleTool.initialize(assetManager, inputManager); insertionTool = new InsertionTool(); insertionTool.initialize(assetManager, inputManager); currentTool = idleTool; rootNode.attachChild(sceneElements); rootNode.attachChild(insertionElements); AmbientLight al = new AmbientLight(); al.setColor(ColorRGBA.White.mult(0.25f)); rootNode.addLight(al); AmbientLight insertionLight = new AmbientLight(); insertionLight.setColor(ColorRGBA.White.mult(5.0f)); insertionElements.addLight(insertionLight); cam.setFrustumPerspective(45f, (float) cam.getWidth() / cam.getHeight(), 0.01f, 1000f); cam.setLocation(new Vector3f(5, 2, 0)); cam.lookAt(new Vector3f(0, 0, 0), new Vector3f(0, 1, 0)); initKeys(); // cursorConnect1 = (JmeCursor) assetManager.loadAsset("Interface/connect1.ico"); // cursorConnect2 = (JmeCursor) assetManager.loadAsset("Interface/connect2.ico"); // cursorMove = (JmeCursor) assetManager.loadAsset("Interface/move.ico"); // cursorSelect = (JmeCursor) assetManager.loadAsset("Interface/select.ico"); // cursorRotate = (JmeCursor)assetManager.loadAsset("Interface/rotate.ico"); // cursorScale = (JmeCursor)assetManager.loadAsset("Interface/scale.ico"); BulletAppState bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); bulletAppState.setBroadphaseType(PhysicsSpace.BroadphaseType.AXIS_SWEEP_3_32); PhysicsSpace.getPhysicsSpace().setGravity(new Vector3f(0, -9.81f, 0)); GlobalObjects.getInstance().setAssetManager(assetManager); GlobalObjects.getInstance().setInputManager(this.inputManager); wireBoxMaterial = assetManager.loadMaterial("Materials/SelectionBoxMaterial.j3m"); wireBoxGeometry = new Geometry("wireframe cube", wireBox); wireBoxGeometry.setMaterial(wireBoxMaterial); rootNode.attachChild(wireBoxGeometry); } /** * Attaches a guid element to the viewport. * * @param s the spatial to attach to the viewport. */ public void attachGuiElement(Spatial s) { guiNode.attachChild(s); } public Node getSceneElements() { return this.sceneElements; } public dae.project.Level getLevel() { return this.level; } public Iterable<Node> getSelection() { return this.currentSelection; } public boolean isAutoGridEnabled() { return autoGridEnabled; } public AxisEnum getAutoGridAxis() { return this.autoGridAxis; } public void disableFlyCam() { flyCam.setEnabled(false); } public void enableFlyCam() { flyCam.setEnabled(true); } public void adaptSelectionBox() { BoundingVolume bv = null; for (Node n : this.currentSelection) { if (n == null) { continue; } if (bv == null) { bv = n.getWorldBound(); } else { bv.merge(n.getWorldBound()); } } if (bv != null && bv.getType() == Type.AABB) { BoundingBox bb = (BoundingBox) bv; if (wireBoxGeometry != null) { wireBoxGeometry.removeFromParent(); } wireBoxGeometry = WireBox.makeGeometry(bb); wireBoxGeometry.setLocalTranslation(bb.getCenter()); wireBoxGeometry.setMaterial(wireBoxMaterial); if (wireBoxGeometry.getParent() == null) { this.rootNode.attachChild(wireBoxGeometry); } } else if (wireBoxGeometry != null) { wireBoxGeometry.removeFromParent(); } } @Override public void reshape(int w, int h) { super.reshape(w, h); GlobalObjects.getInstance().postEvent(new ViewportReshapeEvent(w, h)); } /** * Initialize the inputs. */ private void initKeys() { inputManager.setCursorVisible(true); // You can map one or several inputs to one named action inputManager.addMapping("ACCEPT_INSERTION", new KeyTrigger(KeyInput.KEY_RETURN)); inputManager.addMapping("ACCEPT_INSERTION", new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); inputManager.addMapping("REJECT_INSERTION", new KeyTrigger(KeyInput.KEY_ESCAPE)); inputManager.addMapping("DELETE_SELECTION", new KeyTrigger(KeyInput.KEY_DELETE)); inputManager.addMapping("CHANGE_PIVOT", new KeyTrigger(KeyInput.KEY_C)); inputManager.addMapping("COPY_LASTOBJECT", new KeyTrigger(KeyInput.KEY_F1)); inputManager.addMapping("CREATE_ANIMATION_KEY", new KeyTrigger(KeyInput.KEY_F11)); inputManager.addMapping("DELETE_ANIMATION_KEY", new KeyTrigger(KeyInput.KEY_F12)); inputManager.addMapping("DOBRUSH", new KeyTrigger(KeyInput.KEY_LSHIFT), new KeyTrigger(KeyInput.KEY_RSHIFT)); inputManager.addMapping("UNDO", new KeyTrigger(KeyInput.KEY_U)); inputManager.addMapping("REDO", new KeyTrigger(KeyInput.KEY_R)); inputManager.addMapping("ROTATION_UP", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false)); inputManager.addMapping("ROTATION_DOWN", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)); inputManager.addListener(analogListener, new String[]{"ACCEPT_INSERTION", "SELECT_OBJECT", "REJECT_INSERTION", "DELETE_SELECTION", "ROTATION_UP", "ROTATION_DOWN"}); inputManager.addListener(actionListener, new String[]{"CHANGE_PIVOT", "COPY_LASTOBJECT"}); inputManager.addListener(undoRedoListener, new String[]{"UNDO", "REDO"}); inputManager.addListener(animationListener, new String[]{"CREATE_ANIMATION_KEY", "DELETE_ANIMATION_KEY"}); inputManager.addRawInputListener(this); } private final ActionListener animationListener = new ActionListener() { @Override public void onAction(String name, boolean isPressed, float tpf) { if (!isPressed) { if (name.startsWith("CREATE")) { if (level instanceof AssetLevel) { // search the rig. List<Rig> rigs = level.descendantMatches(Rig.class); if (rigs.size() > 0) { Rig r = rigs.get(0); for (Node n : getSelection()) { Behaviour current = r.getCurrentBehaviour(); if (current != null) { TimeLine tl = current.getTimeLine(n); tl.addRotation(current.getCurrentFrame(), n.getLocalRotation()); } } GlobalObjects.getInstance().postEvent(new AnimationEvent(r, AnimationEventType.CREATE)); } } } else if (name.startsWith("DELETE")) { System.out.println("deleting the animation key"); if (level instanceof AssetLevel){ List<Rig> rigs = level.descendantMatches(Rig.class); if (rigs.size() > 0) { Rig r = rigs.get(0); for (Node n : getSelection()) { Behaviour current = r.getCurrentBehaviour(); if (current != null) { TimeLine tl = current.getTimeLine(n); tl.removeRotation(current.getCurrentFrame()); } } GlobalObjects.getInstance().postEvent(new AnimationEvent(r, AnimationEventType.CREATE)); } } } } } }; private final ActionListener undoRedoListener = new ActionListener() { @Override public void onAction(String name, boolean keyPressed, float tpf) { if (name.equals("UNDO") && !keyPressed) { try { GlobalObjects.getInstance().undo(); } catch (CannotUndoException ex) { Logger.getLogger("DArtE").log(Level.WARNING, "Cannot undo.", ex); } } else if (name.equals("REDO") && !keyPressed) { try { GlobalObjects.getInstance().redo(); } catch (CannotRedoException ex) { Logger.getLogger("DArtE").log(Level.WARNING, "Cannot redo.", ex); } } } }; private ActionListener actionListener = new ActionListener() { @Override public void onAction(String name, boolean keyPressed, float tpf) { if (name.equals("CHANGE_PIVOT") && !keyPressed) { for (Spatial s : insertionElements.getChildren()) { if (s instanceof Prefab) { ((Prefab) s).cyclePivot(); } } } else if (name.equals("COPY_LASTOBJECT") && !keyPressed) { if (objectCreationEvent != null) { insertionElements.detachAllChildren(); editorState = EditorState.INSERTIONEVENT; } } } }; private final AnalogListener analogListener = new AnalogListener() { @Override public void onAnalog(String name, float value, float tpf) { if (editorState == EditorState.IDLE) { if ("DELETE_SELECTION".equals(name)) { for (Node n : currentSelection) { removeNode(level, n); } clearSelection(); } } } }; /** * Return the objects to create. * * @return the objects to create. */ public ObjectTypeCategory getObjectsToCreate() { return this.objectsToCreate; } /** * */ @Override public void beginInput() { } @Override public void endInput() { } @Override public void onJoyAxisEvent(JoyAxisEvent evt) { } @Override public void onJoyButtonEvent(JoyButtonEvent evt) { } @Override public void onMouseMotionEvent(MouseMotionEvent evt) { currentTool.onMouseMotionEvent(evt, this); } @Override public void onMouseButtonEvent(MouseButtonEvent evt) { if (evt.isReleased()) { currentTool.onMouseButtonReleased(this); } else if (evt.isPressed()) { currentTool.onMouseButtonPressed(this); } } public void addToScene() { clearSelection(); for (Spatial p : insertionElements.getChildren()) { addToSelection((Node) p); sceneElements.attachChild(p); if (p instanceof Prefab) { Prefab prefab = (Prefab) p; //prefab.connect(sceneElements); BulletAppState bas = this.stateManager.getState(BulletAppState.class); prefab.addPhysics(bas.getPhysicsSpace()); } AddPrefabEdit edit = new AddPrefabEdit((Node) p); GlobalObjects.getInstance().addEdit(edit); LevelEvent le = new LevelEvent(this.level, LevelEvent.EventType.NODEADDED, (Node) p); GlobalObjects.getInstance().postEvent(le); } insertionElements.detachAllChildren(); editorState = EditorState.IDLE; } @Override public void onKeyEvent(KeyInputEvent evt) { int kc = evt.getKeyCode(); if (evt.isPressed()) { //controlIsDown = (kc == KeyInput.KEY_LCONTROL || kc == KeyInput.KEY_RCONTROL); shiftIsDown = (kc == KeyInput.KEY_LSHIFT || kc == KeyInput.KEY_RSHIFT); } else { switch (kc) { case KeyInput.KEY_LSHIFT: case KeyInput.KEY_RSHIFT: shiftIsDown = false; break; // case KeyInput.KEY_LCONTROL: // case KeyInput.KEY_RCONTROL: // controlIsDown = false; // break; } } } @Override public void onTouchEvent(TouchEvent evt) { } /** * Clears everything from the scene. */ public void clearScene() { this.insertionElements.detachAllChildren(); this.sceneElements.detachAllChildren(); } @Override public void simpleUpdate(float tpf) { if (this.selectionFromOutside.size() > 0) { clearSelection(); for (Node n : selectionFromOutside) { this.addToSelection(n); } selectionFromOutside.clear(); editorState = EditorState.IDLE; activateIdleState(this); } if (editorState == EditorState.INSERTIONEVENT) { ObjectType objectTypeToCreate = objectCreationEvent.getObjectType(); String name = createName(this.sceneElements, objectTypeToCreate.getLabel()); Prefab p = objectTypeToCreate.create(assetManager, name); if (objectCreationEvent.hasComponents()) { for (PrefabComponent pc : objectCreationEvent.getComponents()) { p.removeComponents(pc.getId()); p.addPrefabComponent(pc); } } if (p != null) { BulletAppState state = stateManager.getState(BulletAppState.class); state.getPhysicsSpace().addAll(p); insertionElement = p; this.insertionElements.attachChild(insertionElement); this.clearSelection(); this.addToSelection(p); activateInsertionTool(objectCreationEvent); } editorState = EditorState.IDLE; } if (editorState == EditorState.ADDTOSCENE) { addToScene(); } if (editorState == EditorState.LEVELCHANGED) { if (this.level != null) { viewPort.clearProcessors(); BulletAppState bas = this.getStateManager().getState(BulletAppState.class); if (this.sceneElements != null) { sceneElements.removeFromParent(); bas.getPhysicsSpace().removeAll(sceneElements); } clearSelection(); rootNode.attachChild(level); this.sceneElements = level; this.level.levelShown(this.assetManager, bas); editorState = EditorState.IDLE; level.updateGeometricState(); bas.getPhysicsSpace().addAll(level); CameraFrame cf = level.getLastCamera(); if (cf != null) { this.cam.setLocation(cf.getTranslation().clone()); this.cam.setRotation(cf.getRotation().clone()); this.cam.setProjectionMatrix(cf.getProjectionMatrix().clone()); } } } currentTool.simpleUpdate(tpf, this); // Gizmo part if (newGizmoType != gizmoType) { switchGizmo(); } synchronized (viewportTasks) { for (Runnable tasks : viewportTasks) { tasks.run(); } viewportTasks.clear(); } adaptSelectionBox(); } public String createName(Node base, String prefix) { int i = 0; Spatial spatial = null; do { ++i; spatial = base.getChild(prefix + i); } while (spatial != null); return prefix + i; } public Prefab findPrefabParent(Geometry g) { Node parent = g.getParent(); while (!(parent instanceof Prefab) && parent != this.sceneElements && parent != null) { parent = parent.getParent(); } if (parent != null && parent instanceof Prefab) { return (Prefab) parent; } else { return null; } } public Prefab pick() { CollisionResults results = new CollisionResults(); // Convert screen click to 3d position Vector2f click2d = inputManager.getCursorPosition(); Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone(); Vector3f dir = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d); // Aim the ray from the clicked spot forwards. Ray ray = new Ray(click3d, dir); // Collect intersections between ray and all nodes in results list. sceneElements.collideWith(ray, results); if (results.size() == 0) { return null; } // check if the axis is in there. for (Iterator<CollisionResult> it = results.iterator(); it.hasNext();) { CollisionResult cr = it.next(); Geometry g = cr.getGeometry(); if (hasGizmoParent(g)) { return null; } } // if (editorState == EditorState.IDLE || editorState == EditorState.LINK || editorState == EditorState.LINKPARENT || editorState == EditorState.PICK) { int index = 0; for (; index < results.size(); ++index) { Geometry g = results.getCollision(index).getGeometry(); Boolean pickable = (Boolean) g.getUserData("Pickable"); if (pickable == null || pickable == true) { break; } } if (index == results.size()) { return null; } Geometry g = results.getCollision(index).getGeometry(); Node parent = g.getParent(); boolean hasKlatchParent = false; boolean hasPrefabParent = false; Node check = parent; while (check != this.sceneElements) { if (check instanceof Prefab) { hasPrefabParent = true; } if (check instanceof Klatch) { hasKlatchParent = true; } check = check.getParent(); } if (hasKlatchParent) { while (!(parent instanceof Klatch) && parent != this.sceneElements) { parent = parent.getParent(); } } else if (hasPrefabParent) { while (!(parent instanceof Prefab) && parent != this.sceneElements) { parent = parent.getParent(); } } else { return null; } return (Prefab) parent; /* if (parent != this.sceneElements) { if (editorState == EditorState.IDLE) { clearSelection(); this.addToSelection(parent); } else if (editorState == EditorState.PICK) { PickEvent pe = new PickEvent((Prefab) parent, this, pickProperty); GlobalObjects.getInstance().postEvent(pe); clearSelection(); this.newGizmoType = GizmoType.TRANSLATE; editorState = EditorState.IDLE; linkText.setText(""); textBackground.setDimension(0, 0); textBackgroundGeometry.updateModelBound(); linkGeometry.removeFromParent(); wireBoxGeometryLinkParent.removeFromParent(); currentChildElement = null; guiNode.detachChild(linkText); guiNode.detachChild(textBackgroundGeometry); } else if (editorState == EditorState.LINK) { this.currentChildElement = (Prefab) parent; addToSelection(currentChildElement); rootNode.attachChild(linkGeometry); editorState = EditorState.LINKPARENT; } else if (editorState == EditorState.LINKPARENT) { Prefab p = (Prefab) parent; if (p == currentChildElement) { return; } Vector3f wtrans = currentChildElement.getWorldTranslation().clone(); Quaternion wrot = currentChildElement.getWorldRotation().clone(); Vector3f wscale = currentChildElement.getWorldScale().clone(); // child element is moved from one place to another. ProjectTreeNode previousParent = currentChildElement.getProjectParent(); int previousIndex = previousParent.getIndexOfChild(currentChildElement); p.attachChild(currentChildElement); // it is possible that the attachment process attaches the child somewhere else. // express the world transformation of the child as a local transformation in the parent space. Node pn = currentChildElement.getParent(); if (pn != null) { Matrix4f parentMatrix = new Matrix4f(); parentMatrix.setTranslation(pn.getWorldTranslation()); parentMatrix.setRotationQuaternion(pn.getWorldRotation()); parentMatrix.setScale(pn.getWorldScale()); parentMatrix.invertLocal(); Matrix4f childMatrix = new Matrix4f(); childMatrix.setTranslation(wtrans); childMatrix.setRotationQuaternion(wrot); childMatrix.setScale(wscale); Matrix4f local = parentMatrix.mult(childMatrix); currentChildElement.setLocalTranslation(local.toTranslationVector()); currentChildElement.setLocalRotation(local.toRotationQuat()); currentChildElement.setLocalScale(local.toScaleVector()); } // remove child from its layer if (previousParent instanceof Layer) { Layer l = (Layer) previousParent; l.removeNode(currentChildElement); } LevelEvent le = new LevelEvent(level, EventType.NODEMOVED, currentChildElement, previousParent, previousIndex, pn); GlobalObjects.getInstance().postEvent(le); editorState = EditorState.IDLE; newGizmoType = GizmoType.TRANSLATE; linkText.setText(""); textBackground.setDimension(0, 0); textBackgroundGeometry.updateModelBound(); linkGeometry.removeFromParent(); wireBoxGeometryLinkParent.removeFromParent(); currentChildElement = null; guiNode.detachChild(linkText); guiNode.detachChild(textBackgroundGeometry); } } } */ } private boolean hasGizmoParent(Geometry g) { Spatial parent = g; do { parent = parent.getParent(); if (parent instanceof Axis || parent instanceof RotateGizmo) { return true; } } while (!(parent instanceof Prefab) && parent != this.sceneElements); return false; } public void addToSelection(Node node) { if (node == null) { return; } currentSelection.add(node); if (node instanceof Prefab) { Prefab p = (Prefab) node; p.setSelected(true); GlobalObjects.getInstance().postEvent(new SelectionEvent((Prefab) node, this)); } System.out.println("currentTool: " + currentTool.getToolName()); System.out.println("Selecction changed : " + node.getName()); currentTool.selectionChanged(this, node); adaptSelectionBox(); } public void clearSelection() { for (Node n : currentSelection) { ((Prefab) n).setSelected(false); } currentSelection.clear(); currentTool.removeGizmo(); adaptSelectionBox(); } public void pickGizmo() { CollisionResults results = new CollisionResults(); // Convert screen click to 3d position Vector2f click2d = inputManager.getCursorPosition(); Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone(); Vector3f dir = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0.5f).subtractLocal(click3d); // Aim the ray from the clicked spot forwards. Ray ray = new Ray(click3d, dir); // Collect intersections between ray and all nodes in results list. currentTool.pickGizmo(ray, results); if (results.size() > 0) { Geometry g = results.getCollision(0).getGeometry(); Vector3f contactPoint = results.getClosestCollision().getContactPoint(); if (g.getUserData("Transform") != null) { currentTool.gizmoPicked(this, g, contactPoint); } } } private void setupTranslateTransform(Geometry g, Vector3f contactPoint) { /* String transform = g.getUserData("Transform"); if ("translate_X".equals(transform)) { editorState = EditorState.TRANSLATEX; a.getWorldRotation().mult(new Vector3f(1, 0, 0), pickAxis1); } else if ("translate_Y".equals(transform)) { editorState = EditorState.TRANSLATEY; a.getWorldRotation().mult(new Vector3f(0, 1, 0), pickAxis1); } else if ("translate_Z".equals(transform)) { editorState = EditorState.TRANSLATEZ; a.getWorldRotation().mult(new Vector3f(0, 0, 1), pickAxis1); } else if ("translate_XY".equals(transform)) { a.getWorldRotation().mult(new Vector3f(1, 0, 0), pickAxis1); a.getWorldRotation().mult(new Vector3f(0, 1, 0), pickAxis2); editorState = EditorState.TRANSLATETWOAXIS; } else if ("translate_YZ".equals(transform)) { a.getWorldRotation().mult(new Vector3f(0, 1, 0), pickAxis1); a.getWorldRotation().mult(new Vector3f(0, 0, 1), pickAxis2); editorState = EditorState.TRANSLATETWOAXIS; } else if ("translate_XZ".equals(transform)) { a.getWorldRotation().mult(new Vector3f(1, 0, 0), pickAxis1); a.getWorldRotation().mult(new Vector3f(0, 0, 1), pickAxis2); editorState = EditorState.TRANSLATETWOAXIS; } pickOffset = contactPoint.clone(); */ for (Node n : currentSelection) { n.setUserData("BaseTranslation", n.getLocalTranslation().clone()); } // TODO : copy to TranslateTool class. if (shiftIsDown) { // create a copy ArrayList<Prefab> duplicates = new ArrayList<>(); for (Node n : this.currentSelection) { if (n instanceof Prefab) { Prefab copy = ((Prefab) n).duplicate(assetManager, true); // copy will be added to sceneElements. Quaternion q = n.getLocalRotation(); copy.setLocalPrefabRotation(q); copy.setLocalPrefabTranslation(n.getLocalTranslation().clone()); //System.out.println("Copy created :" + copy); duplicates.add(copy); copy.setUserData("BaseTranslation", n.getLocalTranslation().clone()); copy.disablePhysics(); copy.setUserData("DuplicateParent", n.getParent()); copy.setName(this.createName(this.level, copy.getPrefix())); BulletAppState bas = this.getStateManager().getState(BulletAppState.class); copy.addPhysics(bas.getPhysicsSpace()); } } clearSelection(); for (Prefab p : duplicates) { Node parent = (Node) p.getUserData("DuplicateParent"); if (parent != null) { parent.attachChild(p); } else { sceneElements.attachChild(p); } AddPrefabEdit edit = new AddPrefabEdit(p); GlobalObjects.getInstance().addEdit(edit); LevelEvent le = new LevelEvent(this.level, LevelEvent.EventType.NODEADDED, (Node) p); GlobalObjects.getInstance().postEvent(le); addToSelection(p); } } else { for (Node n : currentSelection) { ((Prefab) n).disablePhysics(); } } } private void setupRotateTransform(Geometry g, Vector3f contactPoint) { /* String transform = g.getName(); Vector3f cp = g.worldToLocal(contactPoint, null); if ("X".equals(transform)) { editorState = EditorState.ROTATEX; Vector3f axis = g.getLocalRotation().mult(Vector3f.UNIT_X); rotationDir = cp.cross(axis); } else if ("Y".equals(transform)) { editorState = EditorState.ROTATEY; Vector3f axis = g.getLocalRotation().mult(Vector3f.UNIT_Y); rotationDir = cp.cross(axis); } else if ("Z".equals(transform)) { editorState = EditorState.ROTATEZ; Vector3f axis = g.getLocalRotation().mult(Vector3f.UNIT_Z); rotationDir = cp.cross(axis); } g.getWorldRotation().mult(rotationDir, rotationDir); rotationDir.normalizeLocal(); pickOffset = contactPoint.clone(); for (Node n : currentSelection) { n.setUserData("BaseRotation", n.getLocalRotation().clone()); } */ } /** * This function is called when a new object is created. * * @param coe */ @Subscribe public void onObjectCreation(CreateObjectEvent coe) { synchronized (this) { editorState = EditorState.INSERTIONEVENT; this.objectCreationEvent = coe; //creationTime = System.currentTimeMillis(); } } @Subscribe public void onObjectInsertion(final InsertObjectEvent ioe) { submitViewportTask(new Runnable() { public void run() { Spatial s = assetManager.loadModel(ioe.getPath()); s.setName(ioe.getName()); s.setLocalTransform(ioe.getTransform()); ioe.getParent().attachChild(s); LevelEvent le = new LevelEvent(ioe.getLevel(), EventType.NODEADDED, (Node) s); GlobalObjects.getInstance().postEvent(le); GlobalObjects.getInstance().addEdit(new AddPrefabEdit((Node) s)); } }); } @Subscribe() public void prefabSelected(SelectionEvent se) { if (se.getSource() != this) { this.selectionFromOutside.clear(); if (!currentSelection.contains(se.getSelectedNode())) { selectionFromOutside.add(se.getSelectedNode()); } } } @Subscribe public void setCurrentProject(ProjectEvent pe) { project = pe.getProject(); for (File file : project.getAssetLocations()) { assetManager.registerLocator(file.getPath(), FileLocator.class); } } @Subscribe public void setCurrentLevel(final LevelEvent le) { if (le.getEventType() == EventType.LEVELSELECTED) { if (le.getLevel() != this.level) { if (this.level != null) { this.level.levelHidden(); } this.level = le.getLevel(); editorState = EditorState.LEVELCHANGED; } } else if (le.getEventType() == EventType.NODEREMOVEREQUEST) { submitViewportTask(new Runnable() { public void run() { for (Node n : le.getNodes()) { removeNode(le.getLevel(), n); } clearSelection(); } }); } } private void removeNode(dae.project.Level level, Node n) { if (n instanceof Prefab) { Prefab p = (Prefab) n; // remove the physics BulletAppState bas = this.stateManager.getState(BulletAppState.class); bas.getPhysicsSpace().removeAll(p); ProjectTreeNode parent = p.getProjectParent(); if (parent != null) { int childIndex = parent.getIndexOfChild(p); GlobalObjects.getInstance().addEdit(new DeletePrefabEdit(this.level, n)); n.removeFromParent(); LevelEvent le = LevelEvent.createNodeRemovedEvent(level, n, parent, childIndex); GlobalObjects.getInstance().postEvent(le); } } } @Subscribe public void editAsset(final AssetEvent ae) { if (ae.getAssetEventType() == AssetEventType.MODIFIED) { submitViewportTask(new Runnable() { public void run() { reloadAsset(ae.getFileNode()); } }); } } private void reloadAsset(FileNode asset) { if (asset == null) { return; } if (assetManager instanceof DesktopAssetManager) { ModelKey mk = new ModelKey(asset.getFullName()); DesktopAssetManager dt = (DesktopAssetManager) assetManager; dt.deleteFromCache(mk); } if (project != null) { String fullName = asset.getFullName(); for (dae.project.Level l : project.getLevels()) { if (asset.getExtension().equals("j3o")) { List<MeshObject> meshesToChange = l.descendantMatches(MeshObject.class); for (MeshObject mo : meshesToChange) { MeshComponent mc = (MeshComponent) mo.getComponent("MeshComponent"); if (mc.getMeshFile().equals(fullName)) { mo.reloadMesh(); } } } else if (asset.getExtension().equals("klatch")) { List<Klatch> klatchesToChange = l.descendantMatches(Klatch.class); for (Klatch k : klatchesToChange) { if (k.getKlatchFile().equals(fullName)) { Node parent = k.getParent(); Transform backup = k.getLocalTransform(); k.removeFromParent(); Klatch newversion = (Klatch) this.assetManager.loadModel(k.getKlatchFile()); newversion.setLocalTransform(backup); parent.attachChild(newversion); for (Spatial s : k.getChildren()) { Object klatchpart = s.getUserData("klatchpart"); if (klatchpart != Boolean.TRUE) { newversion.attachChild(s); } } } } } } } } @Subscribe public void setCurrentGizmo(GizmoEvent ge) { if (ge.getSource() != this) { this.newGizmoType = ge.getType(); if (ge.getType() == GizmoType.PICK) { this.pickTool.setPickProperty(ge.getPickProperty()); } } } public Node getFirstSelectedNode() { return currentSelection.size() > 0 ? currentSelection.get(0) : null; } private void switchGizmo() { gizmoType = newGizmoType; Node n = null; if (currentTool != null) { currentTool.deactivate(this); } if (currentSelection.size() > 0) { n = this.currentSelection.get(0); } switch (gizmoType) { case TRANSLATE: currentTool = translateTool; break; case ROTATE: currentTool = rotateTool; break; case LINK: currentTool = linkTool; break; case PICK: currentTool = pickTool; break; case BRUSH: currentTool = brushTool; break; case INSERT: currentTool = insertionTool; break; case NONE: currentTool = idleTool; break; } currentTool.activate(this); GizmoEvent gce = new GizmoEvent(this, gizmoType); GlobalObjects.getInstance().postEvent(gce); } @Subscribe public void doZoomEvent(ZoomEvent ze) { switch (ze.getEventType()) { case EXTENTS_SELECTED: break; case LEVEL: break; } } @Subscribe public void shadowChanged(final ShadowEvent se) { synchronized (viewportTasks) { viewportTasks.add(new Runnable() { public void run() { Prefab p = (Prefab) se.getSource(); if (p.hasAncestor(sceneElements)) { enableShadowRenderer(se.getSource().getShadowRenderer(), se.getSource().getCastShadow()); } } }); } } @Subscribe public void addComponent(final ComponentEvent event) { synchronized (viewportTasks) { viewportTasks.add(new Runnable() { public void run() { for (Node n : currentSelection) { if (n instanceof Prefab) { Prefab prefab = (Prefab) n; ComponentType ct = GlobalObjects.getInstance().getObjectsTypeCategory().getComponent(event.getComponentId()); if (ct != null) { PrefabComponent pc = ct.create(); prefab.addPrefabComponent(pc); } } } } }); } } @Subscribe public void doCutCopyPasteAction(final CutCopyPasteEvent event) { synchronized (viewportTasks) { viewportTasks.add(new Runnable() { public void run() { switch (event.getType()) { case CUT: copyBuffer.clear(); copyBuffer.addAll(currentSelection); break; case PASTE: for (Node newParent : currentSelection) { for (Node toPaste : copyBuffer) { if (newParent == toPaste || toPaste.getParent() == newParent) { // don't paste object on itself. // don't paste if parent is already the parent. continue; } Matrix4f local = MathUtil.changeParent(toPaste, newParent); toPaste.setLocalTranslation(local.toTranslationVector()); toPaste.setLocalRotation(local.toRotationQuat()); toPaste.setLocalScale(local.toScaleVector()); ProjectTreeNode previousParent = null; int index = -1; if (toPaste instanceof ProjectTreeNode) { ProjectTreeNode toPasteNode = (ProjectTreeNode) toPaste; previousParent = toPasteNode.getProjectParent(); index = previousParent.getIndexOfChild(toPasteNode); } newParent.attachChild(toPaste); if (previousParent instanceof Layer) { Layer l = (Layer) previousParent; l.removeNode(toPaste); } if (index != -1) { LevelEvent le = new LevelEvent(level, EventType.NODEMOVED, toPaste, previousParent, index, newParent); GlobalObjects.getInstance().postEvent(le); } } } copyBuffer.clear(); break; } } }); } } private void enableShadowRenderer(AbstractShadowRenderer renderer, boolean enable) { if (enable) { this.viewPort.addProcessor(renderer); } else { this.viewPort.removeProcessor(renderer); } } private void zoomExtentsSelected() { } public void submitViewportTask(Runnable r) { synchronized (viewportTasks) { viewportTasks.add(r); } } @Subscribe public void autoGridStateChanged(final AutoGridEvent age) { submitViewportTask(new Runnable() { public void run() { autoGridEnabled = age.isAutoGridEnabled(); autoGridAxis = age.getMainAxis(); } }); } public void setFlyByCamera(FlyByCamera flyCam) { this.flyCam = flyCam; } public void setLocationOnPrefab(Prefab prefab, Vector3f translation, boolean undoable) { ObjectType oType = prefab.getObjectType(); if (oType != null) { Parameter ptrans = oType.findParameter("TransformComponent", "translation"); if (ptrans != null) { ptrans.invokeSet(prefab, translation, undoable); } } } @Subscribe public void playOrPauseLevel(PlayEvent event) { switch (event.getType()) { case PLAY: try { // get the asset directories, export the current level to one // of the asset directories and start the application. this.submitViewportTask(new Runnable() { public void run() { GameBuilder gb = new GameBuilder(); gb.startGame(project, level); } }); GameWriter.writeGame(project, level); } catch (IOException ex) { Logger.getLogger(SandboxViewport.class.getName()).log(Level.SEVERE, null, ex); } } } public void activateIdleState(Object source) { GizmoEvent ge = new GizmoEvent(source, GizmoType.NONE); GlobalObjects.getInstance().postEvent(ge); //newGizmoType = GizmoType.NONE; } private void activateInsertionTool(Object source) { GizmoEvent ge = new GizmoEvent(source, GizmoType.INSERT); GlobalObjects.getInstance().postEvent(ge); //newGizmoType = GizmoType.INSERT; } public void clearInsertionElements() { insertionElements.detachAllChildren(); } public Prefab getInsertionElement() { return insertionElement; } }
src/dae/gui/SandboxViewport.java
package dae.gui; import com.google.common.eventbus.Subscribe; import com.jme3.app.SimpleApplication; import com.jme3.asset.DesktopAssetManager; import com.jme3.asset.ModelKey; import com.jme3.asset.plugins.FileLocator; import com.jme3.bounding.BoundingBox; import com.jme3.bounding.BoundingVolume; import com.jme3.bounding.BoundingVolume.Type; import com.jme3.bullet.BulletAppState; import com.jme3.bullet.PhysicsSpace; import com.jme3.collision.CollisionResult; import com.jme3.collision.CollisionResults; import com.jme3.cursors.plugins.JmeCursor; import com.jme3.input.FlyByCamera; import com.jme3.input.KeyInput; import com.jme3.input.MouseInput; import com.jme3.input.RawInputListener; import com.jme3.input.controls.ActionListener; import com.jme3.input.controls.AnalogListener; import com.jme3.input.controls.KeyTrigger; import com.jme3.input.controls.MouseAxisTrigger; import com.jme3.input.controls.MouseButtonTrigger; import com.jme3.input.event.JoyAxisEvent; import com.jme3.input.event.JoyButtonEvent; import com.jme3.input.event.KeyInputEvent; import com.jme3.input.event.MouseButtonEvent; import com.jme3.input.event.MouseMotionEvent; import com.jme3.input.event.TouchEvent; import com.jme3.light.AmbientLight; import com.jme3.material.Material; import com.jme3.math.ColorRGBA; import com.jme3.math.Matrix4f; import com.jme3.math.Quaternion; import com.jme3.math.Ray; import com.jme3.math.Transform; import com.jme3.math.Vector2f; import com.jme3.math.Vector3f; import com.jme3.scene.Geometry; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.scene.debug.WireBox; import com.jme3.shadow.AbstractShadowRenderer; import dae.DAECamAppState; import dae.GlobalObjects; import dae.animation.rig.Rig; import dae.animation.rig.io.RigLoader; import dae.animation.rig.timing.Behaviour; import dae.animation.rig.timing.TimeLine; import dae.components.ComponentType; import dae.components.MeshComponent; import dae.components.PrefabComponent; import dae.controller.ControllerLoader; import dae.gui.tools.BrushTool; import dae.gui.tools.IdleTool; import dae.gui.tools.InsertionTool; import dae.gui.tools.LinkTool; import dae.gui.tools.PickTool; import dae.gui.tools.RotateTool; import dae.gui.tools.TranslateTool; import dae.gui.tools.ViewportTool; import dae.io.AnimationReader; import dae.io.ComponentReader; import dae.io.ObjectTypeReader; import dae.io.SceneLoader; import dae.io.game.GameBuilder; import dae.io.game.GameWriter; import dae.io.readers.OVMReader; import dae.prefabs.AxisEnum; import dae.prefabs.Klatch; import dae.prefabs.Prefab; import dae.prefabs.gizmos.Axis; import dae.prefabs.gizmos.RotateGizmo; import dae.prefabs.gizmos.events.AutoGridEvent; import dae.prefabs.parameters.Parameter; import dae.prefabs.prefab.undo.AddPrefabEdit; import dae.prefabs.prefab.undo.DeletePrefabEdit; import dae.prefabs.standard.CameraFrame; import dae.prefabs.standard.MeshObject; import dae.prefabs.types.ObjectType; import dae.prefabs.types.ObjectTypeCategory; import dae.prefabs.ui.classpath.FileNode; import dae.prefabs.ui.events.AnimationEvent; import dae.prefabs.ui.events.AnimationEventType; import dae.prefabs.ui.events.AssetEvent; import dae.prefabs.ui.events.AssetEventType; import dae.prefabs.ui.events.ComponentEvent; import dae.prefabs.ui.events.CreateObjectEvent; import dae.prefabs.ui.events.CutCopyPasteEvent; import dae.prefabs.ui.events.GizmoEvent; import dae.prefabs.ui.events.GizmoType; import static dae.prefabs.ui.events.GizmoType.ROTATE; import static dae.prefabs.ui.events.GizmoType.TRANSLATE; import dae.prefabs.ui.events.InsertObjectEvent; import dae.prefabs.ui.events.LevelEvent; import dae.prefabs.ui.events.LevelEvent.EventType; import dae.prefabs.ui.events.PlayEvent; import dae.prefabs.ui.events.ProjectEvent; import dae.prefabs.ui.events.SelectionEvent; import dae.prefabs.ui.events.ShadowEvent; import dae.prefabs.ui.events.ViewportReshapeEvent; import dae.prefabs.ui.events.ZoomEvent; import dae.project.AssetLevel; import dae.project.Layer; import dae.project.Project; import dae.project.ProjectTreeNode; import dae.util.MathUtil; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.undo.CannotRedoException; import javax.swing.undo.CannotUndoException; /** * * @author Koen Samyn */ public class SandboxViewport extends SimpleApplication implements RawInputListener { /** * The available object types. */ private ObjectTypeCategory objectsToCreate; /** * The default layer for all elements that are added to the scene. */ private Node sceneElements = new Node("scene"); /** * The elements to insert. */ private Node insertionElements = new Node("insertion"); private Prefab insertionElement; /** * The current gizmo type */ private GizmoType gizmoType = GizmoType.NONE; private GizmoType newGizmoType = GizmoType.NONE; /** * The editor state. */ private enum EditorState { IDLE, INSERTIONEVENT, ADDTOSCENE, LEVELCHANGED, SELECTION }; /** * The current editor state. */ private EditorState editorState = EditorState.IDLE; /** * Shift key is used for copying of items */ private boolean shiftIsDown = false; private ArrayList<Node> currentSelection = new ArrayList<>(); private CreateObjectEvent objectCreationEvent; /** * The current level. */ private dae.project.Level level; /** * The current project. */ private Project project; /** * Code that has to be executed on the JMonkey thread. */ private final ArrayList<Runnable> viewportTasks = new ArrayList<>(); /** * Selection from other thread (such as user interface). */ private final ArrayList<Node> selectionFromOutside = new ArrayList<>(); /** * Copy and cut buffer */ private final ArrayList<Node> copyBuffer = new ArrayList<>(); /** * shows the selected object. */ private final WireBox wireBox = new WireBox(); private Geometry wireBoxGeometry; private Material wireBoxMaterial; /** * Cursor */ private JmeCursor cursorConnect1; private JmeCursor cursorConnect2; private JmeCursor cursorSelect; private JmeCursor cursorMove; private JmeCursor cursorRotate; private JmeCursor cursorScale; /** * Tool support */ private IdleTool idleTool; private ViewportTool currentTool; private TranslateTool translateTool; private RotateTool rotateTool; private BrushTool brushTool; private PickTool pickTool; private LinkTool linkTool; private InsertionTool insertionTool; /** * Autogrid functionality */ private boolean autoGridEnabled = false; private AxisEnum autoGridAxis = AxisEnum.Y; public SandboxViewport() { super(new DAECamAppState()); } @Override public void simpleInitApp() { assetManager.registerLoader(ObjectTypeReader.class, "types"); assetManager.registerLoader(ControllerLoader.class, "fcl"); assetManager.registerLoader(SceneLoader.class, "klatch"); assetManager.registerLoader(RigLoader.class, "rig"); assetManager.registerLoader(AnimationReader.class, "animset"); assetManager.registerLoader(ComponentReader.class, "components"); assetManager.registerLoader(OVMReader.class, "ovm"); objectsToCreate = (ObjectTypeCategory) assetManager.loadAsset("Objects/ObjectTypes.types"); GlobalObjects.getInstance().setObjectTypeCategory(objectsToCreate); GlobalObjects.getInstance().registerListener(this); setPauseOnLostFocus(false); translateTool = new TranslateTool(); translateTool.initialize(assetManager, inputManager); rotateTool = new RotateTool(); rotateTool.initialize(assetManager, inputManager); brushTool = new BrushTool(); brushTool.initialize(assetManager, inputManager); pickTool = new PickTool(); pickTool.initialize(assetManager, inputManager); linkTool = new LinkTool(); linkTool.initialize(assetManager, inputManager); idleTool = new IdleTool(); idleTool.initialize(assetManager, inputManager); insertionTool = new InsertionTool(); insertionTool.initialize(assetManager, inputManager); currentTool = idleTool; rootNode.attachChild(sceneElements); rootNode.attachChild(insertionElements); AmbientLight al = new AmbientLight(); al.setColor(ColorRGBA.White.mult(0.25f)); rootNode.addLight(al); AmbientLight insertionLight = new AmbientLight(); insertionLight.setColor(ColorRGBA.White.mult(5.0f)); insertionElements.addLight(insertionLight); cam.setFrustumPerspective(45f, (float) cam.getWidth() / cam.getHeight(), 0.01f, 1000f); cam.setLocation(new Vector3f(5, 2, 0)); cam.lookAt(new Vector3f(0, 0, 0), new Vector3f(0, 1, 0)); initKeys(); // cursorConnect1 = (JmeCursor) assetManager.loadAsset("Interface/connect1.ico"); // cursorConnect2 = (JmeCursor) assetManager.loadAsset("Interface/connect2.ico"); // cursorMove = (JmeCursor) assetManager.loadAsset("Interface/move.ico"); // cursorSelect = (JmeCursor) assetManager.loadAsset("Interface/select.ico"); // cursorRotate = (JmeCursor)assetManager.loadAsset("Interface/rotate.ico"); // cursorScale = (JmeCursor)assetManager.loadAsset("Interface/scale.ico"); BulletAppState bulletAppState = new BulletAppState(); stateManager.attach(bulletAppState); bulletAppState.setBroadphaseType(PhysicsSpace.BroadphaseType.AXIS_SWEEP_3_32); PhysicsSpace.getPhysicsSpace().setGravity(new Vector3f(0, -9.81f, 0)); GlobalObjects.getInstance().setAssetManager(assetManager); GlobalObjects.getInstance().setInputManager(this.inputManager); wireBoxMaterial = assetManager.loadMaterial("Materials/SelectionBoxMaterial.j3m"); wireBoxGeometry = new Geometry("wireframe cube", wireBox); wireBoxGeometry.setMaterial(wireBoxMaterial); rootNode.attachChild(wireBoxGeometry); } /** * Attaches a guid element to the viewport. * * @param s the spatial to attach to the viewport. */ public void attachGuiElement(Spatial s) { guiNode.attachChild(s); } public Node getSceneElements() { return this.sceneElements; } public dae.project.Level getLevel() { return this.level; } public Iterable<Node> getSelection() { return this.currentSelection; } public boolean isAutoGridEnabled() { return autoGridEnabled; } public AxisEnum getAutoGridAxis() { return this.autoGridAxis; } public void disableFlyCam() { flyCam.setEnabled(false); } public void enableFlyCam() { flyCam.setEnabled(true); } public void adaptSelectionBox() { BoundingVolume bv = null; for (Node n : this.currentSelection) { if (n == null) { continue; } if (bv == null) { bv = n.getWorldBound(); } else { bv.merge(n.getWorldBound()); } } if (bv != null && bv.getType() == Type.AABB) { BoundingBox bb = (BoundingBox) bv; if (wireBoxGeometry != null) { wireBoxGeometry.removeFromParent(); } wireBoxGeometry = WireBox.makeGeometry(bb); wireBoxGeometry.setLocalTranslation(bb.getCenter()); wireBoxGeometry.setMaterial(wireBoxMaterial); if (wireBoxGeometry.getParent() == null) { this.rootNode.attachChild(wireBoxGeometry); } } else if (wireBoxGeometry != null) { wireBoxGeometry.removeFromParent(); } } @Override public void reshape(int w, int h) { super.reshape(w, h); GlobalObjects.getInstance().postEvent(new ViewportReshapeEvent(w, h)); } /** * Initialize the inputs. */ private void initKeys() { inputManager.setCursorVisible(true); // You can map one or several inputs to one named action inputManager.addMapping("ACCEPT_INSERTION", new KeyTrigger(KeyInput.KEY_RETURN)); inputManager.addMapping("ACCEPT_INSERTION", new MouseButtonTrigger(MouseInput.BUTTON_LEFT)); inputManager.addMapping("REJECT_INSERTION", new KeyTrigger(KeyInput.KEY_ESCAPE)); inputManager.addMapping("DELETE_SELECTION", new KeyTrigger(KeyInput.KEY_DELETE)); inputManager.addMapping("CHANGE_PIVOT", new KeyTrigger(KeyInput.KEY_C)); inputManager.addMapping("COPY_LASTOBJECT", new KeyTrigger(KeyInput.KEY_F1)); inputManager.addMapping("CREATE_ANIMATION_KEY", new KeyTrigger(KeyInput.KEY_F11)); inputManager.addMapping("DELETE_ANIMATION_KEY", new KeyTrigger(KeyInput.KEY_F12)); inputManager.addMapping("DOBRUSH", new KeyTrigger(KeyInput.KEY_LSHIFT), new KeyTrigger(KeyInput.KEY_RSHIFT)); inputManager.addMapping("UNDO", new KeyTrigger(KeyInput.KEY_U)); inputManager.addMapping("REDO", new KeyTrigger(KeyInput.KEY_R)); inputManager.addMapping("ROTATION_UP", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, false)); inputManager.addMapping("ROTATION_DOWN", new MouseAxisTrigger(MouseInput.AXIS_WHEEL, true)); inputManager.addListener(analogListener, new String[]{"ACCEPT_INSERTION", "SELECT_OBJECT", "REJECT_INSERTION", "DELETE_SELECTION", "ROTATION_UP", "ROTATION_DOWN"}); inputManager.addListener(actionListener, new String[]{"CHANGE_PIVOT", "COPY_LASTOBJECT"}); inputManager.addListener(undoRedoListener, new String[]{"UNDO", "REDO"}); inputManager.addListener(animationListener, new String[]{"CREATE_ANIMATION_KEY", "DELETE_ANIMATION_KEY"}); inputManager.addRawInputListener(this); } private final ActionListener animationListener = new ActionListener() { @Override public void onAction(String name, boolean isPressed, float tpf) { if (!isPressed) { if (name.startsWith("CREATE")) { if (level instanceof AssetLevel) { // search the rig. List<Rig> rigs = level.descendantMatches(Rig.class); if (rigs.size() > 0) { Rig r = rigs.get(0); for (Node n : getSelection()) { Behaviour current = r.getCurrentBehaviour(); if (current != null) { TimeLine tl = current.getTimeLine(n); tl.addRotation(current.getCurrentFrame(), n.getLocalRotation()); } } GlobalObjects.getInstance().postEvent(new AnimationEvent(r, AnimationEventType.CREATE)); } } } else if (name.startsWith("DELETE")) { System.out.println("deleting the animation key"); } } } }; private final ActionListener undoRedoListener = new ActionListener() { @Override public void onAction(String name, boolean keyPressed, float tpf) { if (name.equals("UNDO") && !keyPressed) { try { GlobalObjects.getInstance().undo(); } catch (CannotUndoException ex) { Logger.getLogger("DArtE").log(Level.WARNING, "Cannot undo.", ex); } } else if (name.equals("REDO") && !keyPressed) { try { GlobalObjects.getInstance().redo(); } catch (CannotRedoException ex) { Logger.getLogger("DArtE").log(Level.WARNING, "Cannot redo.", ex); } } } }; private ActionListener actionListener = new ActionListener() { @Override public void onAction(String name, boolean keyPressed, float tpf) { if (name.equals("CHANGE_PIVOT") && !keyPressed) { for (Spatial s : insertionElements.getChildren()) { if (s instanceof Prefab) { ((Prefab) s).cyclePivot(); } } } else if (name.equals("COPY_LASTOBJECT") && !keyPressed) { if (objectCreationEvent != null) { insertionElements.detachAllChildren(); editorState = EditorState.INSERTIONEVENT; } } } }; private final AnalogListener analogListener = new AnalogListener() { @Override public void onAnalog(String name, float value, float tpf) { if (editorState == EditorState.IDLE) { if ("DELETE_SELECTION".equals(name)) { for (Node n : currentSelection) { removeNode(level, n); } clearSelection(); } } } }; /** * Return the objects to create. * * @return the objects to create. */ public ObjectTypeCategory getObjectsToCreate() { return this.objectsToCreate; } /** * */ @Override public void beginInput() { } @Override public void endInput() { } @Override public void onJoyAxisEvent(JoyAxisEvent evt) { } @Override public void onJoyButtonEvent(JoyButtonEvent evt) { } @Override public void onMouseMotionEvent(MouseMotionEvent evt) { currentTool.onMouseMotionEvent(evt, this); } @Override public void onMouseButtonEvent(MouseButtonEvent evt) { if (evt.isReleased()) { currentTool.onMouseButtonReleased(this); } else if (evt.isPressed()) { currentTool.onMouseButtonPressed(this); } } public void addToScene() { clearSelection(); for (Spatial p : insertionElements.getChildren()) { addToSelection((Node) p); sceneElements.attachChild(p); if (p instanceof Prefab) { Prefab prefab = (Prefab) p; //prefab.connect(sceneElements); BulletAppState bas = this.stateManager.getState(BulletAppState.class); prefab.addPhysics(bas.getPhysicsSpace()); } AddPrefabEdit edit = new AddPrefabEdit((Node) p); GlobalObjects.getInstance().addEdit(edit); LevelEvent le = new LevelEvent(this.level, LevelEvent.EventType.NODEADDED, (Node) p); GlobalObjects.getInstance().postEvent(le); } insertionElements.detachAllChildren(); editorState = EditorState.IDLE; } @Override public void onKeyEvent(KeyInputEvent evt) { int kc = evt.getKeyCode(); if (evt.isPressed()) { //controlIsDown = (kc == KeyInput.KEY_LCONTROL || kc == KeyInput.KEY_RCONTROL); shiftIsDown = (kc == KeyInput.KEY_LSHIFT || kc == KeyInput.KEY_RSHIFT); } else { switch (kc) { case KeyInput.KEY_LSHIFT: case KeyInput.KEY_RSHIFT: shiftIsDown = false; break; // case KeyInput.KEY_LCONTROL: // case KeyInput.KEY_RCONTROL: // controlIsDown = false; // break; } } } @Override public void onTouchEvent(TouchEvent evt) { } /** * Clears everything from the scene. */ public void clearScene() { this.insertionElements.detachAllChildren(); this.sceneElements.detachAllChildren(); } @Override public void simpleUpdate(float tpf) { if (this.selectionFromOutside.size() > 0) { clearSelection(); for (Node n : selectionFromOutside) { this.addToSelection(n); } selectionFromOutside.clear(); editorState = EditorState.IDLE; activateIdleState(this); } if (editorState == EditorState.INSERTIONEVENT) { ObjectType objectTypeToCreate = objectCreationEvent.getObjectType(); String name = createName(this.sceneElements, objectTypeToCreate.getLabel()); Prefab p = objectTypeToCreate.create(assetManager, name); if (objectCreationEvent.hasComponents()) { for (PrefabComponent pc : objectCreationEvent.getComponents()) { p.removeComponents(pc.getId()); p.addPrefabComponent(pc); } } if (p != null) { BulletAppState state = stateManager.getState(BulletAppState.class); state.getPhysicsSpace().addAll(p); insertionElement = p; this.insertionElements.attachChild(insertionElement); this.clearSelection(); this.addToSelection(p); activateInsertionTool(objectCreationEvent); } editorState = EditorState.IDLE; } if (editorState == EditorState.ADDTOSCENE) { addToScene(); } if (editorState == EditorState.LEVELCHANGED) { if (this.level != null) { viewPort.clearProcessors(); BulletAppState bas = this.getStateManager().getState(BulletAppState.class); if (this.sceneElements != null) { sceneElements.removeFromParent(); bas.getPhysicsSpace().removeAll(sceneElements); } clearSelection(); rootNode.attachChild(level); this.sceneElements = level; this.level.levelShown(this.assetManager, bas); editorState = EditorState.IDLE; level.updateGeometricState(); bas.getPhysicsSpace().addAll(level); CameraFrame cf = level.getLastCamera(); if (cf != null) { this.cam.setLocation(cf.getTranslation().clone()); this.cam.setRotation(cf.getRotation().clone()); this.cam.setProjectionMatrix(cf.getProjectionMatrix().clone()); } } } currentTool.simpleUpdate(tpf, this); // Gizmo part if (newGizmoType != gizmoType) { switchGizmo(); } synchronized (viewportTasks) { for (Runnable tasks : viewportTasks) { tasks.run(); } viewportTasks.clear(); } adaptSelectionBox(); } public String createName(Node base, String prefix) { int i = 0; Spatial spatial = null; do { ++i; spatial = base.getChild(prefix + i); } while (spatial != null); return prefix + i; } public Prefab findPrefabParent(Geometry g) { Node parent = g.getParent(); while (!(parent instanceof Prefab) && parent != this.sceneElements && parent != null) { parent = parent.getParent(); } if (parent != null && parent instanceof Prefab) { return (Prefab) parent; } else { return null; } } public Prefab pick() { CollisionResults results = new CollisionResults(); // Convert screen click to 3d position Vector2f click2d = inputManager.getCursorPosition(); Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone(); Vector3f dir = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 1f).subtractLocal(click3d); // Aim the ray from the clicked spot forwards. Ray ray = new Ray(click3d, dir); // Collect intersections between ray and all nodes in results list. sceneElements.collideWith(ray, results); if (results.size() == 0) { return null; } // check if the axis is in there. for (Iterator<CollisionResult> it = results.iterator(); it.hasNext();) { CollisionResult cr = it.next(); Geometry g = cr.getGeometry(); if (hasGizmoParent(g)) { return null; } } // if (editorState == EditorState.IDLE || editorState == EditorState.LINK || editorState == EditorState.LINKPARENT || editorState == EditorState.PICK) { int index = 0; for (; index < results.size(); ++index) { Geometry g = results.getCollision(index).getGeometry(); Boolean pickable = (Boolean) g.getUserData("Pickable"); if (pickable == null || pickable == true) { break; } } if (index == results.size()) { return null; } Geometry g = results.getCollision(index).getGeometry(); Node parent = g.getParent(); boolean hasKlatchParent = false; boolean hasPrefabParent = false; Node check = parent; while (check != this.sceneElements) { if (check instanceof Prefab) { hasPrefabParent = true; } if (check instanceof Klatch) { hasKlatchParent = true; } check = check.getParent(); } if (hasKlatchParent) { while (!(parent instanceof Klatch) && parent != this.sceneElements) { parent = parent.getParent(); } } else if (hasPrefabParent) { while (!(parent instanceof Prefab) && parent != this.sceneElements) { parent = parent.getParent(); } } else { return null; } return (Prefab) parent; /* if (parent != this.sceneElements) { if (editorState == EditorState.IDLE) { clearSelection(); this.addToSelection(parent); } else if (editorState == EditorState.PICK) { PickEvent pe = new PickEvent((Prefab) parent, this, pickProperty); GlobalObjects.getInstance().postEvent(pe); clearSelection(); this.newGizmoType = GizmoType.TRANSLATE; editorState = EditorState.IDLE; linkText.setText(""); textBackground.setDimension(0, 0); textBackgroundGeometry.updateModelBound(); linkGeometry.removeFromParent(); wireBoxGeometryLinkParent.removeFromParent(); currentChildElement = null; guiNode.detachChild(linkText); guiNode.detachChild(textBackgroundGeometry); } else if (editorState == EditorState.LINK) { this.currentChildElement = (Prefab) parent; addToSelection(currentChildElement); rootNode.attachChild(linkGeometry); editorState = EditorState.LINKPARENT; } else if (editorState == EditorState.LINKPARENT) { Prefab p = (Prefab) parent; if (p == currentChildElement) { return; } Vector3f wtrans = currentChildElement.getWorldTranslation().clone(); Quaternion wrot = currentChildElement.getWorldRotation().clone(); Vector3f wscale = currentChildElement.getWorldScale().clone(); // child element is moved from one place to another. ProjectTreeNode previousParent = currentChildElement.getProjectParent(); int previousIndex = previousParent.getIndexOfChild(currentChildElement); p.attachChild(currentChildElement); // it is possible that the attachment process attaches the child somewhere else. // express the world transformation of the child as a local transformation in the parent space. Node pn = currentChildElement.getParent(); if (pn != null) { Matrix4f parentMatrix = new Matrix4f(); parentMatrix.setTranslation(pn.getWorldTranslation()); parentMatrix.setRotationQuaternion(pn.getWorldRotation()); parentMatrix.setScale(pn.getWorldScale()); parentMatrix.invertLocal(); Matrix4f childMatrix = new Matrix4f(); childMatrix.setTranslation(wtrans); childMatrix.setRotationQuaternion(wrot); childMatrix.setScale(wscale); Matrix4f local = parentMatrix.mult(childMatrix); currentChildElement.setLocalTranslation(local.toTranslationVector()); currentChildElement.setLocalRotation(local.toRotationQuat()); currentChildElement.setLocalScale(local.toScaleVector()); } // remove child from its layer if (previousParent instanceof Layer) { Layer l = (Layer) previousParent; l.removeNode(currentChildElement); } LevelEvent le = new LevelEvent(level, EventType.NODEMOVED, currentChildElement, previousParent, previousIndex, pn); GlobalObjects.getInstance().postEvent(le); editorState = EditorState.IDLE; newGizmoType = GizmoType.TRANSLATE; linkText.setText(""); textBackground.setDimension(0, 0); textBackgroundGeometry.updateModelBound(); linkGeometry.removeFromParent(); wireBoxGeometryLinkParent.removeFromParent(); currentChildElement = null; guiNode.detachChild(linkText); guiNode.detachChild(textBackgroundGeometry); } } } */ } private boolean hasGizmoParent(Geometry g) { Spatial parent = g; do { parent = parent.getParent(); if (parent instanceof Axis || parent instanceof RotateGizmo) { return true; } } while (!(parent instanceof Prefab) && parent != this.sceneElements); return false; } public void addToSelection(Node node) { if (node == null) { return; } currentSelection.add(node); if (node instanceof Prefab) { Prefab p = (Prefab) node; p.setSelected(true); GlobalObjects.getInstance().postEvent(new SelectionEvent((Prefab) node, this)); } System.out.println("currentTool: " + currentTool.getToolName()); System.out.println("Selecction changed : " + node.getName()); currentTool.selectionChanged(this, node); adaptSelectionBox(); } public void clearSelection() { for (Node n : currentSelection) { ((Prefab) n).setSelected(false); } currentSelection.clear(); currentTool.removeGizmo(); adaptSelectionBox(); } public void pickGizmo() { CollisionResults results = new CollisionResults(); // Convert screen click to 3d position Vector2f click2d = inputManager.getCursorPosition(); Vector3f click3d = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0f).clone(); Vector3f dir = cam.getWorldCoordinates(new Vector2f(click2d.x, click2d.y), 0.5f).subtractLocal(click3d); // Aim the ray from the clicked spot forwards. Ray ray = new Ray(click3d, dir); // Collect intersections between ray and all nodes in results list. currentTool.pickGizmo(ray, results); if (results.size() > 0) { Geometry g = results.getCollision(0).getGeometry(); Vector3f contactPoint = results.getClosestCollision().getContactPoint(); if (g.getUserData("Transform") != null) { currentTool.gizmoPicked(this, g, contactPoint); } } } private void setupTranslateTransform(Geometry g, Vector3f contactPoint) { /* String transform = g.getUserData("Transform"); if ("translate_X".equals(transform)) { editorState = EditorState.TRANSLATEX; a.getWorldRotation().mult(new Vector3f(1, 0, 0), pickAxis1); } else if ("translate_Y".equals(transform)) { editorState = EditorState.TRANSLATEY; a.getWorldRotation().mult(new Vector3f(0, 1, 0), pickAxis1); } else if ("translate_Z".equals(transform)) { editorState = EditorState.TRANSLATEZ; a.getWorldRotation().mult(new Vector3f(0, 0, 1), pickAxis1); } else if ("translate_XY".equals(transform)) { a.getWorldRotation().mult(new Vector3f(1, 0, 0), pickAxis1); a.getWorldRotation().mult(new Vector3f(0, 1, 0), pickAxis2); editorState = EditorState.TRANSLATETWOAXIS; } else if ("translate_YZ".equals(transform)) { a.getWorldRotation().mult(new Vector3f(0, 1, 0), pickAxis1); a.getWorldRotation().mult(new Vector3f(0, 0, 1), pickAxis2); editorState = EditorState.TRANSLATETWOAXIS; } else if ("translate_XZ".equals(transform)) { a.getWorldRotation().mult(new Vector3f(1, 0, 0), pickAxis1); a.getWorldRotation().mult(new Vector3f(0, 0, 1), pickAxis2); editorState = EditorState.TRANSLATETWOAXIS; } pickOffset = contactPoint.clone(); */ for (Node n : currentSelection) { n.setUserData("BaseTranslation", n.getLocalTranslation().clone()); } // TODO : copy to TranslateTool class. if (shiftIsDown) { // create a copy ArrayList<Prefab> duplicates = new ArrayList<>(); for (Node n : this.currentSelection) { if (n instanceof Prefab) { Prefab copy = ((Prefab) n).duplicate(assetManager, true); // copy will be added to sceneElements. Quaternion q = n.getLocalRotation(); copy.setLocalPrefabRotation(q); copy.setLocalPrefabTranslation(n.getLocalTranslation().clone()); //System.out.println("Copy created :" + copy); duplicates.add(copy); copy.setUserData("BaseTranslation", n.getLocalTranslation().clone()); copy.disablePhysics(); copy.setUserData("DuplicateParent", n.getParent()); copy.setName(this.createName(this.level, copy.getPrefix())); BulletAppState bas = this.getStateManager().getState(BulletAppState.class); copy.addPhysics(bas.getPhysicsSpace()); } } clearSelection(); for (Prefab p : duplicates) { Node parent = (Node) p.getUserData("DuplicateParent"); if (parent != null) { parent.attachChild(p); } else { sceneElements.attachChild(p); } AddPrefabEdit edit = new AddPrefabEdit(p); GlobalObjects.getInstance().addEdit(edit); LevelEvent le = new LevelEvent(this.level, LevelEvent.EventType.NODEADDED, (Node) p); GlobalObjects.getInstance().postEvent(le); addToSelection(p); } } else { for (Node n : currentSelection) { ((Prefab) n).disablePhysics(); } } } private void setupRotateTransform(Geometry g, Vector3f contactPoint) { /* String transform = g.getName(); Vector3f cp = g.worldToLocal(contactPoint, null); if ("X".equals(transform)) { editorState = EditorState.ROTATEX; Vector3f axis = g.getLocalRotation().mult(Vector3f.UNIT_X); rotationDir = cp.cross(axis); } else if ("Y".equals(transform)) { editorState = EditorState.ROTATEY; Vector3f axis = g.getLocalRotation().mult(Vector3f.UNIT_Y); rotationDir = cp.cross(axis); } else if ("Z".equals(transform)) { editorState = EditorState.ROTATEZ; Vector3f axis = g.getLocalRotation().mult(Vector3f.UNIT_Z); rotationDir = cp.cross(axis); } g.getWorldRotation().mult(rotationDir, rotationDir); rotationDir.normalizeLocal(); pickOffset = contactPoint.clone(); for (Node n : currentSelection) { n.setUserData("BaseRotation", n.getLocalRotation().clone()); } */ } /** * This function is called when a new object is created. * * @param coe */ @Subscribe public void onObjectCreation(CreateObjectEvent coe) { synchronized (this) { editorState = EditorState.INSERTIONEVENT; this.objectCreationEvent = coe; //creationTime = System.currentTimeMillis(); } } @Subscribe public void onObjectInsertion(final InsertObjectEvent ioe) { submitViewportTask(new Runnable() { public void run() { Spatial s = assetManager.loadModel(ioe.getPath()); s.setName(ioe.getName()); s.setLocalTransform(ioe.getTransform()); ioe.getParent().attachChild(s); LevelEvent le = new LevelEvent(ioe.getLevel(), EventType.NODEADDED, (Node) s); GlobalObjects.getInstance().postEvent(le); GlobalObjects.getInstance().addEdit(new AddPrefabEdit((Node) s)); } }); } @Subscribe() public void prefabSelected(SelectionEvent se) { if (se.getSource() != this) { this.selectionFromOutside.clear(); if (!currentSelection.contains(se.getSelectedNode())) { selectionFromOutside.add(se.getSelectedNode()); } } } @Subscribe public void setCurrentProject(ProjectEvent pe) { project = pe.getProject(); for (File file : project.getAssetLocations()) { assetManager.registerLocator(file.getPath(), FileLocator.class); } } @Subscribe public void setCurrentLevel(final LevelEvent le) { if (le.getEventType() == EventType.LEVELSELECTED) { if (le.getLevel() != this.level) { if (this.level != null) { this.level.levelHidden(); } this.level = le.getLevel(); editorState = EditorState.LEVELCHANGED; } } else if (le.getEventType() == EventType.NODEREMOVEREQUEST) { submitViewportTask(new Runnable() { public void run() { for (Node n : le.getNodes()) { removeNode(le.getLevel(), n); } clearSelection(); } }); } } private void removeNode(dae.project.Level level, Node n) { if (n instanceof Prefab) { Prefab p = (Prefab) n; // remove the physics BulletAppState bas = this.stateManager.getState(BulletAppState.class); bas.getPhysicsSpace().removeAll(p); ProjectTreeNode parent = p.getProjectParent(); if (parent != null) { int childIndex = parent.getIndexOfChild(p); GlobalObjects.getInstance().addEdit(new DeletePrefabEdit(this.level, n)); n.removeFromParent(); LevelEvent le = LevelEvent.createNodeRemovedEvent(level, n, parent, childIndex); GlobalObjects.getInstance().postEvent(le); } } } @Subscribe public void editAsset(final AssetEvent ae) { if (ae.getAssetEventType() == AssetEventType.MODIFIED) { submitViewportTask(new Runnable() { public void run() { reloadAsset(ae.getFileNode()); } }); } } private void reloadAsset(FileNode asset) { if (asset == null) { return; } if (assetManager instanceof DesktopAssetManager) { ModelKey mk = new ModelKey(asset.getFullName()); DesktopAssetManager dt = (DesktopAssetManager) assetManager; dt.deleteFromCache(mk); } if (project != null) { String fullName = asset.getFullName(); for (dae.project.Level l : project.getLevels()) { if (asset.getExtension().equals("j3o")) { List<MeshObject> meshesToChange = l.descendantMatches(MeshObject.class); for (MeshObject mo : meshesToChange) { MeshComponent mc = (MeshComponent) mo.getComponent("MeshComponent"); if (mc.getMeshFile().equals(fullName)) { mo.reloadMesh(); } } } else if (asset.getExtension().equals("klatch")) { List<Klatch> klatchesToChange = l.descendantMatches(Klatch.class); for (Klatch k : klatchesToChange) { if (k.getKlatchFile().equals(fullName)) { Node parent = k.getParent(); Transform backup = k.getLocalTransform(); k.removeFromParent(); Klatch newversion = (Klatch) this.assetManager.loadModel(k.getKlatchFile()); newversion.setLocalTransform(backup); parent.attachChild(newversion); for (Spatial s : k.getChildren()) { Object klatchpart = s.getUserData("klatchpart"); if (klatchpart != Boolean.TRUE) { newversion.attachChild(s); } } } } } } } } @Subscribe public void setCurrentGizmo(GizmoEvent ge) { if (ge.getSource() != this) { this.newGizmoType = ge.getType(); if (ge.getType() == GizmoType.PICK) { this.pickTool.setPickProperty(ge.getPickProperty()); } } } public Node getFirstSelectedNode() { return currentSelection.size() > 0 ? currentSelection.get(0) : null; } private void switchGizmo() { gizmoType = newGizmoType; Node n = null; if (currentTool != null) { currentTool.deactivate(this); } if (currentSelection.size() > 0) { n = this.currentSelection.get(0); } switch (gizmoType) { case TRANSLATE: currentTool = translateTool; break; case ROTATE: currentTool = rotateTool; break; case LINK: currentTool = linkTool; break; case PICK: currentTool = pickTool; break; case BRUSH: currentTool = brushTool; break; case INSERT: currentTool = insertionTool; break; case NONE: currentTool = idleTool; break; } currentTool.activate(this); GizmoEvent gce = new GizmoEvent(this, gizmoType); GlobalObjects.getInstance().postEvent(gce); } @Subscribe public void doZoomEvent(ZoomEvent ze) { switch (ze.getEventType()) { case EXTENTS_SELECTED: break; case LEVEL: break; } } @Subscribe public void shadowChanged(final ShadowEvent se) { synchronized (viewportTasks) { viewportTasks.add(new Runnable() { public void run() { Prefab p = (Prefab) se.getSource(); if (p.hasAncestor(sceneElements)) { enableShadowRenderer(se.getSource().getShadowRenderer(), se.getSource().getCastShadow()); } } }); } } @Subscribe public void addComponent(final ComponentEvent event) { synchronized (viewportTasks) { viewportTasks.add(new Runnable() { public void run() { for (Node n : currentSelection) { if (n instanceof Prefab) { Prefab prefab = (Prefab) n; ComponentType ct = GlobalObjects.getInstance().getObjectsTypeCategory().getComponent(event.getComponentId()); if (ct != null) { PrefabComponent pc = ct.create(); prefab.addPrefabComponent(pc); } } } } }); } } @Subscribe public void doCutCopyPasteAction(final CutCopyPasteEvent event) { synchronized (viewportTasks) { viewportTasks.add(new Runnable() { public void run() { switch (event.getType()) { case CUT: copyBuffer.clear(); copyBuffer.addAll(currentSelection); break; case PASTE: for (Node newParent : currentSelection) { for (Node toPaste : copyBuffer) { if (newParent == toPaste || toPaste.getParent() == newParent) { // don't paste object on itself. // don't paste if parent is already the parent. continue; } Matrix4f local = MathUtil.changeParent(toPaste, newParent); toPaste.setLocalTranslation(local.toTranslationVector()); toPaste.setLocalRotation(local.toRotationQuat()); toPaste.setLocalScale(local.toScaleVector()); ProjectTreeNode previousParent = null; int index = -1; if (toPaste instanceof ProjectTreeNode) { ProjectTreeNode toPasteNode = (ProjectTreeNode) toPaste; previousParent = toPasteNode.getProjectParent(); index = previousParent.getIndexOfChild(toPasteNode); } newParent.attachChild(toPaste); if (previousParent instanceof Layer) { Layer l = (Layer) previousParent; l.removeNode(toPaste); } if (index != -1) { LevelEvent le = new LevelEvent(level, EventType.NODEMOVED, toPaste, previousParent, index, newParent); GlobalObjects.getInstance().postEvent(le); } } } copyBuffer.clear(); break; } } }); } } private void enableShadowRenderer(AbstractShadowRenderer renderer, boolean enable) { if (enable) { this.viewPort.addProcessor(renderer); } else { this.viewPort.removeProcessor(renderer); } } private void zoomExtentsSelected() { } public void submitViewportTask(Runnable r) { synchronized (viewportTasks) { viewportTasks.add(r); } } @Subscribe public void autoGridStateChanged(final AutoGridEvent age) { submitViewportTask(new Runnable() { public void run() { autoGridEnabled = age.isAutoGridEnabled(); autoGridAxis = age.getMainAxis(); } }); } public void setFlyByCamera(FlyByCamera flyCam) { this.flyCam = flyCam; } public void setLocationOnPrefab(Prefab prefab, Vector3f translation, boolean undoable) { ObjectType oType = prefab.getObjectType(); if (oType != null) { Parameter ptrans = oType.findParameter("TransformComponent", "translation"); if (ptrans != null) { ptrans.invokeSet(prefab, translation, undoable); } } } @Subscribe public void playOrPauseLevel(PlayEvent event) { switch (event.getType()) { case PLAY: try { // get the asset directories, export the current level to one // of the asset directories and start the application. this.submitViewportTask(new Runnable() { public void run() { GameBuilder gb = new GameBuilder(); gb.startGame(project, level); } }); GameWriter.writeGame(project, level); } catch (IOException ex) { Logger.getLogger(SandboxViewport.class.getName()).log(Level.SEVERE, null, ex); } } } public void activateIdleState(Object source) { GizmoEvent ge = new GizmoEvent(source, GizmoType.NONE); GlobalObjects.getInstance().postEvent(ge); //newGizmoType = GizmoType.NONE; } private void activateInsertionTool(Object source) { GizmoEvent ge = new GizmoEvent(source, GizmoType.INSERT); GlobalObjects.getInstance().postEvent(ge); //newGizmoType = GizmoType.INSERT; } public void clearInsertionElements() { insertionElements.detachAllChildren(); } public Prefab getInsertionElement() { return insertionElement; } }
Implemented delete animation key.
src/dae/gui/SandboxViewport.java
Implemented delete animation key.
<ide><path>rc/dae/gui/SandboxViewport.java <ide> } <ide> } else if (name.startsWith("DELETE")) { <ide> System.out.println("deleting the animation key"); <del> <add> if (level instanceof AssetLevel){ <add> List<Rig> rigs = level.descendantMatches(Rig.class); <add> if (rigs.size() > 0) { <add> Rig r = rigs.get(0); <add> for (Node n : getSelection()) { <add> Behaviour current = r.getCurrentBehaviour(); <add> if (current != null) { <add> TimeLine tl = current.getTimeLine(n); <add> tl.removeRotation(current.getCurrentFrame()); <add> } <add> } <add> GlobalObjects.getInstance().postEvent(new AnimationEvent(r, AnimationEventType.CREATE)); <add> } <add> } <ide> } <ide> } <ide> }
Java
mit
e0d924f14f473d7f1d39c9ad627c4143a72c30bb
0
igvteam/igv,amwenger/igv,igvteam/igv,amwenger/igv,igvteam/igv,igvteam/igv,amwenger/igv,igvteam/igv,amwenger/igv,amwenger/igv
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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. */ package org.broad.igv.ui; import apple.dts.samplecode.osxadapter.OSXAdapter; import org.apache.log4j.Logger; import org.broad.igv.DirectoryManager; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.annotations.ForTesting; import org.broad.igv.charts.ScatterPlotUtils; import org.broad.igv.cli_plugin.PluginSpecReader; import org.broad.igv.cli_plugin.ui.RunPlugin; import org.broad.igv.cli_plugin.ui.SetPluginPathDialog; import org.broad.igv.dev.db.DBProfileEditor; import org.broad.igv.feature.genome.GenomeListItem; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.ga4gh.Ga4ghAPIHelper; import org.broad.igv.ga4gh.OAuthUtils; import org.broad.igv.gs.GSOpenSessionMenuAction; import org.broad.igv.gs.GSSaveSessionMenuAction; import org.broad.igv.gs.GSUtils; import org.broad.igv.lists.GeneListManagerUI; import org.broad.igv.lists.VariantListManager; import org.broad.igv.tools.IgvToolsGui; import org.broad.igv.track.CombinedDataSourceDialog; import org.broad.igv.ui.action.*; import org.broad.igv.ui.legend.LegendDialog; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.ui.panel.MainPanel; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.ui.panel.ReorderPanelsDialog; import org.broad.igv.ui.util.*; import org.broad.igv.util.*; import org.broad.igv.util.encode.EncodeFileBrowser; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.plaf.basic.BasicBorders; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import static org.broad.igv.ui.UIConstants.*; /** * Main menu bar at top of window. File / genomes / view / etc. * Singleton * * @author jrobinso * @date Apr 4, 2011 */ public class IGVMenuBar extends JMenuBar { private static Logger log = Logger.getLogger(IGVMenuBar.class); public static final String GENOMESPACE_REG_TOOLTIP = "Register for GenomeSpace"; public static final String GENOMESPACE_REG_PAGE = "http://www.genomespace.org/register"; private JMenu fileMenu; private JMenu extrasMenu; private FilterTracksMenuAction filterTracksAction; private JMenu viewMenu; IGV igv; private JMenu toolsMenu; /** * We store this as a field because we alter it if * we can't access genome server list */ private JMenuItem loadFromServerMenuItem; private static final String LOAD_GENOME_SERVER_TOOLTIP = "Select genomes available on the server to appear in menu."; private static final String CANNOT_LOAD_GENOME_SERVER_TOOLTIP = "Could not reach genome server"; private static IGVMenuBar instance; private JMenu googleMenu; public void notifyGenomeServerReachable(boolean reachable) { if (loadFromServerMenuItem != null) { loadFromServerMenuItem.setEnabled(reachable); String tooltip = reachable ? LOAD_GENOME_SERVER_TOOLTIP : CANNOT_LOAD_GENOME_SERVER_TOOLTIP; loadFromServerMenuItem.setToolTipText(tooltip); } } public void showAboutDialog() { (new AboutDialog(IGV.getMainFrame(), true)).setVisible(true); } static IGVMenuBar createInstance(IGV igv) { if (instance != null) { if (igv == instance.igv) { return instance; } throw new IllegalStateException("Cannot create another IGVMenuBar, use getInstance"); } instance = new IGVMenuBar(igv); return instance; } public static IGVMenuBar getInstance() { return instance; } private IGVMenuBar(IGV igv) { this.igv = igv; setBorder(new BasicBorders.MenuBarBorder(Color.GRAY, Color.GRAY)); setBorderPainted(true); for (AbstractButton menu : createMenus()) { add(menu); } //This is for Macs, so showing the about dialog //from the command bar does what we want. if (Globals.IS_MAC) { try { OSXAdapter.setAboutHandler(this, getClass().getDeclaredMethod("showAboutDialog", (Class[]) null)); OSXAdapter.setQuitHandler(ShutdownThread.class, ShutdownThread.class.getDeclaredMethod("runS", (Class[]) null)); } catch (Exception e) { log.error("Error setting apple-specific about and quit handlers", e); } } } private List<AbstractButton> createMenus() { List<AbstractButton> menus = new ArrayList<AbstractButton>(); createFileMenu(); menus.add(fileMenu); menus.add(createGenomesMenu()); menus.add(createViewMenu()); menus.add(createTracksMenu()); menus.add(createRegionsMenu()); refreshToolsMenu(); menus.add(toolsMenu); menus.add(createGenomeSpaceMenu()); extrasMenu = createExtrasMenu(); //extrasMenu.setVisible(false); menus.add(extrasMenu); googleMenu = createGoogleMenu(); googleMenu.setVisible(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.ENABLE_GOOGLE_MENU)); menus.add(googleMenu); menus.add(createHelpMenu()); // Experimental -- remove for production release return menus; } /** * Generate the "tools" menu. * This is imperative, it is written to field {@code toolsMenu}. * Reason being, when we add (TODO remove) * a new tool, we need to refresh just this menu */ void refreshToolsMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(10); // batch script MenuAction menuAction = new RunScriptMenuAction("Run Batch Script...", KeyEvent.VK_X, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // igvtools //menuItems.add(new JSeparator()); menuAction = new SortTracksMenuAction("Run igvtools...", KeyEvent.VK_T, igv) { @Override public void actionPerformed(ActionEvent e) { IgvToolsGui.launch(false, igv.getGenomeManager().getGenomeId()); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); List<JComponent> otherToolMenus = igv.getOtherToolMenus(); if (otherToolMenus.size() > 0) { for (JComponent entry : otherToolMenus) { menuItems.add(entry); } } //menuItems.add(new JSeparator()); //-------------------------------------// //"Add tool" option, for loading cli_plugin from someplace else JMenuItem addTool = new JMenuItem("Add Tool..."); addTool.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File pluginFi = FileDialogUtils.chooseFile("Select cli_plugin .xml spec"); if (pluginFi == null) return; try { PluginSpecReader.addCustomPlugin(pluginFi.getAbsolutePath()); refreshToolsMenu(); } catch (IOException e1) { MessageUtils.showErrorMessage("Error loading custom cli_plugin", e1); } } }); //menuItems.add(addTool); //menuItems.add(new JSeparator()); //-------------------------------------// for (final PluginSpecReader pluginSpecReader : PluginSpecReader.getPlugins()) { for (final PluginSpecReader.Tool tool : pluginSpecReader.getTools()) { final String toolName = tool.name; boolean toolVisible = tool.visible; JMenuItem toolMenu; if (toolVisible) { final String toolPath = pluginSpecReader.getToolPath(tool); final String tool_url = tool.toolUrl; boolean isValid = PluginSpecReader.isToolPathValid(toolPath); ActionListener invalidActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String msg = String.format("%s executable not found at %s", toolName, toolPath); if (tool_url != null) { msg += "<br/>See " + tool_url + " to install"; } MessageUtils.showMessage(msg); } }; toolMenu = new JMenu(toolName); //Kind of overlaps with the side-pull menu, doesn't look great //toolMenu.setToolTipText(tool.getAttribute("description")); for (final PluginSpecReader.Command command : tool.commandList) { final String cmdName = command.name; JMenuItem cmdItem = new JMenuItem(cmdName); toolMenu.add(cmdItem); if (isValid || toolPath == null) { cmdItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RunPlugin runPlugin = null; try { runPlugin = new RunPlugin(IGV.getMainFrame(), pluginSpecReader, tool, command); } catch (IllegalStateException e1) { MessageUtils.showErrorMessage(e1.getMessage(), e1); return; } runPlugin.setVisible(true); } }); cmdItem.setEnabled(true); } else { cmdItem.setEnabled(false); } } //Hack so we can have a tool which is just general command line stuff //Don't let the user change the path in that case if (tool.defaultPath != null) { JMenuItem setPathItem = new JMenuItem(String.format("Set path to %s...", toolName)); setPathItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { (new SetPluginPathDialog(IGV.getMainFrame(), pluginSpecReader, tool)).setVisible(true); refreshToolsMenu(); } }); toolMenu.add(setPathItem); } menuItems.add(toolMenu); } } } //-------------------------------------// //-----------SQL DB Tools--------------// boolean showDBEditor = Globals.isDevelopment(); if (showDBEditor) { JMenu sqlDBProfileEditor = new JMenu("SQL DB Profile Editor"); JMenuItem createNewProfile = new JMenuItem("Create New Profile"); createNewProfile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File file = FileDialogUtils.chooseFile("Save DB Profile", DirectoryManager.getUserDirectory(), FileDialogUtils.SAVE); if (file != null) { DBProfileEditor editor = new DBProfileEditor(IGV.getMainFrame(), file.getAbsolutePath()); editor.setVisible(true); } } }); JMenuItem editExistingProfile = new JMenuItem("Edit Existing Profile"); editExistingProfile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File file = FileDialogUtils.chooseFile("Select .dbxml database profile"); if (file != null) { if (!file.exists()) { } DBProfileEditor editor = new DBProfileEditor(IGV.getMainFrame(), file.getAbsolutePath()); editor.setVisible(true); } } }); sqlDBProfileEditor.add(createNewProfile); sqlDBProfileEditor.add(editExistingProfile); menuItems.add(sqlDBProfileEditor); } //-------------------------------------// //DataTrack Math------------------------// JMenuItem combineDataItem = new JMenuItem("Combine Data Tracks"); combineDataItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CombinedDataSourceDialog dialog = new CombinedDataSourceDialog(IGV.getMainFrame()); dialog.setVisible(true); } }); menuItems.add(combineDataItem); //-------------------------------------// MenuAction toolsMenuAction = new MenuAction("Tools", null); if (toolsMenu == null) { toolsMenu = MenuAndToolbarUtils.createMenu(menuItems, toolsMenuAction); toolsMenu.setName("Tools"); } else { toolsMenu.removeAll(); for (JComponent item : menuItems) { toolsMenu.add(item); } } } public void enableExtrasMenu() { extrasMenu.setVisible(true); } void createFileMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; //We disable certain load items when there is no genome. boolean genomeLoaded = GenomeManager.getInstance().getCurrentGenome() != null; menuItems.add(new JSeparator()); // Load menu items menuAction = new LoadFilesMenuAction("Load from File...", KeyEvent.VK_L, igv); menuAction.setToolTipText(UIConstants.LOAD_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new LoadFromURLMenuAction(LoadFromURLMenuAction.LOAD_FROM_URL, KeyEvent.VK_U, igv); menuAction.setToolTipText(UIConstants.LOAD_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new LoadFromServerAction("Load from Server...", KeyEvent.VK_S, igv); menuAction.setToolTipText(UIConstants.LOAD_SERVER_DATA_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new LoadFromURLMenuAction(LoadFromURLMenuAction.LOAD_FROM_DAS, KeyEvent.VK_D, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.DB_ENABLED)) { menuAction = new LoadFromDatabaseAction("Load from Database...", 0, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); } String genomeId = IGV.getInstance().getGenomeManager().getGenomeId(); if (EncodeFileBrowser.genomeSupported(genomeId)) { menuAction = new BrowseEncodeAction("Load from ENCODE...", KeyEvent.VK_E, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); } menuAction = new BrowseGa4ghAction("Load from Ga4gh...", KeyEvent.VK_G, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); //Disable loading if no genome loaded. Something of an edge case if (!genomeLoaded) { for (JComponent menuItem : menuItems) { menuItem.setEnabled(false); } } menuItems.add(new JSeparator()); // Session menu items menuAction = new NewSessionMenuAction("New Session...", KeyEvent.VK_N, igv); menuAction.setToolTipText(UIConstants.NEW_SESSION_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new OpenSessionMenuAction("Open Session...", KeyEvent.VK_O, igv); menuAction.setToolTipText(UIConstants.RESTORE_SESSION_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new SaveSessionMenuAction("Save Session...", KeyEvent.VK_V, igv); menuAction.setToolTipText(UIConstants.SAVE_SESSION_TOOLTIP); JMenuItem saveSessionItem = MenuAndToolbarUtils.createMenuItem(menuAction); menuItems.add(saveSessionItem); saveSessionItem.setEnabled(genomeLoaded); menuItems.add(new JSeparator()); // ***** Snapshots // Snapshot Application menuAction = new MenuAction("Save Image ...", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { igv.saveImage(igv.getMainPanel()); } }; menuAction.setToolTipText(SAVE_IMAGE_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // TODO -- change "Exit" to "Close" for BioClipse menuItems.add(new JSeparator()); // Exit menuAction = new MenuAction("Exit", null, KeyEvent.VK_X) { @Override public void actionPerformed(ActionEvent e) { doExitApplication(); } }; menuAction.setToolTipText(EXIT_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Empty the recent sessions list before we start to do // anything with it igv.getRecentSessionList().clear(); // Retrieve the stored session paths String recentSessions = PreferenceManager.getInstance().getRecentSessions(); if (recentSessions != null) { String[] sessions = recentSessions.split(";"); for (String sessionPath : sessions) { if (!igv.getRecentSessionList().contains(sessionPath)) { igv.getRecentSessionList().add(sessionPath); } } } if (!IGV.getInstance().getRecentSessionList().isEmpty()) { menuItems.add(new JSeparator()); // Now add menu items for (final String session : IGV.getInstance().getRecentSessionList()) { OpenSessionMenuAction osMenuAction = new OpenSessionMenuAction(session, session, IGV.getInstance()); menuItems.add(MenuAndToolbarUtils.createMenuItem(osMenuAction)); } } MenuAction fileMenuAction = new MenuAction("File", null, KeyEvent.VK_F); if (fileMenu == null) { fileMenu = MenuAndToolbarUtils.createMenu(menuItems, fileMenuAction); } else { fileMenu.removeAll(); for (JComponent item : menuItems) { fileMenu.add(item); } } } private void notifyGenomesAddedRemoved(List<GenomeListItem> selectedValues, boolean added) { if (selectedValues == null || selectedValues.size() == 0) return; int size = selectedValues.size(); String msg = ""; if (size == 1) { msg += selectedValues.get(0) + " genome"; } else { msg += size + " genomes"; } if (added) { msg += " added to"; } else { msg += " removed from"; } msg += " list"; MessageUtils.setStatusBarMessage(msg); } private JMenu createGenomesMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; // Load genome menuAction = new MenuAction("Load Genome from File...", null, KeyEvent.VK_I) { @Override public void actionPerformed(ActionEvent event) { try { org.broad.igv.ui.util.ProgressMonitor monitor = new org.broad.igv.ui.util.ProgressMonitor(); igv.doLoadGenome(monitor); } catch (Exception e) { MessageUtils.showErrorMessage(e.getMessage(), e); } } }; menuAction.setToolTipText("Load a FASTA or .genome file..."); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Load genome from URL menuAction = new LoadFromURLMenuAction(LoadFromURLMenuAction.LOAD_GENOME_FROM_URL, 0, igv); menuAction.setToolTipText("Load a FASTA or .genome file..."); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Add genome to combo box from server menuAction = new MenuAction("Load Genome From Server...", null) { @Override public void actionPerformed(ActionEvent event) { IGV.getInstance().loadGenomeFromServerAction(); } }; menuAction.setToolTipText(LOAD_GENOME_SERVER_TOOLTIP); loadFromServerMenuItem = MenuAndToolbarUtils.createMenuItem(menuAction); menuItems.add(loadFromServerMenuItem); menuItems.add(new JSeparator()); menuAction = new MenuAction("Create .genome File...", null, KeyEvent.VK_D) { @Override public void actionPerformed(ActionEvent event) { org.broad.igv.ui.util.ProgressMonitor monitor = new org.broad.igv.ui.util.ProgressMonitor(); igv.doDefineGenome(monitor); } }; menuAction.setToolTipText(UIConstants.IMPORT_GENOME_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); // Add genome to combo box from server menuAction = new MenuAction("Manage Genome List...", null) { @Override public void actionPerformed(ActionEvent event) { ManageGenomesDialog dialog2 = new ManageGenomesDialog(IGV.getMainFrame()); dialog2.setVisible(true); boolean cancelled = dialog2.isCancelled(); List<GenomeListItem> removedValuesList = dialog2.getRemovedValuesList(); if (!cancelled) { GenomeManager.getInstance().buildGenomeItemList(); igv.getContentPane().getCommandBar().refreshGenomeListComboBox(); if (removedValuesList != null && !removedValuesList.isEmpty()) { try { GenomeManager.getInstance().deleteDownloadedGenomes(removedValuesList); } catch (IOException e) { MessageUtils.showErrorMessage("Error deleting genome files", e); } GenomeManager.getInstance().updateImportedGenomePropertyFile(); notifyGenomesAddedRemoved(removedValuesList, false); } } } }; menuAction.setToolTipText("Add, remove, or reorder genomes which appear in the dropdown list"); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction genomeMenuAction = new MenuAction("Genomes", null); return MenuAndToolbarUtils.createMenu(menuItems, genomeMenuAction); } private JMenu createTracksMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; // Sort Context menuAction = new SortTracksMenuAction("Sort Tracks...", KeyEvent.VK_S, IGV.getInstance()); menuAction.setToolTipText(SORT_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new GroupTracksMenuAction("Group Tracks... ", KeyEvent.VK_G, IGV.getInstance()); menuAction.setToolTipText(UIConstants.GROUP_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Filter Tracks filterTracksAction = new FilterTracksMenuAction("Filter Tracks...", KeyEvent.VK_F, IGV.getInstance()); filterTracksAction.setToolTipText(UIConstants.FILTER_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(filterTracksAction)); menuItems.add(new JSeparator()); // Reset Tracks menuAction = new FitDataToWindowMenuAction("Fit Data to Window", KeyEvent.VK_W, IGV.getInstance()); menuAction.setToolTipText(UIConstants.FIT_DATA_TO_WINDOW_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Set track height menuAction = new SetTrackHeightMenuAction("Set Track Height...", KeyEvent.VK_H, IGV.getInstance()); menuAction.setToolTipText(UIConstants.SET_DEFAULT_TRACK_HEIGHT_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction dataMenuAction = new MenuAction("Tracks", null, KeyEvent.VK_K); //menuItems.add(exportData); return MenuAndToolbarUtils.createMenu(menuItems, dataMenuAction); } private JMenu createViewMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; // Preferences menuAction = new MenuAction("Preferences...", null, KeyEvent.VK_P) { @Override public void actionPerformed(ActionEvent e) { UIUtilities.invokeOnEventThread(new Runnable() { public void run() { IGV.getInstance().doViewPreferences(); } }); } }; menuAction.setToolTipText(PREFERENCE_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("Color Legends ...", null, KeyEvent.VK_H) { @Override public void actionPerformed(ActionEvent e) { (new LegendDialog(IGV.getMainFrame())).setVisible(true); } }; menuAction.setToolTipText(SHOW_HEATMAP_LEGEND_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); menuAction = new MenuAction("Show Name Panel", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource(); if (menuItem.isSelected()) { IGV.getInstance().getMainPanel().expandNamePanel(); } else { IGV.getInstance().getMainPanel().collapseNamePanel(); } IGV.getInstance().doRefresh(); } }; boolean isShowing = IGV.getInstance().getMainPanel().isExpanded(); JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(); menuItem.setSelected(isShowing); menuItem.setAction(menuAction); menuItems.add(menuItem); JMenuItem panelWidthmenuItem = new JMenuItem(); menuAction = new MenuAction("Set Name Panel Width...", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { MainPanel mainPanel = IGV.getInstance().getMainPanel(); String currentValue = String.valueOf(mainPanel.getNamePanelWidth()); String newValue = MessageUtils.showInputDialog("Enter track name panel width: ", currentValue); if (newValue != null) { try { Integer w = Integer.parseInt(newValue); if (w <= 0 || w == 1000) throw new NumberFormatException(); PreferenceManager.getInstance().put(PreferenceManager.NAME_PANEL_WIDTH, newValue); mainPanel.setNamePanelWidth(w); } catch (NumberFormatException ex) { MessageUtils.showErrorMessage("Error: value must be a positive integer < 1000.", ex); } } } }; panelWidthmenuItem.setAction(menuAction); menuItems.add(panelWidthmenuItem); // Hide or Show the attribute panels boolean isShow = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SHOW_ATTRIBUTE_VIEWS_KEY); IGV.getInstance().doShowAttributeDisplay(isShow); // <= WEIRD doing IGV.getInstance() here! menuAction = new MenuAction("Show Attribute Display", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource(); PreferenceManager.getInstance().setShowAttributeView(menuItem.getState()); IGV.getInstance().getMainPanel().invalidate(); IGV.getInstance().doRefresh(); } }; menuItem = MenuAndToolbarUtils.createMenuItem(menuAction, isShow); menuItems.add(menuItem); menuAction = new MenuAction("Select Attributes to Show...", null, KeyEvent.VK_S) { @Override public void actionPerformed(ActionEvent e) { IGV.getInstance().doSelectDisplayableAttribute(); } }; menuAction.setToolTipText(SELECT_DISPLAYABLE_ATTRIBUTES_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("Show Header Panel", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource(); if (menuItem.isSelected()) { IGV.getInstance().getMainPanel().restoreHeader(); } else { IGV.getInstance().getMainPanel().removeHeader(); } IGV.getInstance().doRefresh(); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction, true)); menuItems.add(new JSeparator()); menuAction = new MenuAction("Reorder Panels...", null, KeyEvent.VK_S) { @Override public void actionPerformed(ActionEvent e) { ReorderPanelsDialog dlg = new ReorderPanelsDialog(IGV.getMainFrame()); dlg.setVisible(true); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); menuItems.add(new HistoryMenu("Go to")); // Add to IGVPanel menu MenuAction dataMenuAction = new MenuAction("View", null, KeyEvent.VK_V); viewMenu = MenuAndToolbarUtils.createMenu(menuItems, dataMenuAction); return viewMenu; } private JMenu createRegionsMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; menuAction = new NavigateRegionsMenuAction("Region Navigator ...", IGV.getInstance()); menuAction.setToolTipText(UIConstants.REGION_NAVIGATOR_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("Gene Lists...", null, KeyEvent.VK_S) { @Override public void actionPerformed(ActionEvent e) { (GeneListManagerUI.getInstance(IGV.getMainFrame())).setVisible(true); } }; menuAction.setToolTipText("Open gene list manager"); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); // Export Regions menuAction = new ExportRegionsMenuAction("Export Regions ...", KeyEvent.VK_E, IGV.getInstance()); menuAction.setToolTipText(UIConstants.EXPORT_REGION_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Import Regions menuAction = new ImportRegionsMenuAction("Import Regions ...", KeyEvent.VK_I, IGV.getInstance()); menuAction.setToolTipText(IMPORT_REGION_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Import Regions // menuAction = new ClearRegionsMenuAction("Clear Regions ...", IGV.getInstance()); // menuAction.setToolTipText(IMPORT_REGION_TOOLTIP); // menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction dataMenuAction = new MenuAction("Regions", null, KeyEvent.VK_V); viewMenu = MenuAndToolbarUtils.createMenu(menuItems, dataMenuAction); return viewMenu; } private JMenu createHelpMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; menuAction = new MenuAction("User Guide ... ") { @Override public void actionPerformed(ActionEvent e) { try { BrowserLauncher.openURL(SERVER_BASE_URL + "igv/UserGuide"); } catch (IOException ex) { log.error("Error opening browser", ex); } } }; menuAction.setToolTipText(HELP_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); if (Desktop.isDesktopSupported()) { final Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.MAIL)) { menuAction = new MenuAction("Help Forum...") { @Override public void actionPerformed(ActionEvent e) { try { URI uri = new URI("http://groups.google.com/forum/#!forum/igv-help"); Desktop.getDesktop().browse(uri); } catch (Exception ex) { log.error("Error opening igv-help uri", ex); } } }; menuAction.setToolTipText("Email support"); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); } } menuAction = new MenuAction("Check for Updates...") { @Override public void actionPerformed(ActionEvent e) { checkVersion(); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("About IGV ") { @Override public void actionPerformed(ActionEvent e) { (new AboutDialog(IGV.getMainFrame(), true)).setVisible(true); } }; menuAction.setToolTipText(ABOUT_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction helpMenuAction = new MenuAction("Help"); return MenuAndToolbarUtils.createMenu(menuItems, helpMenuAction); } private void checkVersion() { int readTimeout = Globals.READ_TIMEOUT; int connectTimeout = Globals.CONNECT_TIMEOUT; try { Main.Version thisVersion = Main.Version.getVersion(Globals.VERSION); if (thisVersion == null) return; // Can't compare Globals.CONNECT_TIMEOUT = 5000; Globals.READ_TIMEOUT = 1000; final String serverVersionString = HttpUtils.getInstance().getContentsAsString(new URL(Globals.getVersionURL())).trim(); // See if user has specified to skip this update final String skipString = PreferenceManager.getInstance().get(PreferenceManager.SKIP_VERSION); HashSet<String> skipVersion = new HashSet<String>(Arrays.asList(skipString.split(","))); if (skipVersion.contains(serverVersionString)) return; Main.Version serverVersion = Main.Version.getVersion(serverVersionString.trim()); if (serverVersion == null) return; if (thisVersion.lessThan(serverVersion)) { log.info("A later version of IGV is available (" + serverVersionString + ")"); final VersionUpdateDialog dlg = new VersionUpdateDialog(serverVersionString); dlg.setVisible(true); if (dlg.isSkipVersion()) { String newSkipString = skipString + "," + serverVersionString; PreferenceManager.getInstance().put(PreferenceManager.SKIP_VERSION, newSkipString); } } else { MessageUtils.showMessage("IGV is up to date"); } } catch (Exception e) { log.error("Error checking version", e); } finally { Globals.CONNECT_TIMEOUT = connectTimeout; Globals.READ_TIMEOUT = readTimeout; } } private JMenu createGenomeSpaceMenu() { JMenu menu = new JMenu("GenomeSpace"); MenuAction menuAction = null; menuAction = new LoadFromGSMenuAction("Load File from GenomeSpace...", KeyEvent.VK_U, igv); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.addSeparator(); menuAction = new LoadGenomeFromGSMenuAction("Load Genome from GenomeSpace...", KeyEvent.VK_Z, igv); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.addSeparator(); menuAction = new GSSaveSessionMenuAction("Save Session to GenomeSpace...", igv); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new GSOpenSessionMenuAction("Load Session from GenomeSpace...", igv); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.add(new JSeparator()); menuAction = new MenuAction("Logout") { @Override public void actionPerformed(ActionEvent e) { GSUtils.logout(); if (MessageUtils.confirm("You must shutdown IGV to complete the GenomeSpace logout. Shutdown now?")) { doExitApplication(); } } }; menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.add(new JSeparator()); menuAction = new MenuAction("Register... ") { @Override public void actionPerformed(ActionEvent e) { try { BrowserLauncher.openURL(GENOMESPACE_REG_PAGE); } catch (IOException ex) { log.error("Error opening browser", ex); } } }; menuAction.setToolTipText(GENOMESPACE_REG_TOOLTIP); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.setVisible(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.GENOME_SPACE_ENABLE)); return menu; } private JMenu createExtrasMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; // Preferences reset menuAction = new ResetPreferencesAction("Reset Preferences", IGV.getInstance()); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); menuAction = new MenuAction("Variant list ... *EXPERIMENTAL*") { @Override public void actionPerformed(ActionEvent e) { VariantListManager.openNavigator(IGV.getMainFrame()); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); // Set frame dimensions menuAction = new MenuAction("Set window dimensions", null, KeyEvent.VK_C) { @Override public void actionPerformed(ActionEvent e) { String value = JOptionPane.showInputDialog("Enter dimensions, e.g. 800x400"); if (value != null) { String[] vals = value.split("x"); if (vals.length == 2) { int w = Integer.parseInt(vals[0]); int h = Integer.parseInt(vals[1]); IGV.getMainFrame().setSize(w, h); } } } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Save entire window menuAction = new MenuAction("Save Screenshot ...", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { IGV.getInstance().saveImage(IGV.getInstance().getContentPane()); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new ExportTrackNamesMenuAction("Export track names...", IGV.getInstance()); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("Scatter Plot ...") { @Override public void actionPerformed(ActionEvent e) { final ReferenceFrame defaultFrame = FrameManager.getDefaultFrame(); String chr = defaultFrame.getChrName(); int start = (int) defaultFrame.getOrigin(); int end = (int) defaultFrame.getEnd(); int zoom = defaultFrame.getZoom(); ScatterPlotUtils.openPlot(chr, start, end, zoom); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction extrasMenuAction = new MenuAction("Extras"); JMenu menu = MenuAndToolbarUtils.createMenu(menuItems, extrasMenuAction); // JMenu lfMenu = new JMenu("L&F"); LookAndFeel lf = UIManager.getLookAndFeel(); for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { final String lfName = info.getName(); JMenuItem cb = new JMenuItem(lfName); //cb.setSelected(info.getClassName().equals(lf.getClass().getName()); cb.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if (lfName.equals(info.getName())) { try { UIManager.setLookAndFeel(info.getClassName()); } catch (Exception e) { e.printStackTrace(); } break; } } } }); lfMenu.add(cb); } menu.add(lfMenu); menu.setVisible(false); return menu; } private JMenu createGoogleMenu() { final JMenu menu = new JMenu("Google"); final JMenuItem login = new JMenuItem("Login ... "); login.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { OAuthUtils.getInstance().openAuthorizationPage(); } catch (Exception ex) { MessageUtils.showErrorMessage("Error fetching oAuth tokens. See log for details", ex); log.error("Error fetching oAuth tokens", ex); } } }); login.setEnabled(false); menu.add(login); final JMenuItem logout = new JMenuItem("Logout "); logout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { OAuthUtils.getInstance().logout(); } }); logout.setEnabled(false); menu.add(logout); final JMenuItem loadReadset = new JMenuItem("Load Genomics ReadGroupSet... "); loadReadset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String readsetId = MessageUtils.showInputDialog("Enter ReadGroupSet ID (e.g. CMvnhpKTFhCjz9_25e_lCw): "); if (readsetId != null) { ResourceLocator locator = new ResourceLocator(readsetId); locator.setName(readsetId); locator.setType(Ga4ghAPIHelper.RESOURCE_TYPE); locator.setAttribute("provider", Ga4ghAPIHelper.GA4GH_GOOGLE_PROVIDER); IGV.getInstance().loadTracks(Arrays.asList(locator)); } } }); loadReadset.setEnabled(false); menu.add(loadReadset); menu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { Runnable runnable = new Runnable() { @Override public void run() { boolean loggedIn = OAuthUtils.getInstance().isLoggedIn(); if (loggedIn) { login.setText(OAuthUtils.getInstance().getCurrentUserName()); } else { login.setText("Login ..."); } login.setEnabled(!loggedIn); logout.setEnabled(loggedIn); loadReadset.setEnabled(loggedIn); } }; LongRunningTask.submit(runnable); } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); return menu; } // public void enableRemoveGenomes() { // if (removeImportedGenomeAction != null) { // removeImportedGenomeAction.setEnabled(true); // } // } public void resetSessionActions() { if (filterTracksAction != null) { filterTracksAction.resetTrackFilter(); } } public void setFilterMatchAll(boolean value) { if (filterTracksAction != null) { filterTracksAction.setFilterMatchAll(value); } } public boolean isFilterMatchAll() { if (filterTracksAction != null) { return filterTracksAction.isFilterMatchAll(); } return false; } public void setFilterShowAllTracks(boolean value) { if (filterTracksAction != null) { filterTracksAction.setFilterShowAllTracks(value); } } public boolean isFilterShowAllTracks() { if (filterTracksAction != null) { return filterTracksAction.getShowAllTracksFilterCheckBox().isSelected(); } return false; } public JMenu getViewMenu() { return viewMenu; } final public void doExitApplication() { try { IGV.getInstance().saveStateForExit(); Frame mainFrame = IGV.getMainFrame(); // Hide and close the application mainFrame.setVisible(false); mainFrame.dispose(); } finally { System.exit(0); } } @ForTesting static void destroyInstance() { instance = null; } public void enableGoogleMenu(boolean aBoolean) { googleMenu.setVisible(aBoolean); } }
src/org/broad/igv/ui/IGVMenuBar.java
/* * The MIT License (MIT) * * Copyright (c) 2007-2015 Broad Institute * * 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. */ package org.broad.igv.ui; import apple.dts.samplecode.osxadapter.OSXAdapter; import org.apache.log4j.Logger; import org.broad.igv.DirectoryManager; import org.broad.igv.Globals; import org.broad.igv.PreferenceManager; import org.broad.igv.annotations.ForTesting; import org.broad.igv.charts.ScatterPlotUtils; import org.broad.igv.cli_plugin.PluginSpecReader; import org.broad.igv.cli_plugin.ui.RunPlugin; import org.broad.igv.cli_plugin.ui.SetPluginPathDialog; import org.broad.igv.dev.db.DBProfileEditor; import org.broad.igv.feature.genome.GenomeListItem; import org.broad.igv.feature.genome.GenomeManager; import org.broad.igv.ga4gh.Ga4ghAPIHelper; import org.broad.igv.ga4gh.OAuthUtils; import org.broad.igv.gs.GSOpenSessionMenuAction; import org.broad.igv.gs.GSSaveSessionMenuAction; import org.broad.igv.gs.GSUtils; import org.broad.igv.lists.GeneListManagerUI; import org.broad.igv.lists.VariantListManager; import org.broad.igv.tools.IgvToolsGui; import org.broad.igv.track.CombinedDataSourceDialog; import org.broad.igv.ui.action.*; import org.broad.igv.ui.legend.LegendDialog; import org.broad.igv.ui.panel.FrameManager; import org.broad.igv.ui.panel.MainPanel; import org.broad.igv.ui.panel.ReferenceFrame; import org.broad.igv.ui.panel.ReorderPanelsDialog; import org.broad.igv.ui.util.*; import org.broad.igv.util.*; import org.broad.igv.util.encode.EncodeFileBrowser; import javax.swing.*; import javax.swing.event.MenuEvent; import javax.swing.event.MenuListener; import javax.swing.plaf.basic.BasicBorders; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import static org.broad.igv.ui.UIConstants.*; /** * Main menu bar at top of window. File / genomes / view / etc. * Singleton * * @author jrobinso * @date Apr 4, 2011 */ public class IGVMenuBar extends JMenuBar { private static Logger log = Logger.getLogger(IGVMenuBar.class); public static final String GENOMESPACE_REG_TOOLTIP = "Register for GenomeSpace"; public static final String GENOMESPACE_REG_PAGE = "http://www.genomespace.org/register"; private JMenu fileMenu; private JMenu extrasMenu; private FilterTracksMenuAction filterTracksAction; private JMenu viewMenu; IGV igv; private JMenu toolsMenu; /** * We store this as a field because we alter it if * we can't access genome server list */ private JMenuItem loadFromServerMenuItem; private static final String LOAD_GENOME_SERVER_TOOLTIP = "Select genomes available on the server to appear in menu."; private static final String CANNOT_LOAD_GENOME_SERVER_TOOLTIP = "Could not reach genome server"; private static IGVMenuBar instance; private JMenu googleMenu; public void notifyGenomeServerReachable(boolean reachable) { if (loadFromServerMenuItem != null) { loadFromServerMenuItem.setEnabled(reachable); String tooltip = reachable ? LOAD_GENOME_SERVER_TOOLTIP : CANNOT_LOAD_GENOME_SERVER_TOOLTIP; loadFromServerMenuItem.setToolTipText(tooltip); } } public void showAboutDialog() { (new AboutDialog(IGV.getMainFrame(), true)).setVisible(true); } static IGVMenuBar createInstance(IGV igv) { if (instance != null) { if (igv == instance.igv) { return instance; } throw new IllegalStateException("Cannot create another IGVMenuBar, use getInstance"); } instance = new IGVMenuBar(igv); return instance; } public static IGVMenuBar getInstance() { return instance; } private IGVMenuBar(IGV igv) { this.igv = igv; setBorder(new BasicBorders.MenuBarBorder(Color.GRAY, Color.GRAY)); setBorderPainted(true); for (AbstractButton menu : createMenus()) { add(menu); } //This is for Macs, so showing the about dialog //from the command bar does what we want. if (Globals.IS_MAC) { try { OSXAdapter.setAboutHandler(this, getClass().getDeclaredMethod("showAboutDialog", (Class[]) null)); OSXAdapter.setQuitHandler(ShutdownThread.class, ShutdownThread.class.getDeclaredMethod("runS", (Class[]) null)); } catch (Exception e) { log.error("Error setting apple-specific about and quit handlers", e); } } } private List<AbstractButton> createMenus() { List<AbstractButton> menus = new ArrayList<AbstractButton>(); createFileMenu(); menus.add(fileMenu); menus.add(createGenomesMenu()); menus.add(createViewMenu()); menus.add(createTracksMenu()); menus.add(createRegionsMenu()); refreshToolsMenu(); menus.add(toolsMenu); menus.add(createGenomeSpaceMenu()); extrasMenu = createExtrasMenu(); //extrasMenu.setVisible(false); menus.add(extrasMenu); if(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.ENABLE_GOOGLE_MENU)) { menus.add(createGoogleMenu()); } menus.add(createHelpMenu()); // Experimental -- remove for production release return menus; } /** * Generate the "tools" menu. * This is imperative, it is written to field {@code toolsMenu}. * Reason being, when we add (TODO remove) * a new tool, we need to refresh just this menu */ void refreshToolsMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(10); // batch script MenuAction menuAction = new RunScriptMenuAction("Run Batch Script...", KeyEvent.VK_X, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // igvtools //menuItems.add(new JSeparator()); menuAction = new SortTracksMenuAction("Run igvtools...", KeyEvent.VK_T, igv) { @Override public void actionPerformed(ActionEvent e) { IgvToolsGui.launch(false, igv.getGenomeManager().getGenomeId()); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); List<JComponent> otherToolMenus = igv.getOtherToolMenus(); if (otherToolMenus.size() > 0) { for (JComponent entry : otherToolMenus) { menuItems.add(entry); } } //menuItems.add(new JSeparator()); //-------------------------------------// //"Add tool" option, for loading cli_plugin from someplace else JMenuItem addTool = new JMenuItem("Add Tool..."); addTool.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File pluginFi = FileDialogUtils.chooseFile("Select cli_plugin .xml spec"); if (pluginFi == null) return; try { PluginSpecReader.addCustomPlugin(pluginFi.getAbsolutePath()); refreshToolsMenu(); } catch (IOException e1) { MessageUtils.showErrorMessage("Error loading custom cli_plugin", e1); } } }); //menuItems.add(addTool); //menuItems.add(new JSeparator()); //-------------------------------------// for (final PluginSpecReader pluginSpecReader : PluginSpecReader.getPlugins()) { for (final PluginSpecReader.Tool tool : pluginSpecReader.getTools()) { final String toolName = tool.name; boolean toolVisible = tool.visible; JMenuItem toolMenu; if (toolVisible) { final String toolPath = pluginSpecReader.getToolPath(tool); final String tool_url = tool.toolUrl; boolean isValid = PluginSpecReader.isToolPathValid(toolPath); ActionListener invalidActionListener = new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String msg = String.format("%s executable not found at %s", toolName, toolPath); if (tool_url != null) { msg += "<br/>See " + tool_url + " to install"; } MessageUtils.showMessage(msg); } }; toolMenu = new JMenu(toolName); //Kind of overlaps with the side-pull menu, doesn't look great //toolMenu.setToolTipText(tool.getAttribute("description")); for (final PluginSpecReader.Command command : tool.commandList) { final String cmdName = command.name; JMenuItem cmdItem = new JMenuItem(cmdName); toolMenu.add(cmdItem); if (isValid || toolPath == null) { cmdItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { RunPlugin runPlugin = null; try { runPlugin = new RunPlugin(IGV.getMainFrame(), pluginSpecReader, tool, command); } catch (IllegalStateException e1) { MessageUtils.showErrorMessage(e1.getMessage(), e1); return; } runPlugin.setVisible(true); } }); cmdItem.setEnabled(true); } else { cmdItem.setEnabled(false); } } //Hack so we can have a tool which is just general command line stuff //Don't let the user change the path in that case if (tool.defaultPath != null) { JMenuItem setPathItem = new JMenuItem(String.format("Set path to %s...", toolName)); setPathItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { (new SetPluginPathDialog(IGV.getMainFrame(), pluginSpecReader, tool)).setVisible(true); refreshToolsMenu(); } }); toolMenu.add(setPathItem); } menuItems.add(toolMenu); } } } //-------------------------------------// //-----------SQL DB Tools--------------// boolean showDBEditor = Globals.isDevelopment(); if (showDBEditor) { JMenu sqlDBProfileEditor = new JMenu("SQL DB Profile Editor"); JMenuItem createNewProfile = new JMenuItem("Create New Profile"); createNewProfile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File file = FileDialogUtils.chooseFile("Save DB Profile", DirectoryManager.getUserDirectory(), FileDialogUtils.SAVE); if (file != null) { DBProfileEditor editor = new DBProfileEditor(IGV.getMainFrame(), file.getAbsolutePath()); editor.setVisible(true); } } }); JMenuItem editExistingProfile = new JMenuItem("Edit Existing Profile"); editExistingProfile.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { File file = FileDialogUtils.chooseFile("Select .dbxml database profile"); if (file != null) { if (!file.exists()) { } DBProfileEditor editor = new DBProfileEditor(IGV.getMainFrame(), file.getAbsolutePath()); editor.setVisible(true); } } }); sqlDBProfileEditor.add(createNewProfile); sqlDBProfileEditor.add(editExistingProfile); menuItems.add(sqlDBProfileEditor); } //-------------------------------------// //DataTrack Math------------------------// JMenuItem combineDataItem = new JMenuItem("Combine Data Tracks"); combineDataItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { CombinedDataSourceDialog dialog = new CombinedDataSourceDialog(IGV.getMainFrame()); dialog.setVisible(true); } }); menuItems.add(combineDataItem); //-------------------------------------// MenuAction toolsMenuAction = new MenuAction("Tools", null); if (toolsMenu == null) { toolsMenu = MenuAndToolbarUtils.createMenu(menuItems, toolsMenuAction); toolsMenu.setName("Tools"); } else { toolsMenu.removeAll(); for (JComponent item : menuItems) { toolsMenu.add(item); } } } public void enableExtrasMenu() { extrasMenu.setVisible(true); } void createFileMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; //We disable certain load items when there is no genome. boolean genomeLoaded = GenomeManager.getInstance().getCurrentGenome() != null; menuItems.add(new JSeparator()); // Load menu items menuAction = new LoadFilesMenuAction("Load from File...", KeyEvent.VK_L, igv); menuAction.setToolTipText(UIConstants.LOAD_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new LoadFromURLMenuAction(LoadFromURLMenuAction.LOAD_FROM_URL, KeyEvent.VK_U, igv); menuAction.setToolTipText(UIConstants.LOAD_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new LoadFromServerAction("Load from Server...", KeyEvent.VK_S, igv); menuAction.setToolTipText(UIConstants.LOAD_SERVER_DATA_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new LoadFromURLMenuAction(LoadFromURLMenuAction.LOAD_FROM_DAS, KeyEvent.VK_D, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); if (PreferenceManager.getInstance().getAsBoolean(PreferenceManager.DB_ENABLED)) { menuAction = new LoadFromDatabaseAction("Load from Database...", 0, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); } String genomeId = IGV.getInstance().getGenomeManager().getGenomeId(); if (EncodeFileBrowser.genomeSupported(genomeId)) { menuAction = new BrowseEncodeAction("Load from ENCODE...", KeyEvent.VK_E, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); } menuAction = new BrowseGa4ghAction("Load from Ga4gh...", KeyEvent.VK_G, igv); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); //Disable loading if no genome loaded. Something of an edge case if (!genomeLoaded) { for (JComponent menuItem : menuItems) { menuItem.setEnabled(false); } } menuItems.add(new JSeparator()); // Session menu items menuAction = new NewSessionMenuAction("New Session...", KeyEvent.VK_N, igv); menuAction.setToolTipText(UIConstants.NEW_SESSION_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new OpenSessionMenuAction("Open Session...", KeyEvent.VK_O, igv); menuAction.setToolTipText(UIConstants.RESTORE_SESSION_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new SaveSessionMenuAction("Save Session...", KeyEvent.VK_V, igv); menuAction.setToolTipText(UIConstants.SAVE_SESSION_TOOLTIP); JMenuItem saveSessionItem = MenuAndToolbarUtils.createMenuItem(menuAction); menuItems.add(saveSessionItem); saveSessionItem.setEnabled(genomeLoaded); menuItems.add(new JSeparator()); // ***** Snapshots // Snapshot Application menuAction = new MenuAction("Save Image ...", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { igv.saveImage(igv.getMainPanel()); } }; menuAction.setToolTipText(SAVE_IMAGE_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // TODO -- change "Exit" to "Close" for BioClipse menuItems.add(new JSeparator()); // Exit menuAction = new MenuAction("Exit", null, KeyEvent.VK_X) { @Override public void actionPerformed(ActionEvent e) { doExitApplication(); } }; menuAction.setToolTipText(EXIT_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Empty the recent sessions list before we start to do // anything with it igv.getRecentSessionList().clear(); // Retrieve the stored session paths String recentSessions = PreferenceManager.getInstance().getRecentSessions(); if (recentSessions != null) { String[] sessions = recentSessions.split(";"); for (String sessionPath : sessions) { if (!igv.getRecentSessionList().contains(sessionPath)) { igv.getRecentSessionList().add(sessionPath); } } } if (!IGV.getInstance().getRecentSessionList().isEmpty()) { menuItems.add(new JSeparator()); // Now add menu items for (final String session : IGV.getInstance().getRecentSessionList()) { OpenSessionMenuAction osMenuAction = new OpenSessionMenuAction(session, session, IGV.getInstance()); menuItems.add(MenuAndToolbarUtils.createMenuItem(osMenuAction)); } } MenuAction fileMenuAction = new MenuAction("File", null, KeyEvent.VK_F); if (fileMenu == null) { fileMenu = MenuAndToolbarUtils.createMenu(menuItems, fileMenuAction); } else { fileMenu.removeAll(); for (JComponent item : menuItems) { fileMenu.add(item); } } } private void notifyGenomesAddedRemoved(List<GenomeListItem> selectedValues, boolean added) { if (selectedValues == null || selectedValues.size() == 0) return; int size = selectedValues.size(); String msg = ""; if (size == 1) { msg += selectedValues.get(0) + " genome"; } else { msg += size + " genomes"; } if (added) { msg += " added to"; } else { msg += " removed from"; } msg += " list"; MessageUtils.setStatusBarMessage(msg); } private JMenu createGenomesMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; // Load genome menuAction = new MenuAction("Load Genome from File...", null, KeyEvent.VK_I) { @Override public void actionPerformed(ActionEvent event) { try { org.broad.igv.ui.util.ProgressMonitor monitor = new org.broad.igv.ui.util.ProgressMonitor(); igv.doLoadGenome(monitor); } catch (Exception e) { MessageUtils.showErrorMessage(e.getMessage(), e); } } }; menuAction.setToolTipText("Load a FASTA or .genome file..."); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Load genome from URL menuAction = new LoadFromURLMenuAction(LoadFromURLMenuAction.LOAD_GENOME_FROM_URL, 0, igv); menuAction.setToolTipText("Load a FASTA or .genome file..."); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Add genome to combo box from server menuAction = new MenuAction("Load Genome From Server...", null) { @Override public void actionPerformed(ActionEvent event) { IGV.getInstance().loadGenomeFromServerAction(); } }; menuAction.setToolTipText(LOAD_GENOME_SERVER_TOOLTIP); loadFromServerMenuItem = MenuAndToolbarUtils.createMenuItem(menuAction); menuItems.add(loadFromServerMenuItem); menuItems.add(new JSeparator()); menuAction = new MenuAction("Create .genome File...", null, KeyEvent.VK_D) { @Override public void actionPerformed(ActionEvent event) { org.broad.igv.ui.util.ProgressMonitor monitor = new org.broad.igv.ui.util.ProgressMonitor(); igv.doDefineGenome(monitor); } }; menuAction.setToolTipText(UIConstants.IMPORT_GENOME_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); // Add genome to combo box from server menuAction = new MenuAction("Manage Genome List...", null) { @Override public void actionPerformed(ActionEvent event) { ManageGenomesDialog dialog2 = new ManageGenomesDialog(IGV.getMainFrame()); dialog2.setVisible(true); boolean cancelled = dialog2.isCancelled(); List<GenomeListItem> removedValuesList = dialog2.getRemovedValuesList(); if (!cancelled) { GenomeManager.getInstance().buildGenomeItemList(); igv.getContentPane().getCommandBar().refreshGenomeListComboBox(); if (removedValuesList != null && !removedValuesList.isEmpty()) { try { GenomeManager.getInstance().deleteDownloadedGenomes(removedValuesList); } catch (IOException e) { MessageUtils.showErrorMessage("Error deleting genome files", e); } GenomeManager.getInstance().updateImportedGenomePropertyFile(); notifyGenomesAddedRemoved(removedValuesList, false); } } } }; menuAction.setToolTipText("Add, remove, or reorder genomes which appear in the dropdown list"); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction genomeMenuAction = new MenuAction("Genomes", null); return MenuAndToolbarUtils.createMenu(menuItems, genomeMenuAction); } private JMenu createTracksMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; // Sort Context menuAction = new SortTracksMenuAction("Sort Tracks...", KeyEvent.VK_S, IGV.getInstance()); menuAction.setToolTipText(SORT_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new GroupTracksMenuAction("Group Tracks... ", KeyEvent.VK_G, IGV.getInstance()); menuAction.setToolTipText(UIConstants.GROUP_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Filter Tracks filterTracksAction = new FilterTracksMenuAction("Filter Tracks...", KeyEvent.VK_F, IGV.getInstance()); filterTracksAction.setToolTipText(UIConstants.FILTER_TRACKS_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(filterTracksAction)); menuItems.add(new JSeparator()); // Reset Tracks menuAction = new FitDataToWindowMenuAction("Fit Data to Window", KeyEvent.VK_W, IGV.getInstance()); menuAction.setToolTipText(UIConstants.FIT_DATA_TO_WINDOW_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Set track height menuAction = new SetTrackHeightMenuAction("Set Track Height...", KeyEvent.VK_H, IGV.getInstance()); menuAction.setToolTipText(UIConstants.SET_DEFAULT_TRACK_HEIGHT_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction dataMenuAction = new MenuAction("Tracks", null, KeyEvent.VK_K); //menuItems.add(exportData); return MenuAndToolbarUtils.createMenu(menuItems, dataMenuAction); } private JMenu createViewMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; // Preferences menuAction = new MenuAction("Preferences...", null, KeyEvent.VK_P) { @Override public void actionPerformed(ActionEvent e) { UIUtilities.invokeOnEventThread(new Runnable() { public void run() { IGV.getInstance().doViewPreferences(); } }); } }; menuAction.setToolTipText(PREFERENCE_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("Color Legends ...", null, KeyEvent.VK_H) { @Override public void actionPerformed(ActionEvent e) { (new LegendDialog(IGV.getMainFrame())).setVisible(true); } }; menuAction.setToolTipText(SHOW_HEATMAP_LEGEND_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); menuAction = new MenuAction("Show Name Panel", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource(); if (menuItem.isSelected()) { IGV.getInstance().getMainPanel().expandNamePanel(); } else { IGV.getInstance().getMainPanel().collapseNamePanel(); } IGV.getInstance().doRefresh(); } }; boolean isShowing = IGV.getInstance().getMainPanel().isExpanded(); JCheckBoxMenuItem menuItem = new JCheckBoxMenuItem(); menuItem.setSelected(isShowing); menuItem.setAction(menuAction); menuItems.add(menuItem); JMenuItem panelWidthmenuItem = new JMenuItem(); menuAction = new MenuAction("Set Name Panel Width...", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { MainPanel mainPanel = IGV.getInstance().getMainPanel(); String currentValue = String.valueOf(mainPanel.getNamePanelWidth()); String newValue = MessageUtils.showInputDialog("Enter track name panel width: ", currentValue); if (newValue != null) { try { Integer w = Integer.parseInt(newValue); if (w <= 0 || w == 1000) throw new NumberFormatException(); PreferenceManager.getInstance().put(PreferenceManager.NAME_PANEL_WIDTH, newValue); mainPanel.setNamePanelWidth(w); } catch (NumberFormatException ex) { MessageUtils.showErrorMessage("Error: value must be a positive integer < 1000.", ex); } } } }; panelWidthmenuItem.setAction(menuAction); menuItems.add(panelWidthmenuItem); // Hide or Show the attribute panels boolean isShow = PreferenceManager.getInstance().getAsBoolean(PreferenceManager.SHOW_ATTRIBUTE_VIEWS_KEY); IGV.getInstance().doShowAttributeDisplay(isShow); // <= WEIRD doing IGV.getInstance() here! menuAction = new MenuAction("Show Attribute Display", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource(); PreferenceManager.getInstance().setShowAttributeView(menuItem.getState()); IGV.getInstance().getMainPanel().invalidate(); IGV.getInstance().doRefresh(); } }; menuItem = MenuAndToolbarUtils.createMenuItem(menuAction, isShow); menuItems.add(menuItem); menuAction = new MenuAction("Select Attributes to Show...", null, KeyEvent.VK_S) { @Override public void actionPerformed(ActionEvent e) { IGV.getInstance().doSelectDisplayableAttribute(); } }; menuAction.setToolTipText(SELECT_DISPLAYABLE_ATTRIBUTES_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("Show Header Panel", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { JCheckBoxMenuItem menuItem = (JCheckBoxMenuItem) e.getSource(); if (menuItem.isSelected()) { IGV.getInstance().getMainPanel().restoreHeader(); } else { IGV.getInstance().getMainPanel().removeHeader(); } IGV.getInstance().doRefresh(); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction, true)); menuItems.add(new JSeparator()); menuAction = new MenuAction("Reorder Panels...", null, KeyEvent.VK_S) { @Override public void actionPerformed(ActionEvent e) { ReorderPanelsDialog dlg = new ReorderPanelsDialog(IGV.getMainFrame()); dlg.setVisible(true); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); menuItems.add(new HistoryMenu("Go to")); // Add to IGVPanel menu MenuAction dataMenuAction = new MenuAction("View", null, KeyEvent.VK_V); viewMenu = MenuAndToolbarUtils.createMenu(menuItems, dataMenuAction); return viewMenu; } private JMenu createRegionsMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; menuAction = new NavigateRegionsMenuAction("Region Navigator ...", IGV.getInstance()); menuAction.setToolTipText(UIConstants.REGION_NAVIGATOR_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("Gene Lists...", null, KeyEvent.VK_S) { @Override public void actionPerformed(ActionEvent e) { (GeneListManagerUI.getInstance(IGV.getMainFrame())).setVisible(true); } }; menuAction.setToolTipText("Open gene list manager"); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); // Export Regions menuAction = new ExportRegionsMenuAction("Export Regions ...", KeyEvent.VK_E, IGV.getInstance()); menuAction.setToolTipText(UIConstants.EXPORT_REGION_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Import Regions menuAction = new ImportRegionsMenuAction("Import Regions ...", KeyEvent.VK_I, IGV.getInstance()); menuAction.setToolTipText(IMPORT_REGION_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Import Regions // menuAction = new ClearRegionsMenuAction("Clear Regions ...", IGV.getInstance()); // menuAction.setToolTipText(IMPORT_REGION_TOOLTIP); // menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction dataMenuAction = new MenuAction("Regions", null, KeyEvent.VK_V); viewMenu = MenuAndToolbarUtils.createMenu(menuItems, dataMenuAction); return viewMenu; } private JMenu createHelpMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; menuAction = new MenuAction("User Guide ... ") { @Override public void actionPerformed(ActionEvent e) { try { BrowserLauncher.openURL(SERVER_BASE_URL + "igv/UserGuide"); } catch (IOException ex) { log.error("Error opening browser", ex); } } }; menuAction.setToolTipText(HELP_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); if (Desktop.isDesktopSupported()) { final Desktop desktop = Desktop.getDesktop(); if (desktop.isSupported(Desktop.Action.MAIL)) { menuAction = new MenuAction("Help Forum...") { @Override public void actionPerformed(ActionEvent e) { try { URI uri = new URI("http://groups.google.com/forum/#!forum/igv-help"); Desktop.getDesktop().browse(uri); } catch (Exception ex) { log.error("Error opening igv-help uri", ex); } } }; menuAction.setToolTipText("Email support"); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); } } menuAction = new MenuAction("Check for Updates...") { @Override public void actionPerformed(ActionEvent e) { checkVersion(); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("About IGV ") { @Override public void actionPerformed(ActionEvent e) { (new AboutDialog(IGV.getMainFrame(), true)).setVisible(true); } }; menuAction.setToolTipText(ABOUT_TOOLTIP); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction helpMenuAction = new MenuAction("Help"); return MenuAndToolbarUtils.createMenu(menuItems, helpMenuAction); } private void checkVersion() { int readTimeout = Globals.READ_TIMEOUT; int connectTimeout = Globals.CONNECT_TIMEOUT; try { Main.Version thisVersion = Main.Version.getVersion(Globals.VERSION); if (thisVersion == null) return; // Can't compare Globals.CONNECT_TIMEOUT = 5000; Globals.READ_TIMEOUT = 1000; final String serverVersionString = HttpUtils.getInstance().getContentsAsString(new URL(Globals.getVersionURL())).trim(); // See if user has specified to skip this update final String skipString = PreferenceManager.getInstance().get(PreferenceManager.SKIP_VERSION); HashSet<String> skipVersion = new HashSet<String>(Arrays.asList(skipString.split(","))); if (skipVersion.contains(serverVersionString)) return; Main.Version serverVersion = Main.Version.getVersion(serverVersionString.trim()); if (serverVersion == null) return; if (thisVersion.lessThan(serverVersion)) { log.info("A later version of IGV is available (" + serverVersionString + ")"); final VersionUpdateDialog dlg = new VersionUpdateDialog(serverVersionString); dlg.setVisible(true); if (dlg.isSkipVersion()) { String newSkipString = skipString + "," + serverVersionString; PreferenceManager.getInstance().put(PreferenceManager.SKIP_VERSION, newSkipString); } } else { MessageUtils.showMessage("IGV is up to date"); } } catch (Exception e) { log.error("Error checking version", e); } finally { Globals.CONNECT_TIMEOUT = connectTimeout; Globals.READ_TIMEOUT = readTimeout; } } private JMenu createGenomeSpaceMenu() { JMenu menu = new JMenu("GenomeSpace"); MenuAction menuAction = null; menuAction = new LoadFromGSMenuAction("Load File from GenomeSpace...", KeyEvent.VK_U, igv); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.addSeparator(); menuAction = new LoadGenomeFromGSMenuAction("Load Genome from GenomeSpace...", KeyEvent.VK_Z, igv); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.addSeparator(); menuAction = new GSSaveSessionMenuAction("Save Session to GenomeSpace...", igv); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new GSOpenSessionMenuAction("Load Session from GenomeSpace...", igv); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.add(new JSeparator()); menuAction = new MenuAction("Logout") { @Override public void actionPerformed(ActionEvent e) { GSUtils.logout(); if (MessageUtils.confirm("You must shutdown IGV to complete the GenomeSpace logout. Shutdown now?")) { doExitApplication(); } } }; menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.add(new JSeparator()); menuAction = new MenuAction("Register... ") { @Override public void actionPerformed(ActionEvent e) { try { BrowserLauncher.openURL(GENOMESPACE_REG_PAGE); } catch (IOException ex) { log.error("Error opening browser", ex); } } }; menuAction.setToolTipText(GENOMESPACE_REG_TOOLTIP); menu.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menu.setVisible(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.GENOME_SPACE_ENABLE)); return menu; } private JMenu createExtrasMenu() { List<JComponent> menuItems = new ArrayList<JComponent>(); MenuAction menuAction = null; // Preferences reset menuAction = new ResetPreferencesAction("Reset Preferences", IGV.getInstance()); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); menuAction = new MenuAction("Variant list ... *EXPERIMENTAL*") { @Override public void actionPerformed(ActionEvent e) { VariantListManager.openNavigator(IGV.getMainFrame()); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuItems.add(new JSeparator()); // Set frame dimensions menuAction = new MenuAction("Set window dimensions", null, KeyEvent.VK_C) { @Override public void actionPerformed(ActionEvent e) { String value = JOptionPane.showInputDialog("Enter dimensions, e.g. 800x400"); if (value != null) { String[] vals = value.split("x"); if (vals.length == 2) { int w = Integer.parseInt(vals[0]); int h = Integer.parseInt(vals[1]); IGV.getMainFrame().setSize(w, h); } } } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); // Save entire window menuAction = new MenuAction("Save Screenshot ...", null, KeyEvent.VK_A) { @Override public void actionPerformed(ActionEvent e) { IGV.getInstance().saveImage(IGV.getInstance().getContentPane()); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new ExportTrackNamesMenuAction("Export track names...", IGV.getInstance()); menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); menuAction = new MenuAction("Scatter Plot ...") { @Override public void actionPerformed(ActionEvent e) { final ReferenceFrame defaultFrame = FrameManager.getDefaultFrame(); String chr = defaultFrame.getChrName(); int start = (int) defaultFrame.getOrigin(); int end = (int) defaultFrame.getEnd(); int zoom = defaultFrame.getZoom(); ScatterPlotUtils.openPlot(chr, start, end, zoom); } }; menuItems.add(MenuAndToolbarUtils.createMenuItem(menuAction)); MenuAction extrasMenuAction = new MenuAction("Extras"); JMenu menu = MenuAndToolbarUtils.createMenu(menuItems, extrasMenuAction); // JMenu lfMenu = new JMenu("L&F"); LookAndFeel lf = UIManager.getLookAndFeel(); for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { final String lfName = info.getName(); JMenuItem cb = new JMenuItem(lfName); //cb.setSelected(info.getClassName().equals(lf.getClass().getName()); cb.addActionListener(new AbstractAction() { public void actionPerformed(ActionEvent actionEvent) { for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if (lfName.equals(info.getName())) { try { UIManager.setLookAndFeel(info.getClassName()); } catch (Exception e) { e.printStackTrace(); } break; } } } }); lfMenu.add(cb); } menu.add(lfMenu); menu.setVisible(false); return menu; } private JMenu createGoogleMenu() { final JMenu menu = new JMenu("Google"); final JMenuItem login = new JMenuItem("Login ... "); login.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { OAuthUtils.getInstance().openAuthorizationPage(); } catch (Exception ex) { MessageUtils.showErrorMessage("Error fetching oAuth tokens. See log for details", ex); log.error("Error fetching oAuth tokens", ex); } } }); login.setEnabled(false); menu.add(login); final JMenuItem logout = new JMenuItem("Logout "); logout.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { OAuthUtils.getInstance().logout(); } }); logout.setEnabled(false); menu.add(logout); final JMenuItem loadReadset = new JMenuItem("Load Genomics ReadGroupSet... "); loadReadset.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { String readsetId = MessageUtils.showInputDialog("Enter ReadGroupSet ID (e.g. CMvnhpKTFhCjz9_25e_lCw): "); if (readsetId != null) { ResourceLocator locator = new ResourceLocator(readsetId); locator.setName(readsetId); locator.setType(Ga4ghAPIHelper.RESOURCE_TYPE); locator.setAttribute("provider", Ga4ghAPIHelper.GA4GH_GOOGLE_PROVIDER); IGV.getInstance().loadTracks(Arrays.asList(locator)); } } }); loadReadset.setEnabled(false); menu.add(loadReadset); menu.addMenuListener(new MenuListener() { @Override public void menuSelected(MenuEvent e) { Runnable runnable = new Runnable() { @Override public void run() { boolean loggedIn = OAuthUtils.getInstance().isLoggedIn(); if (loggedIn) { login.setText(OAuthUtils.getInstance().getCurrentUserName()); } else { login.setText("Login ..."); } login.setEnabled(!loggedIn); logout.setEnabled(loggedIn); loadReadset.setEnabled(loggedIn); } }; LongRunningTask.submit(runnable); } @Override public void menuDeselected(MenuEvent e) { } @Override public void menuCanceled(MenuEvent e) { } }); return menu; } // public void enableRemoveGenomes() { // if (removeImportedGenomeAction != null) { // removeImportedGenomeAction.setEnabled(true); // } // } public void resetSessionActions() { if (filterTracksAction != null) { filterTracksAction.resetTrackFilter(); } } public void setFilterMatchAll(boolean value) { if (filterTracksAction != null) { filterTracksAction.setFilterMatchAll(value); } } public boolean isFilterMatchAll() { if (filterTracksAction != null) { return filterTracksAction.isFilterMatchAll(); } return false; } public void setFilterShowAllTracks(boolean value) { if (filterTracksAction != null) { filterTracksAction.setFilterShowAllTracks(value); } } public boolean isFilterShowAllTracks() { if (filterTracksAction != null) { return filterTracksAction.getShowAllTracksFilterCheckBox().isSelected(); } return false; } public JMenu getViewMenu() { return viewMenu; } final public void doExitApplication() { try { IGV.getInstance().saveStateForExit(); Frame mainFrame = IGV.getMainFrame(); // Hide and close the application mainFrame.setVisible(false); mainFrame.dispose(); } finally { System.exit(0); } } @ForTesting static void destroyInstance() { instance = null; } public void enableGoogleMenu(boolean aBoolean) { googleMenu.setVisible(aBoolean); } }
Google menu bug fix
src/org/broad/igv/ui/IGVMenuBar.java
Google menu bug fix
<ide><path>rc/org/broad/igv/ui/IGVMenuBar.java <ide> //extrasMenu.setVisible(false); <ide> menus.add(extrasMenu); <ide> <del> if(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.ENABLE_GOOGLE_MENU)) { <del> menus.add(createGoogleMenu()); <del> } <add> googleMenu = createGoogleMenu(); <add> googleMenu.setVisible(PreferenceManager.getInstance().getAsBoolean(PreferenceManager.ENABLE_GOOGLE_MENU)); <add> menus.add(googleMenu); <ide> <ide> menus.add(createHelpMenu()); <ide>
Java
epl-1.0
57007622aae8b67b0c245d0a8389717dbfda3a67
0
Beagle-PSE/Beagle,Beagle-PSE/Beagle,Beagle-PSE/Beagle
package de.uka.ipd.sdq.beagle.core.judge; import de.uka.ipd.sdq.beagle.core.Blackboard; import de.uka.ipd.sdq.beagle.core.MeasurableSeffElement; import de.uka.ipd.sdq.beagle.core.SeffBranch; import de.uka.ipd.sdq.beagle.core.analysis.ProposedExpressionAnalyserBlackboardView; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.Set; /** * Implements the break condition for evolution of evaluable expressions and decides which * proposed evaluable expression describes the measured result best and will be annotated * in the PCM. * * @author Christoph Michelbach */ public class FinalJudge { /** * If a generation is fitter than this value, evolution of evaluable expressions will * be stopped. */ private static final double fitnessε = 0.5d; /** * IF the current generation is #maxNumberOfGenerationsPassed, evolution of evaluable * expressions will be stopped. */ private static final int maxNumberOfGenerationsPassed = 500; /** * The maximum amount of time (stated in milliseconds) allowed to have passed since * the application started so evolution of evaluable expressions will be continued. */ private static final long maxTimePassed = 3 * 24 * 3600; /** * The number of generations passed. Will be the number of times a {@link FinalJugde} * object received a call to {@link #judge(Blackboard)}. */ private int numberOfGenerationsPassed; /** * Implements the break condition for evolution of evaluable expressions. Decides * whether evolution will be continued or stopped depending on the fitness of the * fittest evaluable expression, the number of generations passed, the time passed, * and the relative improvement of a generation. * * @param blackboard The {@link Blackboard} this {@link FinalJudge} operates on. * @return {@code true} to indicate that evolution of evaluable expressions will be * stopped; {@code false} otherwise. */ boolean judge(final Blackboard blackboard) { this.numberOfGenerationsPassed++; if (this.numberOfGenerationsPassed > maxNumberOfGenerationsPassed) { return true; } final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); final long startTime = runtimeBean.getStartTime() / 1000; final long currentTime = System.currentTimeMillis(); if ((currentTime - startTime) > maxTimePassed) { return true; } EvaluableExpressionFitnessFunction fitnessFunction = blackboard.getFitnessFunction(); // determine the criteria which aren't CPU-intensive first final Set<SeffBranch> seffBranches = blackboard.getSeffBranchesToBeMeasured(); this.containsElementWithSufficientFitness(seffBranches, blackboard, fitnessFunction::gradeFor); return true; } /** * Determines whether a set of {@linkplain MeasurableSeffElement measurable SEFF * elements} contains an element with sufficient fitness to stop evolution of * evaluable expressions. * * <p/> CAUTION: All elements of {@code measurableSeffElements} have to be of type * {@code SE}. * * @param <SeffElementType> The type of which all {@linkplain MeasurableSeffElement * MeasurableSeffElements} of the set {@code measurableSeffElements} are. * * @param measurableSeffElements The set of {@linkplain MeasurableSeffElement * measurable SEFF elements} to operate on. * @param blackboard The {@link Blackboard} to operate on. * @return {@code true} if {@code measurableSeffElements} contains an element with * sufficient fitness to stop evolution of evaluable expressions; * {@code false} otherwise. */ private <SeffElementType extends MeasurableSeffElement> boolean containsElementWithSufficientFitness( final Set<SeffElementType> measurableSeffElements, final Blackboard blackboard, TypedFitnessFunction<SeffElementType> fitnessFunction) { final EvaluableExpressionFitnessFunctionBlackboardView fitnessFunctionView = new ProposedExpressionAnalyserBlackboardView(); for (SeffElementType seffElement : measurableSeffElements) { boolean foundOptimal = false; for (EvaluableExpression proposedExpression : blackboard.getProposedExpressionFor(seffElement)) { final double fitnessValue = fitnessFunction.gradeFor(seffElement, proposedExpression, fitnessFunctionView); foundOptimal = foundOptimal || fitnessValue < fitnessε; } // If a single MeasurableSeffElement to examine doesn't have a good enough // EvaluableExpression to describe it, the set of MeasurableSeffElements // doesn't have good enough EvaluableExpressions to describe it. if (!foundOptimal) { return false; } } return true; } private interface TypedFitnessFunction<SeffElementType extends MeasurableSeffElement> { double gradeFor(SeffElementType seffElement, EvaluableExpression expression, EvaluableExpressionFitnessFunctionBlackboardView blackboard); } }
Core/src/main/java/de/uka/ipd/sdq/beagle/core/judge/FinalJudge.java
package de.uka.ipd.sdq.beagle.core.judge; import de.uka.ipd.sdq.beagle.core.Blackboard; import de.uka.ipd.sdq.beagle.core.MeasurableSeffElement; import de.uka.ipd.sdq.beagle.core.SeffBranch; import de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.util.Iterator; import java.util.Set; /** * Implements the break condition for evolution of evaluable expressions and decides which * proposed evaluable expression describes the measured result best and will be annotated * in the PCM. * * @author Christoph Michelbach */ public class FinalJudge { /** * If a generation is fitter than this value, evolution of evaluable expressions will * be stopped. */ private static final double fitnessε = 0.5d; /** * IF the current generation is #maxNumberOfGenerationsPassed, evolution of evaluable * expressions will be stopped. */ private static final int maxNumberOfGenerationsPassed = 500; /** * The maximum amount of time (stated in milliseconds) allowed to have passed since * the application started so evolution of evaluable expressions will be continued. */ private static final long maxTimePassed = 3 * 24 * 3600; /** * The number of generations passed. Will be the number of times a {@link FinalJugde} * object received a call to {@link #judge(Blackboard)}. */ private int numberOfGenerationsPassed; /** * Implements the break condition for evolution of evaluable expressions. Decides * whether evolution will be continued or stopped depending on the fitness of the * fittest evaluable expression, the number of generations passed, the time passed, * and the relative improvement of a generation. * * @param blackboard The {@link Blackboard} this {@link FinalJudge} operates on. * @return {@code true} to indicate that evolution of evaluable expressions will be * stopped; {@code false} otherwise. */ boolean judge(final Blackboard blackboard) { this.numberOfGenerationsPassed++; if (this.numberOfGenerationsPassed > maxNumberOfGenerationsPassed) { return true; } final RuntimeMXBean runtimeBean = ManagementFactory.getRuntimeMXBean(); final long startTime = runtimeBean.getStartTime() / 1000; final long currentTime = System.currentTimeMillis(); if ((currentTime - startTime) > maxTimePassed) { return true; } // determine the criteria which aren't CPU-intensive first final Set<SeffBranch> seffBranches = blackboard.getSeffBranchesToBeMeasured(); this.containsElementWithSufficientFitness(seffBranches, blackboard); return true; } /** * Determines whether a set of {@linkplain MeasurableSeffElement measurable SEFF * elements} contains an element with sufficient fitness to stop evolution of * evaluable expressions. * * <p/> CAUTION: All elements of {@code measurableSeffElements} have to be of type * {@code SE}. * * @param <SE> The type of which all {@linkplain MeasurableSeffElement * MeasurableSeffElements} of the set {@code measurableSeffElements} are. * * @param measurableSeffElements The set of {@linkplain MeasurableSeffElement * measurable SEFF elements} to operate on. * @param blackboard The {@link Blackboard} to operate on. * @return {@code true} if {@code measurableSeffElements} contains an element with * sufficient fitness to stop evolution of evaluable expressions; * {@code false} otherwise. * @throws ClassCastException Thrown if {@code measurableSeffElements} contains * elements not of type {@code SE}. */ private <SE extends MeasurableSeffElement> boolean containsElementWithSufficientFitness( final Set<SE> measurableSeffElements, final Blackboard blackboard) throws ClassCastException { final EvaluableExpressionFitnessFunction fitnessFunction = blackboard.getFitnessFunction(); @SuppressWarnings("unchecked") final Iterator<MeasurableSeffElement> measurableSeffElementsIterator = (Iterator<MeasurableSeffElement>) measurableSeffElements.iterator(); while (measurableSeffElementsIterator.hasNext()) { @SuppressWarnings("unchecked") final MeasurableSeffElement currentMeasurableSeffElement = measurableSeffElementsIterator.next(); final Set<EvaluableExpression> proposedExpressions = blackboard.getProposedExpressionFor(currentMeasurableSeffElement); final Iterator<EvaluableExpression> proposedExpressionsIterator = proposedExpressions.iterator(); boolean foundFittingEvaluableExpression = false; while (proposedExpressionsIterator.hasNext()) { final EvaluableExpression proposedExpression = proposedExpressionsIterator.next(); if (fitnessFunction.gradeFor((SE) currentMeasurableSeffElement, proposedExpression, blackboard) < fitnessε) { foundFittingEvaluableExpression = true; break; } } // If a single MeasurableSeffElement to examine doesn't have a good enough // EvaluableExpression to describe it, the set of MeasurableSeffElements // doesn't have good enough EvaluableExpressions to describe it. if (!foundFittingEvaluableExpression) { return false; } } return true; } }
Joshua didn't fuck up. :) Thanks.
Core/src/main/java/de/uka/ipd/sdq/beagle/core/judge/FinalJudge.java
Joshua didn't fuck up. :) Thanks.
<ide><path>ore/src/main/java/de/uka/ipd/sdq/beagle/core/judge/FinalJudge.java <ide> import de.uka.ipd.sdq.beagle.core.Blackboard; <ide> import de.uka.ipd.sdq.beagle.core.MeasurableSeffElement; <ide> import de.uka.ipd.sdq.beagle.core.SeffBranch; <add>import de.uka.ipd.sdq.beagle.core.analysis.ProposedExpressionAnalyserBlackboardView; <ide> import de.uka.ipd.sdq.beagle.core.evaluableexpressions.EvaluableExpression; <ide> <ide> import java.lang.management.ManagementFactory; <ide> import java.lang.management.RuntimeMXBean; <del>import java.util.Iterator; <ide> import java.util.Set; <ide> <ide> /** <ide> return true; <ide> } <ide> <add> EvaluableExpressionFitnessFunction fitnessFunction = blackboard.getFitnessFunction(); <ide> // determine the criteria which aren't CPU-intensive first <ide> <ide> final Set<SeffBranch> seffBranches = blackboard.getSeffBranchesToBeMeasured(); <del> this.containsElementWithSufficientFitness(seffBranches, blackboard); <add> this.containsElementWithSufficientFitness(seffBranches, blackboard, fitnessFunction::gradeFor); <ide> <ide> return true; <ide> } <ide> * <p/> CAUTION: All elements of {@code measurableSeffElements} have to be of type <ide> * {@code SE}. <ide> * <del> * @param <SE> The type of which all {@linkplain MeasurableSeffElement <add> * @param <SeffElementType> The type of which all {@linkplain MeasurableSeffElement <ide> * MeasurableSeffElements} of the set {@code measurableSeffElements} are. <ide> * <ide> * @param measurableSeffElements The set of {@linkplain MeasurableSeffElement <ide> * @return {@code true} if {@code measurableSeffElements} contains an element with <ide> * sufficient fitness to stop evolution of evaluable expressions; <ide> * {@code false} otherwise. <del> * @throws ClassCastException Thrown if {@code measurableSeffElements} contains <del> * elements not of type {@code SE}. <ide> */ <del> private <SE extends MeasurableSeffElement> boolean containsElementWithSufficientFitness( <del> final Set<SE> measurableSeffElements, final Blackboard blackboard) throws ClassCastException { <add> private <SeffElementType extends MeasurableSeffElement> boolean containsElementWithSufficientFitness( <add> final Set<SeffElementType> measurableSeffElements, final Blackboard blackboard, <add> TypedFitnessFunction<SeffElementType> fitnessFunction) { <ide> <del> final EvaluableExpressionFitnessFunction fitnessFunction = blackboard.getFitnessFunction(); <add> final EvaluableExpressionFitnessFunctionBlackboardView fitnessFunctionView = <add> new ProposedExpressionAnalyserBlackboardView(); <ide> <del> @SuppressWarnings("unchecked") <del> final Iterator<MeasurableSeffElement> measurableSeffElementsIterator = <del> (Iterator<MeasurableSeffElement>) measurableSeffElements.iterator(); <del> while (measurableSeffElementsIterator.hasNext()) { <del> @SuppressWarnings("unchecked") <del> final MeasurableSeffElement currentMeasurableSeffElement = measurableSeffElementsIterator.next(); <add> for (SeffElementType seffElement : measurableSeffElements) { <add> boolean foundOptimal = false; <ide> <del> final Set<EvaluableExpression> proposedExpressions = <del> blackboard.getProposedExpressionFor(currentMeasurableSeffElement); <del> final Iterator<EvaluableExpression> proposedExpressionsIterator = proposedExpressions.iterator(); <del> <del> boolean foundFittingEvaluableExpression = false; <del> while (proposedExpressionsIterator.hasNext()) { <del> final EvaluableExpression proposedExpression = proposedExpressionsIterator.next(); <del> <del> if (fitnessFunction.gradeFor((SE) currentMeasurableSeffElement, proposedExpression, <del> blackboard) < fitnessε) { <del> foundFittingEvaluableExpression = true; <del> break; <del> } <add> for (EvaluableExpression proposedExpression : blackboard.getProposedExpressionFor(seffElement)) { <add> final double fitnessValue = <add> fitnessFunction.gradeFor(seffElement, proposedExpression, fitnessFunctionView); <add> foundOptimal = foundOptimal || fitnessValue < fitnessε; <ide> } <ide> <ide> // If a single MeasurableSeffElement to examine doesn't have a good enough <ide> // EvaluableExpression to describe it, the set of MeasurableSeffElements <ide> // doesn't have good enough EvaluableExpressions to describe it. <del> if (!foundFittingEvaluableExpression) { <add> if (!foundOptimal) { <ide> return false; <ide> } <ide> } <ide> <ide> return true; <ide> } <add> <add> private interface TypedFitnessFunction<SeffElementType extends MeasurableSeffElement> { <add> <add> double gradeFor(SeffElementType seffElement, EvaluableExpression expression, <add> EvaluableExpressionFitnessFunctionBlackboardView blackboard); <add> } <ide> }
Java
apache-2.0
164a8eb86244333a2694352c056af479ce291def
0
speedy01/Spark,vipinraj/Spark,speedy01/Spark,igniterealtime/Spark,vipinraj/Spark,BittyByte/Spark,vipinraj/Spark,igniterealtime/Spark,wrooot/Spark,BittyByte/Spark,speedy01/Spark,guusdk/Spark,wrooot/Spark,wrooot/Spark,igniterealtime/Spark,wrooot/Spark,speedy01/Spark,BittyByte/Spark,guusdk/Spark,guusdk/Spark,guusdk/Spark,BittyByte/Spark,igniterealtime/Spark,vipinraj/Spark
/** * $Revision$ * $Date$ * * Copyright (C) 1999-2005 Jive Software. All rights reserved. * This software is the proprietary information of Jive Software. Use is subject to license terms. */ package org.jivesoftware.spark.component; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.util.ModelUtil; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Point; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JWindow; import javax.swing.ListCellRenderer; /** * Implementation of a popup field from a TextField. * * @author Derek DeMoro */ public class JContactItemField extends JPanel { private JTextField textField = new JTextField(); private DefaultListModel model = new DefaultListModel(); private JList list = new JList(model); private JWindow popup; private List<ContactItem> items; public JContactItemField(List items) { setLayout(new BorderLayout()); this.items = items; add(textField, BorderLayout.CENTER); textField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent keyEvent) { char ch = keyEvent.getKeyChar(); if (validateChar(ch)) { showPopupMenu(); } if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) { int index = list.getSelectedIndex(); if (index >= 0) { ContactItem selection = (ContactItem)list.getSelectedValue(); textField.setText(selection.getNickname()); popup.setVisible(false); } } if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) { popup.setVisible(false); } dispatchEvent(keyEvent); } public void keyPressed(KeyEvent e) { if (isArrowKey(e)) { list.dispatchEvent(e); } } }); textField.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { textField.requestFocusInWindow(); } }); popup = new JWindow(); popup.getContentPane().add(new JScrollPane(list)); popup.setAlwaysOnTop(true); list.setCellRenderer(new PopupRenderer()); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = list.getSelectedIndex(); if (index >= 0) { ContactItem selection = (ContactItem)list.getSelectedValue(); textField.setText(selection.getNickname()); popup.setVisible(false); } } } }); } public void dispose() { popup.dispose(); } public void setItems(List list) { this.items = items; } public JList getList(){ return list; } private void showPopupMenu() { model.removeAllElements(); String typedItem = textField.getText(); final List<ContactItem> validItems = new ArrayList<ContactItem>(); for (ContactItem contactItem : items) { String nickname = contactItem.getNickname().toLowerCase(); if (nickname.startsWith(typedItem.toLowerCase())) { validItems.add(contactItem); } } if (validItems.size() > 0) { for (final ContactItem label : validItems) { model.addElement(label); } } if (validItems.size() != 0 && !popup.isVisible()) { popup.pack(); popup.setSize(textField.getWidth(), 200); Point pt = textField.getLocationOnScreen(); pt.translate(0, textField.getHeight()); popup.setLocation(pt); popup.toFront(); popup.setVisible(true); } // set initial selection if(validItems.size() > 0){ list.setSelectedIndex(0); } } /** * Validate the given text - to pass it must contain letters, digits, '@', '-', '_', '.', ',' * or a space character. * * @param text the text to check * @return true if the given text is valid, false otherwise. */ public boolean validateChars(String text) { if (!ModelUtil.hasLength(text)) { return false; } for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (!Character.isLetterOrDigit(ch) && ch != '@' && ch != '-' && ch != '_' && ch != '.' && ch != ',' && ch != ' ') { return false; } } return true; } /** * Validate the given text - to pass it must contain letters, digits, '@', '-', '_', '.', ',' * or a space character. * * @param ch the character * @return true if the given text is valid, false otherwise. */ public boolean validateChar(char ch) { if (!Character.isLetterOrDigit(ch) && ch != '@' && ch != '-' && ch != '_' && ch != '.' && ch != ',' && ch != ' ' && ch != KeyEvent.VK_BACK_SPACE && ch != KeyEvent.CTRL_DOWN_MASK && ch != KeyEvent.CTRL_MASK) { return false; } return true; } public boolean isArrowKey(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) { return true; } return false; } public String getText() { return textField.getText(); } public void setText(String text) { textField.setText(text); } public void focus() { textField.requestFocus(); } public JTextField getTextField() { return textField; } public JWindow getPopup() { return popup; } class PopupRenderer extends JLabel implements ListCellRenderer { /** * Construct Default JLabelIconRenderer. */ public PopupRenderer() { setOpaque(true); this.setHorizontalTextPosition(JLabel.RIGHT); this.setHorizontalAlignment(JLabel.LEFT); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } ContactItem contactItem = (ContactItem)value; setText(contactItem.getNickname()); if (contactItem.getIcon() == null) { setIcon(SparkRes.getImageIcon(SparkRes.CLEAR_BALL_ICON)); } else { setIcon(contactItem.getIcon()); } setFont(contactItem.getNicknameLabel().getFont()); setForeground(contactItem.getForeground()); return this; } } }
src/java/org/jivesoftware/spark/component/JContactItemField.java
/** * $Revision$ * $Date$ * * Copyright (C) 1999-2005 Jive Software. All rights reserved. * This software is the proprietary information of Jive Software. Use is subject to license terms. */ package org.jivesoftware.spark.component; import org.jivesoftware.resource.SparkRes; import org.jivesoftware.spark.ui.ContactItem; import org.jivesoftware.spark.util.ModelUtil; import java.awt.BorderLayout; import java.awt.Component; import java.awt.Point; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.util.ArrayList; import java.util.List; import javax.swing.DefaultListModel; import javax.swing.JLabel; import javax.swing.JList; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.JWindow; import javax.swing.ListCellRenderer; /** * Implementation of a popup field from a TextField. * * @author Derek DeMoro */ public class JContactItemField extends JPanel { private JTextField textField = new JTextField(); private DefaultListModel model = new DefaultListModel(); private JList list = new JList(model); private JWindow popup; private List<ContactItem> items; public JContactItemField(List items) { setLayout(new BorderLayout()); this.items = items; add(textField, BorderLayout.CENTER); textField.addKeyListener(new KeyAdapter() { public void keyReleased(KeyEvent keyEvent) { char ch = keyEvent.getKeyChar(); if (validateChar(ch)) { showPopupMenu(); } if (keyEvent.getKeyCode() == KeyEvent.VK_ENTER) { int index = list.getSelectedIndex(); if (index >= 0) { ContactItem selection = (ContactItem)list.getSelectedValue(); textField.setText(selection.getNickname()); popup.setVisible(false); } } if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) { popup.setVisible(false); } dispatchEvent(keyEvent); } public void keyPressed(KeyEvent e) { if (isArrowKey(e)) { list.dispatchEvent(e); } } }); textField.addFocusListener(new FocusListener() { public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { textField.requestFocusInWindow(); } }); popup = new JWindow(); popup.getContentPane().add(new JScrollPane(list)); popup.setAlwaysOnTop(true); list.setCellRenderer(new PopupRenderer()); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = list.getSelectedIndex(); if (index >= 0) { ContactItem selection = (ContactItem)list.getSelectedValue(); textField.setText(selection.getNickname()); popup.setVisible(false); } } } }); } public void dispose() { popup.dispose(); } public void setItems(List list) { this.items = items; } public JList getList(){ return list; } private void showPopupMenu() { model.removeAllElements(); String typedItem = textField.getText(); final List<ContactItem> validItems = new ArrayList<ContactItem>(); for (ContactItem contactItem : items) { String nickname = contactItem.getNickname().toLowerCase(); if (nickname.startsWith(typedItem.toLowerCase())) { validItems.add(contactItem); } } if (validItems.size() > 0) { for (final ContactItem label : validItems) { model.addElement(label); } } if (validItems.size() != 0 && !popup.isVisible()) { popup.pack(); popup.setSize(textField.getWidth(), 200); Point pt = textField.getLocationOnScreen(); pt.translate(0, textField.getHeight()); popup.setLocation(pt); popup.toFront(); popup.setVisible(true); } } /** * Validate the given text - to pass it must contain letters, digits, '@', '-', '_', '.', ',' * or a space character. * * @param text the text to check * @return true if the given text is valid, false otherwise. */ public boolean validateChars(String text) { if (!ModelUtil.hasLength(text)) { return false; } for (int i = 0; i < text.length(); i++) { char ch = text.charAt(i); if (!Character.isLetterOrDigit(ch) && ch != '@' && ch != '-' && ch != '_' && ch != '.' && ch != ',' && ch != ' ') { return false; } } return true; } /** * Validate the given text - to pass it must contain letters, digits, '@', '-', '_', '.', ',' * or a space character. * * @param ch the character * @return true if the given text is valid, false otherwise. */ public boolean validateChar(char ch) { if (!Character.isLetterOrDigit(ch) && ch != '@' && ch != '-' && ch != '_' && ch != '.' && ch != ',' && ch != ' ' && ch != KeyEvent.VK_BACK_SPACE && ch != KeyEvent.CTRL_DOWN_MASK && ch != KeyEvent.CTRL_MASK) { return false; } return true; } public boolean isArrowKey(KeyEvent e) { if (e.getKeyCode() == KeyEvent.VK_UP || e.getKeyCode() == KeyEvent.VK_DOWN) { return true; } return false; } public String getText() { return textField.getText(); } public void setText(String text) { textField.setText(text); } public void focus() { textField.requestFocus(); } public JTextField getTextField() { return textField; } public JWindow getPopup() { return popup; } class PopupRenderer extends JLabel implements ListCellRenderer { /** * Construct Default JLabelIconRenderer. */ public PopupRenderer() { setOpaque(true); this.setHorizontalTextPosition(JLabel.RIGHT); this.setHorizontalAlignment(JLabel.LEFT); } public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } ContactItem contactItem = (ContactItem)value; setText(contactItem.getNickname()); if (contactItem.getIcon() == null) { setIcon(SparkRes.getImageIcon(SparkRes.CLEAR_BALL_ICON)); } else { setIcon(contactItem.getIcon()); } setFont(contactItem.getNicknameLabel().getFont()); setForeground(contactItem.getForeground()); return this; } } }
Have ctrl+f put initial selection on index 0 git-svn-id: f13e20fb8540f76a08799c0051229138c0279aa7@7390 b35dd754-fafc-0310-a699-88a17e54d16e
src/java/org/jivesoftware/spark/component/JContactItemField.java
Have ctrl+f put initial selection on index 0
<ide><path>rc/java/org/jivesoftware/spark/component/JContactItemField.java <ide> popup.setLocation(pt); <ide> popup.toFront(); <ide> popup.setVisible(true); <add> } <add> <add> // set initial selection <add> if(validItems.size() > 0){ <add> list.setSelectedIndex(0); <ide> } <ide> <ide> }
Java
lgpl-2.1
1531c93c225f790a2da11d9ceff44fb5efb363c6
0
tomck/intermine,justincc/intermine,joshkh/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,tomck/intermine,tomck/intermine,joshkh/intermine,JoeCarlson/intermine,elsiklab/intermine,JoeCarlson/intermine,kimrutherford/intermine,kimrutherford/intermine,justincc/intermine,kimrutherford/intermine,tomck/intermine,justincc/intermine,tomck/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,kimrutherford/intermine,justincc/intermine,elsiklab/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,JoeCarlson/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,tomck/intermine,justincc/intermine,elsiklab/intermine,elsiklab/intermine,zebrafishmine/intermine,joshkh/intermine,joshkh/intermine,elsiklab/intermine,joshkh/intermine,zebrafishmine/intermine,kimrutherford/intermine,zebrafishmine/intermine,JoeCarlson/intermine,tomck/intermine,justincc/intermine,Arabidopsis-Information-Portal/intermine,Arabidopsis-Information-Portal/intermine,zebrafishmine/intermine,JoeCarlson/intermine,zebrafishmine/intermine,JoeCarlson/intermine,JoeCarlson/intermine,kimrutherford/intermine,Arabidopsis-Information-Portal/intermine,elsiklab/intermine,elsiklab/intermine,kimrutherford/intermine,joshkh/intermine,joshkh/intermine,Arabidopsis-Information-Portal/intermine,joshkh/intermine,zebrafishmine/intermine,JoeCarlson/intermine,justincc/intermine,tomck/intermine,zebrafishmine/intermine,zebrafishmine/intermine,tomck/intermine,JoeCarlson/intermine,kimrutherford/intermine
package org.intermine.web.task; /* * Copyright (C) 2002-2011 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.intermine.api.bag.UnknownBagTypeException; import org.intermine.api.config.ClassKeyHelper; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.BagState; import org.intermine.metadata.FieldDescriptor; import org.intermine.model.userprofile.SavedBag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.sql.Database; import org.intermine.sql.DatabaseUtil; import org.intermine.web.logic.widget.EnrichmentWidget; /** * Task to load bagvalues table in the userprofile database. * If in the table savedbag, the column 'intermine_state' doesn't exist , add it. * * @author dbutano */ public class LoadBagValuesTask extends Task { private String osAlias; private String userProfileAlias; private ObjectStore uos = null; private ObjectStore os = null; private static final Logger LOG = Logger.getLogger(LoadBagValuesTask.class); /** * Set the alias of the main object store. * @param osAlias the object store alias */ public void setOSAlias(String osAlias) { this.osAlias = osAlias; } /** * Set the alias of the userprofile object store. * @param userProfileAlias the object store alias of the userprofile database */ public void setUserProfileAlias(String userProfileAlias) { this.userProfileAlias = userProfileAlias; } /** * Execute the task - load bagvalues table. * @throws BuildException if there is a problem while */ public void execute() { try { os = ObjectStoreFactory.getObjectStore(osAlias); uos = ObjectStoreFactory.getObjectStore(userProfileAlias); } catch (Exception e) { throw new BuildException("Exception while creating ObjectStore", e); } updateUserProfileDatabase(); ObjectStoreWriter uosw = null; try { uosw = uos.getNewWriter(); } catch (ObjectStoreException ose) { throw new BuildException("Problems retrieving the new writer", ose); } Query q = new Query(); QueryClass qc = new QueryClass(SavedBag.class); q.addFrom(qc); q.addToSelect(qc); Results bags = uos.execute(q, 1000, false, false, true); if (bags.size() == 0) { log("There are no users's saved list."); return; } if (!verifyProductionDatabase(bags)) { log("The task will not be executed. Verify to use the same production database that" + " created the users's saved lists."); return; } //start loading bagvalues for (Iterator i = bags.iterator(); i.hasNext();) { ResultsRow row = (ResultsRow) i.next(); SavedBag savedBag = (SavedBag) row.get(0); if (StringUtils.isBlank(savedBag.getName())) { log("Failed to load bag with blank name"); } else { try { InterMineBag bag = new InterMineBag(os, savedBag.getId(), uosw); log("Start loading bag: " + bag.getName() + " - id: " + bag.getSavedBagId()); Properties classKeyProps = new Properties(); try { classKeyProps.load(this.getClass().getClassLoader() .getResourceAsStream("class_keys.properties")); } catch (Exception e) { log("Error loading class descriptions."); e.printStackTrace(); } Map<String, List<FieldDescriptor>> classKeys = ClassKeyHelper.readKeys(os.getModel(), classKeyProps); List<String> keyFielNames = (List<String>) ClassKeyHelper.getKeyFieldNames( classKeys, bag.getType()); bag.setKeyFieldNames(keyFielNames); bag.addBagValues(); log("Loaded bag: " + bag.getName() + " - id: " + bag.getSavedBagId()); } catch (UnknownBagTypeException e) { log("Ignoring a bag because type: is not in the model."); e.printStackTrace(); } catch (ObjectStoreException ose) { throw new BuildException("Exception while creating InterMineBag", ose); } } } try { uosw.close(); } catch (ObjectStoreException ose) { throw new BuildException("Problems closing the writer", ose); } } private void updateUserProfileDatabase() { if (uos instanceof ObjectStoreInterMineImpl) { Connection conn = null; Database db = ((ObjectStoreInterMineImpl) uos).getDatabase(); try { conn = ((ObjectStoreInterMineImpl) uos).getConnection(); if (!DatabaseUtil.columnExists(conn, "savedbag", "intermine_state") && DatabaseUtil.columnExists(conn, "savedbag", "intermine_current")) { System .out.println("You must not execute the task load-bagvalues-table. Run the task update-savedbag-table task."); return; } if (!DatabaseUtil.columnExists(conn, "savedbag", "intermine_state")) { DatabaseUtil.addColumn(db, "savedbag", "intermine_state", DatabaseUtil.Type.text); DatabaseUtil.updateColumnValue(db, "savedbag", "intermine_state", BagState.CURRENT.toString()); } if (!DatabaseUtil.tableExists(conn, "bagvalues")) { DatabaseUtil.createBagValuesTables(conn); } } catch (SQLException sqle) { sqle.printStackTrace(); throw new BuildException("Problems creating bagvalues table", sqle); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException sqle) { } } } } private boolean verifyProductionDatabase(Results bags) { //verify that we are pointing out the production database that created the users's saved lists. //select osbid from savedbag int totalBags = bags.size(); int bagsMatching = 0; StringBuffer osbids = new StringBuffer(); for (Iterator i = bags.iterator(); i.hasNext();) { ResultsRow row = (ResultsRow) i.next(); SavedBag savedBag = (SavedBag) row.get(0); osbids.append(savedBag.getOsbId() + ","); } LOG.info("BAGVAL - userprofile osbids:" + osbids.length()); LOG.info("BAGVAL - userprofile ids:" + osbids); if (!"".equals(osbids)) { osbids.deleteCharAt(osbids.length() - 1); Connection conn = null; try { conn = ((ObjectStoreInterMineImpl) os).getDatabase().getConnection(); String sqlCountBagsMatching = "SELECT COUNT(DISTINCT bagid) FROM osbag_int WHERE bagid IN (" + osbids + ")"; ResultSet result = conn.createStatement().executeQuery(sqlCountBagsMatching); result.next(); bagsMatching = result.getInt(1); LOG.info("BAGVAL - found in production: " + bagsMatching); if ( bagsMatching/totalBags < 0.8) { return false; } return true; } catch (SQLException sqle) { sqle.printStackTrace(); throw new BuildException("Exception while connecting ", sqle); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException sqle) { } } } else { return true; } } }
intermine/webtasks/main/src/org/intermine/web/task/LoadBagValuesTask.java
package org.intermine.web.task; /* * Copyright (C) 2002-2011 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.Task; import org.intermine.api.bag.UnknownBagTypeException; import org.intermine.api.config.ClassKeyHelper; import org.intermine.api.profile.InterMineBag; import org.intermine.api.profile.BagState; import org.intermine.metadata.FieldDescriptor; import org.intermine.model.userprofile.SavedBag; import org.intermine.objectstore.ObjectStore; import org.intermine.objectstore.ObjectStoreException; import org.intermine.objectstore.ObjectStoreFactory; import org.intermine.objectstore.ObjectStoreWriter; import org.intermine.objectstore.intermine.ObjectStoreInterMineImpl; import org.intermine.objectstore.query.Query; import org.intermine.objectstore.query.QueryClass; import org.intermine.objectstore.query.Results; import org.intermine.objectstore.query.ResultsRow; import org.intermine.sql.Database; import org.intermine.sql.DatabaseUtil; /** * Task to load bagvalues table in the userprofile database. * If in the table savedbag, the column 'intermine_state' doesn't exist , add it. * * @author dbutano */ public class LoadBagValuesTask extends Task { private String osAlias; private String userProfileAlias; private ObjectStore uos = null; private ObjectStore os = null; /** * Set the alias of the main object store. * @param osAlias the object store alias */ public void setOSAlias(String osAlias) { this.osAlias = osAlias; } /** * Set the alias of the userprofile object store. * @param userProfileAlias the object store alias of the userprofile database */ public void setUserProfileAlias(String userProfileAlias) { this.userProfileAlias = userProfileAlias; } /** * Execute the task - load bagvalues table. * @throws BuildException if there is a problem while */ public void execute() { try { os = ObjectStoreFactory.getObjectStore(osAlias); uos = ObjectStoreFactory.getObjectStore(userProfileAlias); } catch (Exception e) { throw new BuildException("Exception while creating ObjectStore", e); } updateUserProfileDatabase(); ObjectStoreWriter uosw = null; try { uosw = uos.getNewWriter(); } catch (ObjectStoreException ose) { throw new BuildException("Problems retrieving the new writer", ose); } Query q = new Query(); QueryClass qc = new QueryClass(SavedBag.class); q.addFrom(qc); q.addToSelect(qc); Results bags = uos.execute(q, 1000, false, false, true); if (bags.size() == 0) { log("There are no users's saved list."); return; } if (!verifyProductionDatabase(bags)) { log("The task will not be executed. Verify to use the same production database that" + " created the users's saved lists."); return; } //start loading bagvalues for (Iterator i = bags.iterator(); i.hasNext();) { ResultsRow row = (ResultsRow) i.next(); SavedBag savedBag = (SavedBag) row.get(0); if (StringUtils.isBlank(savedBag.getName())) { log("Failed to load bag with blank name"); } else { try { InterMineBag bag = new InterMineBag(os, savedBag.getId(), uosw); log("Start loading bag: " + bag.getName() + " - id: " + bag.getSavedBagId()); Properties classKeyProps = new Properties(); try { classKeyProps.load(this.getClass().getClassLoader() .getResourceAsStream("class_keys.properties")); } catch (Exception e) { log("Error loading class descriptions."); e.printStackTrace(); } Map<String, List<FieldDescriptor>> classKeys = ClassKeyHelper.readKeys(os.getModel(), classKeyProps); List<String> keyFielNames = (List<String>) ClassKeyHelper.getKeyFieldNames( classKeys, bag.getType()); bag.setKeyFieldNames(keyFielNames); bag.addBagValues(); log("Loaded bag: " + bag.getName() + " - id: " + bag.getSavedBagId()); } catch (UnknownBagTypeException e) { log("Ignoring a bag because type: is not in the model."); e.printStackTrace(); } catch (ObjectStoreException ose) { throw new BuildException("Exception while creating InterMineBag", ose); } } } try { uosw.close(); } catch (ObjectStoreException ose) { throw new BuildException("Problems closing the writer", ose); } } private void updateUserProfileDatabase() { if (uos instanceof ObjectStoreInterMineImpl) { Connection conn = null; Database db = ((ObjectStoreInterMineImpl) uos).getDatabase(); try { conn = ((ObjectStoreInterMineImpl) uos).getConnection(); if (!DatabaseUtil.columnExists(conn, "savedbag", "intermine_state") && DatabaseUtil.columnExists(conn, "savedbag", "intermine_current")) { System .out.println("You must not execute the task load-bagvalues-table. Run the task update-savedbag-table task."); return; } if (!DatabaseUtil.columnExists(conn, "savedbag", "intermine_state")) { DatabaseUtil.addColumn(db, "savedbag", "intermine_state", DatabaseUtil.Type.text); DatabaseUtil.updateColumnValue(db, "savedbag", "intermine_state", BagState.CURRENT.toString()); } if (!DatabaseUtil.tableExists(conn, "bagvalues")) { DatabaseUtil.createBagValuesTables(conn); } } catch (SQLException sqle) { sqle.printStackTrace(); throw new BuildException("Problems creating bagvalues table", sqle); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException sqle) { } } } } private boolean verifyProductionDatabase(Results bags) { //verify that we are pointing out the production database that created the users's saved lists. //select osbid from savedbag int totalBags = bags.size(); int bagsMatching = 0; StringBuffer osbids = new StringBuffer(); for (Iterator i = bags.iterator(); i.hasNext();) { ResultsRow row = (ResultsRow) i.next(); SavedBag savedBag = (SavedBag) row.get(0); osbids.append(savedBag.getOsbId() + ","); } if (!"".equals(osbids)) { osbids.deleteCharAt(osbids.length() - 1); Connection conn = null; try { conn = ((ObjectStoreInterMineImpl) os).getDatabase().getConnection(); String sqlCountBagsMatching = "SELECT COUNT(DISTINCT bagid) FROM osbag_int WHERE bagid IN (" + osbids + ")"; ResultSet result = conn.createStatement().executeQuery(sqlCountBagsMatching); result.next(); bagsMatching = result.getInt(1); if ( bagsMatching/totalBags < 0.8) { return false; } return true; } catch (SQLException sqle) { sqle.printStackTrace(); throw new BuildException("Exception while connecting ", sqle); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException sqle) { } } } else { return true; } } }
Add some debugging.
intermine/webtasks/main/src/org/intermine/web/task/LoadBagValuesTask.java
Add some debugging.
<ide><path>ntermine/webtasks/main/src/org/intermine/web/task/LoadBagValuesTask.java <ide> import java.util.Properties; <ide> <ide> import org.apache.commons.lang.StringUtils; <add>import org.apache.log4j.Logger; <ide> import org.apache.tools.ant.BuildException; <ide> import org.apache.tools.ant.Task; <ide> import org.intermine.api.bag.UnknownBagTypeException; <ide> import org.intermine.objectstore.query.ResultsRow; <ide> import org.intermine.sql.Database; <ide> import org.intermine.sql.DatabaseUtil; <add>import org.intermine.web.logic.widget.EnrichmentWidget; <ide> <ide> /** <ide> * Task to load bagvalues table in the userprofile database. <ide> private String userProfileAlias; <ide> private ObjectStore uos = null; <ide> private ObjectStore os = null; <add> <add> private static final Logger LOG = Logger.getLogger(LoadBagValuesTask.class); <ide> <ide> /** <ide> * Set the alias of the main object store. <ide> SavedBag savedBag = (SavedBag) row.get(0); <ide> osbids.append(savedBag.getOsbId() + ","); <ide> } <add> LOG.info("BAGVAL - userprofile osbids:" + osbids.length()); <add> LOG.info("BAGVAL - userprofile ids:" + osbids); <ide> if (!"".equals(osbids)) { <ide> osbids.deleteCharAt(osbids.length() - 1); <ide> Connection conn = null; <ide> ResultSet result = conn.createStatement().executeQuery(sqlCountBagsMatching); <ide> result.next(); <ide> bagsMatching = result.getInt(1); <del> <add> LOG.info("BAGVAL - found in production: " + bagsMatching); <ide> if ( bagsMatching/totalBags < 0.8) { <ide> return false; <ide> }
JavaScript
apache-2.0
268da9178824a7404edd1fa49d6e24eeb2a1af4a
0
appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen,appcelerator/titanium_mobile_tizen
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ module.exports = new function() { var finish, valueOf, alarmObj; this.init = function(testUtils) { finish = testUtils.finish; valueOf = testUtils.valueOf; alarmObj = require('Ti/Tizen/Alarm'); } this.name = 'alarm'; this.tests = [ {name: 'alarmAdd'}, {name: 'alarmGet'}, {name: 'alarmRemove'}, {name: 'alarmRelative'}, {name: 'alarmAbsolute'} ] this.alarmAdd = function(testRun) { var alarm, tizenArr, date = new Date(2012, 12, 21, 8, 0); alarmObj.removeAll(); // Alarm in 10 seconds (relative) alarm = alarmObj.createAlarmRelative({ delay: 10 }); valueOf(testRun, alarm instanceof Tizen.Alarm.AlarmRelative).shouldBeTrue(); alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); // Set an alarm on December 21st 2012 08:00 alarm = alarmObj.createAlarmAbsolute({ date: date }); valueOf(testRun, alarm instanceof Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); tizenArr = alarmObj.getAll(); valueOf(testRun, (tizenArr[0] instanceof Tizen.Alarm.AlarmAbsolute || tizenArr[0] instanceof Tizen.Alarm.AlarmRelative)).shouldBeTrue(); valueOf(testRun, tizenArr.length).shouldBe(2); finish(testRun); } this.alarmGet = function(testRun) { var alarm, alarm1, alarm2, alarm3, relative_id, absolute_id, date = new Date(2012, 12, 21, 8, 0); alarmObj.removeAll(); // Alarm in 10 seconds (relative) alarm = alarmObj.createAlarmRelative({ delay: 10 }); // Set an alarm on December 21st 2012 08:00 alarm1 = alarmObj.createAlarmAbsolute({ date: date }); alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); alarmObj.add(alarm1, 'http://tizen.org/alarm-clock'); relative_id = alarm.id; absolute_id = alarm1.id; valueOf(testRun, function() { alarm2 = alarmObj.get(relative_id); alarm3 = alarmObj.get(absolute_id); }).shouldNotThrowException(); valueOf(testRun, alarm2 instanceof Tizen.Alarm.AlarmRelative).shouldBeTrue(); valueOf(testRun, alarm3 instanceof Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); alarmObj.removeAll(); valueOf(testRun, function() { var alarmTmp = alarmObj.get(absolute_id); valueOf(testRun, alarm instanceof Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); alarmTmp = alarmObj.get(relative_id); }).shouldThrowException(); finish(testRun); } this.alarmRemove = function(testRun) { var alarm, alarm1, relative_id, alarmArr, absolute_id, date = new Date(2012, 12, 21, 8, 0); alarmObj.removeAll(); alarmArr = alarmObj.getAll(); valueOf(testRun, alarmArr.length).shouldBe(0); //Alarm in 10 seconds (relative) alarm = alarmObj.createAlarmRelative({ delay: 10 }); alarm1 = alarmObj.createAlarmAbsolute({ date: date }); alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); alarmObj.add(alarm1, 'http://tizen.org/alarm-clock'); relative_id = alarm.id; absolute_id = alarm1.id; valueOf(testRun, function() { alarmObj.remove(absolute_id); }).shouldNotThrowException(); valueOf(testRun, function() { alarmObj.remove(absolute_id); }).shouldThrowException(); finish(testRun); } this.alarmRelative = function(testRun) { var alarm, alarmId, delay = 2 * alarmObj.PERIOD_MINUTE, period = alarmObj.PERIOD_HOUR; alarmObj.removeAll(); alarm = alarmObj.createAlarmRelative({ delay: delay, period: period }); alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); alarmId = alarm.id; valueOf(testRun, function() { var remaining = alarm.getRemainingSeconds(); }).shouldNotThrowException(); valueOf(testRun, alarm.delay).shouldBe(delay); alarm = alarmObj.get(alarmId); valueOf(testRun, function() { var fromReaming = alarm.getRemainingSeconds(); }); valueOf(testRun, alarm.delay).shouldBe(delay); finish(testRun); } this.alarmAbsolute = function(testRun) { alarmObj.removeAll(); var alarm, alarmId, remaining, alarmFrom, fromReaming, date = new Date(), time = date.getTime() + 60000, period = alarmObj.PERIOD_HOUR; date.setTime(time); alarm = alarmObj.createAlarmAbsolute({ date: date, period: period }); alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); alarmId = alarm.id; remaining = alarm.getNextScheduledDate(); valueOf(testRun, remaining.toDateString()).shouldBe(alarm.date.toDateString()); alarmFrom = alarmObj.get(alarmId), fromReaming = alarmFrom.getNextScheduledDate(); valueOf(testRun, fromReaming.toDateString()).shouldBe(date.toDateString()); alarmObj.removeAll(); finish(testRun); } }
tests/anvil/configSet/Resources/suites/tizen/alarm.js
/* * Appcelerator Titanium Mobile * Copyright (c) 2011-2012 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Apache Public License * Please see the LICENSE included with this distribution for details. */ module.exports = new function() { var finish, valueOf; this.init = function(testUtils) { finish = testUtils.finish; valueOf = testUtils.valueOf; } this.name = 'alarm'; this.tests = [ {name: 'alarmAdd'}, {name: 'alarmGet'}, {name: 'alarmRemove'}, {name: 'alarmRelative'}, {name: 'alarmAbsolute'} ] this.alarmAdd = function(testRun) { var alarm, tizenArr, date = new Date(2012, 12, 21, 8, 0); Ti.Tizen.Alarm.removeAll(); // Alarm in 10 seconds (relative) alarm = Ti.Tizen.Alarm.createAlarmRelative({ delay: 10 }); valueOf(testRun, alarm instanceof Ti.Tizen.Alarm.AlarmRelative).shouldBeTrue(); Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); // Set an alarm on December 21st 2012 08:00 alarm = Ti.Tizen.Alarm.createAlarmAbsolute({ date: date }); valueOf(testRun, alarm instanceof Ti.Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); tizenArr = Ti.Tizen.Alarm.getAll(); valueOf(testRun, (tizenArr[0] instanceof Ti.Tizen.Alarm.AlarmAbsolute || tizenArr[0] instanceof Ti.Tizen.Alarm.AlarmRelative)).shouldBeTrue(); valueOf(testRun, tizenArr.length).shouldBe(2); finish(testRun); } this.alarmGet = function(testRun) { var alarm, alarm1, alarm2, alarm3, relative_id, absolute_id, date = new Date(2012, 12, 21, 8, 0); Ti.Tizen.Alarm.removeAll(); // Alarm in 10 seconds (relative) alarm = Ti.Tizen.Alarm.createAlarmRelative({ delay: 10 }); // Set an alarm on December 21st 2012 08:00 alarm1 = Ti.Tizen.Alarm.createAlarmAbsolute({ date: date }); Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); Ti.Tizen.Alarm.add(alarm1, 'http://tizen.org/alarm-clock'); relative_id = alarm.id; absolute_id = alarm1.id; valueOf(testRun, function() { alarm2 = Ti.Tizen.Alarm.get(relative_id); alarm3 = Ti.Tizen.Alarm.get(absolute_id); }).shouldNotThrowException(); valueOf(testRun, alarm2 instanceof Ti.Tizen.Alarm.AlarmRelative).shouldBeTrue(); valueOf(testRun, alarm3 instanceof Ti.Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); Ti.Tizen.Alarm.removeAll(); valueOf(testRun, function() { var alarmTmp = Ti.Tizen.Alarm.get(absolute_id); valueOf(testRun, alarm instanceof Ti.Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); alarmTmp = Ti.Tizen.Alarm.get(relative_id); }).shouldThrowException(); finish(testRun); } this.alarmRemove = function(testRun) { var alarm, alarm1, relative_id, alarmArr, absolute_id, date = new Date(2012, 12, 21, 8, 0); Ti.Tizen.Alarm.removeAll(); alarmArr = Ti.Tizen.Alarm.getAll(); valueOf(testRun, alarmArr.length).shouldBe(0); //Alarm in 10 seconds (relative) alarm = Ti.Tizen.Alarm.createAlarmRelative({ delay: 10 }); alarm1 = Ti.Tizen.Alarm.createAlarmAbsolute({ date: date }); Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); Ti.Tizen.Alarm.add(alarm1, 'http://tizen.org/alarm-clock'); relative_id = alarm.id; absolute_id = alarm1.id; valueOf(testRun, function() { Ti.Tizen.Alarm.remove(absolute_id); }).shouldNotThrowException(); valueOf(testRun, function() { Ti.Tizen.Alarm.remove(absolute_id); }).shouldThrowException(); finish(testRun); } this.alarmRelative = function(testRun) { var alarm, alarmId, delay = 2 * Ti.Tizen.Alarm.PERIOD_MINUTE, period = Ti.Tizen.Alarm.PERIOD_HOUR; Ti.Tizen.Alarm.removeAll(); alarm = Ti.Tizen.Alarm.createAlarmRelative({ delay: delay, period: period }); Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); alarmId = alarm.id; valueOf(testRun, function() { var remaining = alarm.getRemainingSeconds(); }).shouldNotThrowException(); valueOf(testRun, alarm.delay).shouldBe(delay); alarm = Ti.Tizen.Alarm.get(alarmId); valueOf(testRun, function() { var fromReaming = alarm.getRemainingSeconds(); }); valueOf(testRun, alarm.delay).shouldBe(delay); finish(testRun); } this.alarmAbsolute = function(testRun) { Ti.Tizen.Alarm.removeAll(); var alarm, alarmId, remaining, alarmFrom, fromReaming, date = new Date(), time = date.getTime() + 60000, period = Ti.Tizen.Alarm.PERIOD_HOUR; date.setTime(time); alarm = Ti.Tizen.Alarm.createAlarmAbsolute({ date: date, period: period }); Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); alarmId = alarm.id; remaining = alarm.getNextScheduledDate(); valueOf(testRun, remaining.toDateString()).shouldBe(alarm.date.toDateString()); alarmFrom = Ti.Tizen.Alarm.get(alarmId), fromReaming = alarmFrom.getNextScheduledDate(); valueOf(testRun, fromReaming.toDateString()).shouldBe(date.toDateString()); Ti.Tizen.Alarm.removeAll(); finish(testRun); } }
Fix Anvil alarm test according to new namespace Tizen.Alarm
tests/anvil/configSet/Resources/suites/tizen/alarm.js
Fix Anvil alarm test according to new namespace Tizen.Alarm
<ide><path>ests/anvil/configSet/Resources/suites/tizen/alarm.js <ide> <ide> module.exports = new function() { <ide> var finish, <del> valueOf; <del> <add> valueOf, <add> alarmObj; <add> <ide> this.init = function(testUtils) { <ide> finish = testUtils.finish; <ide> valueOf = testUtils.valueOf; <add> alarmObj = require('Ti/Tizen/Alarm'); <ide> } <ide> <ide> this.name = 'alarm'; <ide> tizenArr, <ide> date = new Date(2012, 12, 21, 8, 0); <ide> <del> Ti.Tizen.Alarm.removeAll(); <add> alarmObj.removeAll(); <ide> <ide> // Alarm in 10 seconds (relative) <del> alarm = Ti.Tizen.Alarm.createAlarmRelative({ <add> alarm = alarmObj.createAlarmRelative({ <ide> delay: 10 <ide> }); <ide> <del> valueOf(testRun, alarm instanceof Ti.Tizen.Alarm.AlarmRelative).shouldBeTrue(); <del> <del> Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); <add> valueOf(testRun, alarm instanceof Tizen.Alarm.AlarmRelative).shouldBeTrue(); <add> <add> alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); <ide> <ide> // Set an alarm on December 21st 2012 08:00 <del> alarm = Ti.Tizen.Alarm.createAlarmAbsolute({ <add> alarm = alarmObj.createAlarmAbsolute({ <ide> date: date <ide> }); <ide> <del> valueOf(testRun, alarm instanceof Ti.Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); <del> <del> Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); <del> <del> tizenArr = Ti.Tizen.Alarm.getAll(); <del> <del> valueOf(testRun, (tizenArr[0] instanceof Ti.Tizen.Alarm.AlarmAbsolute || tizenArr[0] instanceof Ti.Tizen.Alarm.AlarmRelative)).shouldBeTrue(); <add> valueOf(testRun, alarm instanceof Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); <add> <add> alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); <add> <add> tizenArr = alarmObj.getAll(); <add> <add> valueOf(testRun, (tizenArr[0] instanceof Tizen.Alarm.AlarmAbsolute || tizenArr[0] instanceof Tizen.Alarm.AlarmRelative)).shouldBeTrue(); <ide> <ide> valueOf(testRun, tizenArr.length).shouldBe(2); <ide> <ide> absolute_id, <ide> date = new Date(2012, 12, 21, 8, 0); <ide> <del> Ti.Tizen.Alarm.removeAll(); <add> alarmObj.removeAll(); <ide> <ide> // Alarm in 10 seconds (relative) <del> alarm = Ti.Tizen.Alarm.createAlarmRelative({ <add> alarm = alarmObj.createAlarmRelative({ <ide> delay: 10 <ide> }); <ide> <ide> // Set an alarm on December 21st 2012 08:00 <del> alarm1 = Ti.Tizen.Alarm.createAlarmAbsolute({ <add> alarm1 = alarmObj.createAlarmAbsolute({ <ide> date: date <ide> }); <ide> <del> Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); <del> Ti.Tizen.Alarm.add(alarm1, 'http://tizen.org/alarm-clock'); <add> alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); <add> alarmObj.add(alarm1, 'http://tizen.org/alarm-clock'); <ide> <ide> relative_id = alarm.id; <ide> absolute_id = alarm1.id; <ide> <ide> valueOf(testRun, function() { <del> alarm2 = Ti.Tizen.Alarm.get(relative_id); <del> alarm3 = Ti.Tizen.Alarm.get(absolute_id); <add> alarm2 = alarmObj.get(relative_id); <add> alarm3 = alarmObj.get(absolute_id); <ide> }).shouldNotThrowException(); <ide> <del> valueOf(testRun, alarm2 instanceof Ti.Tizen.Alarm.AlarmRelative).shouldBeTrue(); <del> valueOf(testRun, alarm3 instanceof Ti.Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); <del> <del> Ti.Tizen.Alarm.removeAll(); <del> <del> valueOf(testRun, function() { <del> var alarmTmp = Ti.Tizen.Alarm.get(absolute_id); <del> valueOf(testRun, alarm instanceof Ti.Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); <add> valueOf(testRun, alarm2 instanceof Tizen.Alarm.AlarmRelative).shouldBeTrue(); <add> valueOf(testRun, alarm3 instanceof Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); <add> <add> alarmObj.removeAll(); <add> <add> valueOf(testRun, function() { <add> var alarmTmp = alarmObj.get(absolute_id); <add> valueOf(testRun, alarm instanceof Tizen.Alarm.AlarmAbsolute).shouldBeTrue(); <ide> <del> alarmTmp = Ti.Tizen.Alarm.get(relative_id); <add> alarmTmp = alarmObj.get(relative_id); <ide> }).shouldThrowException(); <ide> <ide> finish(testRun); <ide> absolute_id, <ide> date = new Date(2012, 12, 21, 8, 0); <ide> <del> Ti.Tizen.Alarm.removeAll(); <del> alarmArr = Ti.Tizen.Alarm.getAll(); <add> alarmObj.removeAll(); <add> alarmArr = alarmObj.getAll(); <ide> valueOf(testRun, alarmArr.length).shouldBe(0); <ide> <ide> //Alarm in 10 seconds (relative) <del> alarm = Ti.Tizen.Alarm.createAlarmRelative({ <add> alarm = alarmObj.createAlarmRelative({ <ide> delay: 10 <ide> }); <del> alarm1 = Ti.Tizen.Alarm.createAlarmAbsolute({ <add> alarm1 = alarmObj.createAlarmAbsolute({ <ide> date: date <ide> }); <del> Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); <del> Ti.Tizen.Alarm.add(alarm1, 'http://tizen.org/alarm-clock'); <add> alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); <add> alarmObj.add(alarm1, 'http://tizen.org/alarm-clock'); <ide> relative_id = alarm.id; <ide> absolute_id = alarm1.id; <ide> <ide> valueOf(testRun, function() { <del> Ti.Tizen.Alarm.remove(absolute_id); <add> alarmObj.remove(absolute_id); <ide> }).shouldNotThrowException(); <ide> <ide> valueOf(testRun, function() { <del> Ti.Tizen.Alarm.remove(absolute_id); <add> alarmObj.remove(absolute_id); <ide> }).shouldThrowException(); <ide> <ide> finish(testRun); <ide> this.alarmRelative = function(testRun) { <ide> var alarm, <ide> alarmId, <del> delay = 2 * Ti.Tizen.Alarm.PERIOD_MINUTE, <del> period = Ti.Tizen.Alarm.PERIOD_HOUR; <del> <del> Ti.Tizen.Alarm.removeAll(); <del> alarm = Ti.Tizen.Alarm.createAlarmRelative({ <add> delay = 2 * alarmObj.PERIOD_MINUTE, <add> period = alarmObj.PERIOD_HOUR; <add> <add> alarmObj.removeAll(); <add> alarm = alarmObj.createAlarmRelative({ <ide> delay: delay, <ide> period: period <ide> }); <del> Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); <add> alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); <ide> alarmId = alarm.id; <ide> <ide> valueOf(testRun, function() { <ide> }).shouldNotThrowException(); <ide> valueOf(testRun, alarm.delay).shouldBe(delay); <ide> <del> alarm = Ti.Tizen.Alarm.get(alarmId); <add> alarm = alarmObj.get(alarmId); <ide> <ide> valueOf(testRun, function() { <ide> var fromReaming = alarm.getRemainingSeconds(); <ide> } <ide> <ide> this.alarmAbsolute = function(testRun) { <del> Ti.Tizen.Alarm.removeAll(); <add> alarmObj.removeAll(); <ide> <ide> var alarm, <ide> alarmId, <ide> fromReaming, <ide> date = new Date(), <ide> time = date.getTime() + 60000, <del> period = Ti.Tizen.Alarm.PERIOD_HOUR; <add> period = alarmObj.PERIOD_HOUR; <ide> <ide> date.setTime(time); <del> alarm = Ti.Tizen.Alarm.createAlarmAbsolute({ <add> alarm = alarmObj.createAlarmAbsolute({ <ide> date: date, period: period <ide> }); <del> Ti.Tizen.Alarm.add(alarm, 'http://tizen.org/alarm-clock'); <add> alarmObj.add(alarm, 'http://tizen.org/alarm-clock'); <ide> alarmId = alarm.id; <ide> remaining = alarm.getNextScheduledDate(); <ide> <ide> valueOf(testRun, remaining.toDateString()).shouldBe(alarm.date.toDateString()); <ide> <del> alarmFrom = Ti.Tizen.Alarm.get(alarmId), <add> alarmFrom = alarmObj.get(alarmId), <ide> fromReaming = alarmFrom.getNextScheduledDate(); <ide> <ide> valueOf(testRun, fromReaming.toDateString()).shouldBe(date.toDateString()); <ide> <del> Ti.Tizen.Alarm.removeAll(); <add> alarmObj.removeAll(); <ide> finish(testRun); <ide> } <ide> }
Java
epl-1.0
21377984842c4fdcec52246f62a2a132ac4fe897
0
ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio,css-iter/cs-studio,ControlSystemStudio/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,css-iter/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ESSICS/cs-studio,ControlSystemStudio/cs-studio,css-iter/cs-studio,css-iter/cs-studio
/* * Copyright (c) 2006 Stiftung Deutsches Elektronen-Synchroton, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.sds.components.ui.internal.figures; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.csstudio.sds.ui.figures.IBorderEquippedWidget; import org.csstudio.sds.ui.figures.IRefreshableFigure; import org.csstudio.sds.uil.CustomMediaFactory; import org.eclipse.draw2d.BorderLayout; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.FigureListener; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.Panel; import org.eclipse.draw2d.RectangleFigure; import org.eclipse.draw2d.ToolbarLayout; import org.eclipse.draw2d.XYLayout; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; /** * A bargraph figure. * * @author Kai Meyer * */ public final class RefreshableBargraphFigure extends RectangleFigure implements IRefreshableFigure { /** * Height of the text. */ private static final int TEXTHEIGHT = 24; /** * Width of the text. */ private static final int TEXTWIDTH = 46; /** * The Strings, which are displayed in this figure. */ private static final String[] LABELS = new String[] {"LOLO", "LO", "M", "HI", "HIHI"}; // /** // * Don't show markers. // */ // private static final int NONE = 0; /** * Show markers at bottom or right. */ private static final int BOTTOM_RIGHT = 1; /** * Show markers at top or left. */ private static final int TOP_LEFT = 2; /** * Minimum value for this figure. */ private double _minimum = 0.0; /** * Maximum value for this figure. */ private double _maximum = 1.0; /** * The boolean, which indicates, if the values should be shown or not. */ private boolean _showValues = false; /** * The int, which indicates, how the marks should be shown. */ private int _showMarks = BOTTOM_RIGHT; /** * The int, which indicates, how the scale should be shown. */ private int _showScale = BOTTOM_RIGHT; /** * The count of sections in the scale. */ private int _scaleSectionCount = 1; /** * The default height of this figure. */ private static final int DEFAULT_HEIGHT = 30; /** * The default width of this figure. */ private static final int DEFAULT_WIDTH = 200; /** * The orientation (horizontal==true | vertical==false). */ private boolean _orientationHorizontal = true; /** * The Color for the border. */ private Color _borderColor; /** * The Map for the Colors. */ private final Map<String, Color> _colorMap = new HashMap<String, Color>(); /** * The Map for the levels. */ private final Map<String, Double> _levelMap = new HashMap<String, Double>(); /** * A border adapter, which covers all border handlings. */ private IBorderEquippedWidget _borderAdapter; /** * The Scale of this figure. */ private Scale _scale; /** * The MarkerPanel of this figure. */ private MarkerPanel _markerPanel; /** * The FillRectangle of this figure. */ private FillRectangleFigure _fillRectangleFigure; /** * The Rectangle for the FillRectangleFigure. */ private Rectangle _barRectangle; /** * The wideness of the Scale. */ private int _scaleWideness = 10; /** * Constructor. * */ public RefreshableBargraphFigure() { super(); this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); this.initColorMap(); this.initLevelMap(); this.setLayoutManager(new XYLayout()); _fillRectangleFigure = new FillRectangleFigure(); _markerPanel = new MarkerPanel(_showMarks==TOP_LEFT, _orientationHorizontal); _scale = new Scale(); this.add(_fillRectangleFigure); this.add(_markerPanel); this.add(_scale); this.refreshConstraints(); // listen to figure movement events addFigureListener(new FigureListener() { public void figureMoved(final IFigure source) { refreshConstraints(); } }); } /** * Initializes the Map of Colors. */ private void initColorMap() { _colorMap.put(LABELS[0], CustomMediaFactory.getInstance().getColor(new RGB(255,0,0))); _colorMap.put(LABELS[1], CustomMediaFactory.getInstance().getColor(new RGB(255,100,100))); _colorMap.put(LABELS[2], CustomMediaFactory.getInstance().getColor(new RGB(0,255,0))); _colorMap.put(LABELS[3], CustomMediaFactory.getInstance().getColor(new RGB(255,255,0))); _colorMap.put(LABELS[4], CustomMediaFactory.getInstance().getColor(new RGB(255,255,255))); } /** * Initializes the Map of levels. */ private void initLevelMap() { _levelMap.put(LABELS[0], Double.valueOf(0.1)); _levelMap.put(LABELS[1], Double.valueOf(0.3)); _levelMap.put(LABELS[2], Double.valueOf(0.5)); _levelMap.put(LABELS[3], Double.valueOf(0.7)); _levelMap.put(LABELS[4], Double.valueOf(0.9)); } /** * {@inheritDoc} */ public synchronized void paintFigure(final Graphics graphics) { graphics.setBackgroundColor(this.getBackgroundColor()); graphics.fillRectangle(this.getBounds()); //this.refreshConstraints(); graphics.setBackgroundColor(this.getBackgroundColor()); graphics.setForegroundColor(this.getBorderColor()); this.setToolTip(this.getToolTipFigure()); } /** * Gets the IFigure for the tooltip. * @return IFigure * The IFigure for the tooltip */ private IFigure getToolTipFigure() { Panel panel = new Panel(); panel.setLayoutManager(new ToolbarLayout(false)); panel.add(new Label("Fill level: "+this.getFill()+"%")); panel.add(new Label("Minimum value: "+_minimum)); panel.add(new Label("Maximum value: "+_maximum)); for (int i=0;i<LABELS.length;i++) { panel.add(new Label(LABELS[i]+" level: "+_levelMap.get(LABELS[i]))); } panel.setBackgroundColor(ColorConstants.tooltipBackground); return panel; } /** * Refreshes the Constraints. */ private void refreshConstraints() { _barRectangle = this.getBarRectangle(); this.setConstraint(_fillRectangleFigure, _barRectangle); this.setConstraint(_markerPanel, this.getMarkerPanelConstraint(this.getBounds())); this.setConstraint(_scale, this.getScaleConstraint(this.getBounds())); } /** * Gets the Constraints for the MarkerPanel. * @param bounds * The bounds for the MarkerPanel * @return The constraints for the MarkerPanel */ private Rectangle getMarkerPanelConstraint(final Rectangle bounds) { if (_orientationHorizontal) { _markerPanel.setReferencePositions(_barRectangle.x, _barRectangle.x+_barRectangle.width); if (_showMarks==BOTTOM_RIGHT) { return new Rectangle(1,bounds.height-TEXTHEIGHT,bounds.width-2,TEXTHEIGHT-2); } if (_showMarks==TOP_LEFT) { return new Rectangle(1,1,bounds.width-2,TEXTHEIGHT-1); } } else { _markerPanel.setReferencePositions(_barRectangle.y, _barRectangle.y+_barRectangle.height); if (_showMarks==BOTTOM_RIGHT) { return new Rectangle(_barRectangle.width,1,TEXTWIDTH-1,bounds.height-2); } if (_showMarks==TOP_LEFT) { return new Rectangle(1,1,TEXTWIDTH-1,bounds.height-2); } } return new Rectangle(0,0,0,0); } /** * Gets the constraints for the Scale. * @param bounds * The bounds for the Scale * @return Rectangle * The Constraints for the Scale */ private Rectangle getScaleConstraint(final Rectangle bounds) { _scale.setHorizontalOrientation(_orientationHorizontal); if (_orientationHorizontal) { _scale.setLength(_barRectangle.width); _scale.setReferencePositions(_barRectangle.x); if (_showScale==BOTTOM_RIGHT) { return new Rectangle(0,_barRectangle.y+_barRectangle.height-_scaleWideness-1,bounds.width,_scaleWideness); } if (_showScale==TOP_LEFT) { return new Rectangle(0,_barRectangle.y,bounds.width,_scaleWideness); } } else { _scale.setLength(_barRectangle.height); _scale.setReferencePositions(_barRectangle.y); if (_showScale==BOTTOM_RIGHT) { return new Rectangle(_barRectangle.x+_barRectangle.width-_scaleWideness,0,_scaleWideness,bounds.height); } if (_showScale==TOP_LEFT) { return new Rectangle(_barRectangle.x,0,_scaleWideness,bounds.height); } } return new Rectangle(0,0,0,0); } /** * Calculate the real length of this bargraph. * The value is calculated, to fit the scale completly into the bargraph * @param length * The given length * @return int * The new length */ private int calculateRealLength(final int length) { int neededScaleLines = _scaleSectionCount + 1; return length - ((length - neededScaleLines) % _scaleSectionCount); } /** * Gets the rectangle for the bargraph. * @return Rectangle * The rectangle for the bargraph */ private Rectangle getBarRectangle() { Rectangle bounds = this.getBounds(); int yCorrection = 0; int heightCorrection = 0; int xCorrection = 0; int widthCorrection = 0; if (_orientationHorizontal) { if (_showMarks==TOP_LEFT) { yCorrection = TEXTHEIGHT; xCorrection = (TEXTWIDTH/2); } if (_showMarks==BOTTOM_RIGHT) { heightCorrection = TEXTHEIGHT; xCorrection = (TEXTWIDTH/2); } // if (_showValues) { // yCorrection = yCorrection*2; // heightCorrection = heightCorrection*2; // } return new Rectangle(xCorrection,yCorrection,this.calculateRealLength(bounds.width-2*xCorrection),bounds.height-(yCorrection+heightCorrection)); } if (_showMarks==TOP_LEFT) { xCorrection = TEXTWIDTH; yCorrection = TEXTHEIGHT/2; } if (_showMarks==BOTTOM_RIGHT) { widthCorrection = TEXTWIDTH; yCorrection = TEXTHEIGHT/2; } // if (_showValues) { // xCorrection = xCorrection*2-10; // widthCorrection = widthCorrection*2; // } return new Rectangle(xCorrection,yCorrection,bounds.width-(xCorrection+widthCorrection),this.calculateRealLength(bounds.height-2*yCorrection)); } /** * Gets the weight (0.0 - 1.0) for the value. * @param value * The value, which weight should be calculated. * @return double * The weight for the value */ private double getWeight(final double value) { double max = _maximum-_minimum; if (max==0) { max = 0.001; } return (value-_minimum) / max; } /** * {@inheritDoc} */ public void randomNoiseRefresh() { this.setFill(Math.random() * 100); repaint(); } /** * {@inheritDoc} */ @Override public void setBackgroundColor(final Color bg) { _markerPanel.setBackgroundColor(bg); super.setBackgroundColor(bg); } /** * Sets the color for the border. * @param borderRGB * The RGB-value of the Color for the border */ public void setBorderColor(final RGB borderRGB) { _borderColor = CustomMediaFactory.getInstance().getColor(borderRGB); _fillRectangleFigure.setBorderColor(_borderColor); } /** * Gets the color for the border. * @return Color * The color for the border */ public Color getBorderColor() { return _borderColor; } /** * Sets the default fill Color. * @param defaultFillRGB * The RGB-value of the default fill Color */ public void setDefaultFillColor(final RGB defaultFillRGB) { _fillRectangleFigure.setDefaultFillColor(CustomMediaFactory.getInstance().getColor(defaultFillRGB)); } /** * Gets the default fill Color. * @return Color * The color default fill Color */ public Color getDefaultFillColor() { return _fillRectangleFigure.getDefaultFillColor(); } /** * Sets the color for the backgrounf of the fill-area. * @param fillBackgroundRGB * The RGB-value of the Color for the backgrounf of the fill-area */ public void setFillBackgroundColor(final RGB fillBackgroundRGB) { _fillRectangleFigure.setBackgroundColor(CustomMediaFactory.getInstance().getColor(fillBackgroundRGB)); } /** * Gets the color for the backgrounf of the fill-area. * @return Color * The color for the backgrounf of the fill-area */ public Color getFillBackgroundColor() { return _fillRectangleFigure.getBackgroundColor(); } /** * Sets the fill grade. * * @param fill * The fill grade. */ public void setFill(final double fill) { _fillRectangleFigure.setFill(fill/100); } /** * Gets the fill grade. * * @return double * The fill grade */ public double getFill() { return _fillRectangleFigure.getFill(); } /** * Sets the orientation (horizontal==true | vertical==false). * * @param horizontal * The orientation. */ public void setOrientation(final boolean horizontal) { _orientationHorizontal = horizontal; _scale.setHorizontalOrientation(_orientationHorizontal); _markerPanel.setHorizontalOrientation(horizontal); this.refreshConstraints(); } /** * Gets the orientation (horizontal==true | vertical==false). * * @return boolean * The orientation */ public boolean getOrientation() { return _orientationHorizontal; } /** * Sets the color for lolo fill level. * @param rgb * The color for lolo fill level */ public void setLoloColor(final RGB rgb) { _colorMap.put(LABELS[0], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for lolo fill level. * @return Color * The color for lolo fill level */ public Color getLoloColor() { return _colorMap.get(LABELS[0]); } /** * Sets the color for lo fill level. * @param rgb * The color for lo fill level */ public void setLoColor(final RGB rgb) { _colorMap.put(LABELS[1], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for lo fill level. * @return Color * The color for lo fill level */ public Color getLoColor() { return _colorMap.get(LABELS[1]); } /** * Sets the color for m fill level. * @param rgb * The color for m fill level */ public void setMColor(final RGB rgb) { _colorMap.put(LABELS[2], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for m fill level. * @return Color * The color for m fill level */ public Color getMColor() { return _colorMap.get(LABELS[2]); } /** * Sets the color for hi fill level. * @param rgb * The color for hi fill level */ public void setHiColor(final RGB rgb) { _colorMap.put(LABELS[3], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for hi fill level. * @return Color * The color for hi fill level */ public Color getHiColor() { return _colorMap.get(LABELS[3]); } /** * Sets the color for hihi fill level. * @param rgb * The color for hihi fill level */ public void setHihiColor(final RGB rgb) { _colorMap.put(LABELS[4], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for hihi fill level. * @return Color * The color for hihi fill level */ public Color getHihiColor() { return _colorMap.get(LABELS[4]); } /** * Sets the minimum value. * @param min * The minimum value */ public void setMinimum(final double min) { _minimum = min; this.refreshConstraints(); } /** * Gets the minimum value. * @return double * The minimum value */ public double getMinimum() { return _minimum; } /** * Sets the lolo level. * @param loloLevel * The lolo level */ public void setLoloLevel(final double loloLevel) { _levelMap.put(LABELS[0], loloLevel); this.refreshConstraints(); } /** * Gets the lolo level. * @return double * The lolo level */ public double getLoloLevel() { return _levelMap.get(LABELS[0]); } /** * Sets the lo level. * @param loLevel * The lo level */ public void setLoLevel(final double loLevel) { _levelMap.put(LABELS[1], loLevel); this.refreshConstraints(); } /** * Gets the lo level. * @return double * The lo level */ public double getLoLevel() { return _levelMap.get(LABELS[1]); } /** * Sets the m level. * @param mLevel * The m level */ public void setMLevel(final double mLevel) { _levelMap.put(LABELS[2], mLevel); this.refreshConstraints(); } /** * Gets the m level. * @return double * The m level */ public double getMLevel() { return _levelMap.get(LABELS[2]); } /** * Sets the hi level. * @param hiLevel * The hi level */ public void setHiLevel(final double hiLevel) { _levelMap.put(LABELS[3], hiLevel); this.refreshConstraints(); } /** * Gets the hi level. * @return double * The hi level */ public double getHiLevel() { return _levelMap.get(LABELS[3]); } /** * Sets the hihi level. * @param hihiLevel * The hihi level */ public void setHihiLevel(final double hihiLevel) { _levelMap.put(LABELS[4], hihiLevel); this.refreshConstraints(); } /** * Gets the hihi level. * @return double * The hihi level */ public double getHihiLevel() { return _levelMap.get(LABELS[4]); } /** * Sets the maximum value. * @param max * The maximum value */ public void setMaximum(final double max) { _maximum = max; this.refreshConstraints(); } /** * Gets the maximum value. * @return double * The maximum value */ public double getMaximum() { return _maximum; } /** * Sets, if the values should be shown. * @param showValues * True, if the values should be shown, false otherwise */ public void setShowValues(final boolean showValues) { _showValues = showValues; } /** * Gets, if the values should be shown. * @return boolean * True, if the values should be shown, false otherwise */ public boolean getShowValues() { return _showValues; } /** * Sets, how the marks should be shown. * @param showMarks * 0 = don't show, 1 = show Bottom/Right, 2 = show Top/Left */ public void setShowMarks(final int showMarks) { _showMarks = showMarks; _markerPanel.setTopLeftAlignment(showMarks==TOP_LEFT); this.refreshConstraints(); } /** * Gets, how the marks should be shown. * @return boolean * 0 = don't show, 1 = show Bottom/Right, 2 = show Top/Left */ public int getShowMarks() { return _showMarks; } /** * Sets, how the scale should be shown. * @param showScale * 0 = don't show, 1 = show Bottom/Right, 2 = show Top/Left */ public void setShowScale(final int showScale) { _showScale = showScale; this.refreshConstraints(); } /** * Gets, how the scale should be shown. * @return int * 0 = don't show, 1 = show Bottom/Right, 2 = show Top/Left */ public int getShowScale() { return _showScale; } /** * Sets the count of sections in the scale. * @param scaleSectionCount * The count of sections in the scale */ public void setScaleSectionCount(final int scaleSectionCount) { _scaleSectionCount = scaleSectionCount; _scale.setSectionCount(scaleSectionCount); this.refreshConstraints(); } /** * Gets the count of sections in the scale. * @return int * The count of sections in the scale. */ public int getScaleSectionCount() { return _scaleSectionCount; } /** * {@inheritDoc} */ public Object getAdapter(final Class adapter) { if (adapter == IBorderEquippedWidget.class) { if(_borderAdapter==null) { _borderAdapter = new BorderAdapter(this); } return _borderAdapter; } return null; } /** * This class represents the bargraph. * * @author Kai Meyer */ private final class FillRectangleFigure extends RectangleFigure { /** * The fill grade (0 - 1). */ private double _fillGrade = 0.5; /** * The default fill Color. */ private Color _defaultFillColor; /** * The Color for the border. */ private Color _borderColor; /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { Rectangle bounds = this.getBounds(); graphics.setForegroundColor(this.getForegroundColor()); graphics.setBackgroundColor(this.getBackgroundColor()); graphics.fillRectangle(bounds); graphics.setBackgroundColor(this.getFillColor()); Rectangle fillRectangle = this.getFillLevelRectangle(bounds); graphics.fillRectangle(fillRectangle); graphics.setForegroundColor(this.getBorderColor()); graphics.drawRectangle(new Rectangle(bounds.x,bounds.y,bounds.width-1,bounds.height-1)); graphics.drawRectangle(new Rectangle(fillRectangle.x,fillRectangle.y,fillRectangle.width-1,fillRectangle.height-1)); } /** * Gets the fill Color. * @return Color * The Color for the fill-area */ private Color getFillColor() { List<String> labelList = new LinkedList<String>(); for (int i=0;i<LABELS.length;i++) { if (labelList.isEmpty()) { labelList.add(LABELS[i]); } else { labelList.add(this.getLabelIndex(labelList, LABELS[i]), LABELS[i]); } } String[] tempLabels = labelList.toArray(new String[labelList.size()]); if (_minimum<_maximum) { for (int i=0; i<tempLabels.length;i++) { if (this.getFill()<=getWeight(_levelMap.get(tempLabels[i]))) { return _colorMap.get(tempLabels[i]); } } return this.getDefaultFillColor(); } else { for (int i=tempLabels.length-1; i>=0;i--) { if (this.getFill()<=getWeight(_levelMap.get(tempLabels[i]))) { return _colorMap.get(tempLabels[i]); } } return this.getDefaultFillColor(); } } /** * Gets the index for the label. * @param labelList * The list, where the label should be added * @param label * The label, which should be added * @return int * The index for the label */ private int getLabelIndex(final List<String> labelList, final String label) { for (int j=0;j<labelList.size();j++) { if (_levelMap.get(label)<_levelMap.get(labelList.get(j))) { return j; } } return labelList.size(); } /** * Gets the rectangle for the fill level. * @param area * The rectangle of the bargraph * @return Rectangle * The rectangle for the fill level */ private Rectangle getFillLevelRectangle(final Rectangle area) { if (_orientationHorizontal) { int newW = (int) Math.round(area.width * (this.getFill())); return new Rectangle(area.getLocation(),new Dimension(newW, area.height)); } int newH = (int) Math.round(area.height * (this.getFill())); return new Rectangle(area.x,area.y+area.height-newH,area.width,newH); } /** * Sets the fill grade. * * @param fill * The fill grade. */ public void setFill(final double fill) { _fillGrade = fill; } /** * Gets the fill grade. * * @return double * The fill grade */ public double getFill() { return _fillGrade; } /** * Sets the default fill Color. * @param defaultFillColor * The default fill Color */ public void setDefaultFillColor(final Color defaultFillColor) { _defaultFillColor = defaultFillColor; } /** * Gets the default fill Color. * @return Color * The color default fill Color */ public Color getDefaultFillColor() { return _defaultFillColor; } /** * Sets the color for the border. * @param borderColor * The Color for the border */ public void setBorderColor(final Color borderColor) { _borderColor = borderColor; } /** * Gets the color for the border. * @return Color * The color for the border */ public Color getBorderColor() { return _borderColor; } } /** * This Figure contains the Markers. * * @author Kai Meyer */ private final class MarkerPanel extends Panel { /** * The List of Markers. */ private final List<Marker> _markerList = new LinkedList<Marker>(); /** * The alignment for the Markers. */ private boolean _topLeft; /** * The orientation of theis figure. */ private boolean _isHorizontal; /** * The start position. */ private int _start = 10; /** * The end position. */ private int _end = 100; /** * Constructor. * @param topLeft * true, if the Marker is on top/left of the bargraph, false otherwise * @param isHorizontal * true, if the Marker has a horizontal orientation */ public MarkerPanel(final boolean topLeft, final boolean isHorizontal) { this.setLayoutManager(new XYLayout()); _topLeft = topLeft; _isHorizontal = isHorizontal; Marker marker = null; for (int i=0;i<LABELS.length;i++) { marker = new Marker(LABELS[i], _topLeft, _isHorizontal); marker.setForegroundColor(this.getForegroundColor()); this.add(marker); _markerList.add(marker); } // listen to figure movement events addFigureListener(new FigureListener() { public void figureMoved(final IFigure source) { refreshConstraints(); } }); this.refreshConstraints(); } /** * Refreshes the constraints. */ private void refreshConstraints() { if (_isHorizontal) { for (int i=0;i<_markerList.size();i++) { double weight = getWeight(_levelMap.get(LABELS[i])); if (weight<0 || weight>1) { this.setConstraint(_markerList.get(i), new Rectangle(0,0,0,0)); } else { int x = _start + (int)((_end-_start)*weight)-1 - TEXTWIDTH/2; this.setConstraint(_markerList.get(i), new Rectangle(x,0,TEXTWIDTH, bounds.height )); } } } else { for (int i=0;i<_markerList.size();i++) { double weight = getWeight(_levelMap.get(LABELS[i])); if (weight<0 || weight>1) { this.setConstraint(_markerList.get(i), new Rectangle(0,0,0,0)); } else { int y = _start + (int) ((_end-_start)*(1-weight)) - TEXTHEIGHT/2; this.setConstraint(_markerList.get(i), new Rectangle(1, y, bounds.width, TEXTHEIGHT)); } } } } /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { Rectangle bounds = this.getBounds(); graphics.setBackgroundColor(this.getBackgroundColor()); graphics.setForegroundColor(ColorConstants.black); graphics.fillRectangle(bounds); } /** * Sets the reference values for this figure. * @param start * The start value * @param end * The end value */ public void setReferencePositions(final int start, final int end) { _start = start; _end = end; this.refreshConstraints(); } /** * Sets the orientation of this figure. * @param isHorizontal * The orientation of this figure (true=horizontal;false=vertical) */ public void setHorizontalOrientation(final boolean isHorizontal) { _isHorizontal = isHorizontal; for (Marker marker : _markerList) { marker.setHorizontalOrientation(isHorizontal); } this.refreshConstraints(); } /** * Sets the alignment of this figure. * @param topLeft * The alignment of this figure (true=top/left;false=bottom/right) */ public void setTopLeftAlignment(final boolean topLeft) { _topLeft = topLeft; for (Marker marker : _markerList) { marker.setTopLeftAlignment(topLeft); } this.refreshConstraints(); } } /** * This class represents a Marker. * * @author Kai Meyer * */ private final class Marker extends RectangleFigure { /** * The key of this Marker, which is the drwaed text. */ private String _key; /** * The orientation of this Marker. */ private boolean _isHorizontal; /** * The alignment of this Marker. */ private boolean _topLeft; /** * The Label for the text. */ private Label _textLabel; /** * The Tipmark. */ private TipMark _tipMark; /** * Construktor. * @param key * The text to display * @param topLeft * True, if the marker should be above the y value, false otherwise * @param isHorizontal * True, if the marker should have a horizontal orientation, false otherwise */ public Marker(final String key, final boolean topLeft, final boolean isHorizontal) { BorderLayout borderLayout = new BorderLayout(); this.setLayoutManager(borderLayout); _key = key; _textLabel = new Label(key.toString()); _textLabel.setForegroundColor(this.getForegroundColor()); _tipMark = new TipMark(); _tipMark.setForegroundColor(this.getForegroundColor()); _tipMark.setBackgroundColor(_colorMap.get(_key)); this.add(_tipMark, BorderLayout.CENTER); this.refreshLabel(); } /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { //nothing to do; }; /** * Sets the orientation of this figure. * @param isHorizontal * The orientation of this figure (true=horizontal;false=vertical) */ public void setHorizontalOrientation(final boolean isHorizontal) { _isHorizontal = isHorizontal; _tipMark.setHorizontalOrientation(isHorizontal); this.refreshLabel(); } /** * Sets the alignment of this figure. * @param topLeft * The alignment of this figure (true=top/left;false=bottom/right) */ public void setTopLeftAlignment(final boolean topLeft) { _topLeft = topLeft; _tipMark.setTopLeftAlignment(topLeft); this.refreshLabel(); } /** * Refreshes the Label. */ private void refreshLabel() { if (this.getChildren().contains(_textLabel)) { this.remove(_textLabel); } Integer place; if (_isHorizontal) { if (_topLeft) { place = BorderLayout.TOP; } else { place = BorderLayout.BOTTOM; } } else { if (_topLeft) { place = BorderLayout.LEFT; } else { place = BorderLayout.RIGHT; } } this.add(_textLabel, place); } /** * This class represents a tipmark. * @author Kai Meyer */ private final class TipMark extends RectangleFigure { /** * The width of this marker. */ private int _width; /** * The height of this marker. */ private int _height; /** * The direction of this Marker. */ private int _direction = 1; /** * The orientation of this Marker. */ private boolean _isHorizontal; /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { //System.out.println("TipMark.paintFigure()"); Rectangle bounds = this.getBounds(); graphics.setForegroundColor(this.getForegroundColor()); graphics.setBackgroundColor(_colorMap.get(_key)); PointList pointList = new PointList(); int x; int y; if (_isHorizontal) { x = bounds.x+bounds.width/2; y = bounds.y; if (_direction<0) { y = y + bounds.height; } pointList.addPoint(x, y); pointList.addPoint(x-_width, y+_height*_direction); pointList.addPoint(x+_width, y+_height*_direction); pointList.addPoint(x, y); } else { x = bounds.x; y = bounds.y+bounds.height/2; if (_direction<0) { x = x + bounds.width-2; } pointList.addPoint(x, y); pointList.addPoint(x+_width*_direction, y-_height); pointList.addPoint(x+_width*_direction, y+_height); pointList.addPoint(x, y); } graphics.fillPolygon(pointList); graphics.drawPolyline(pointList); } /** * Sets the orientation of this figure. * @param isHorizontal * The orientation of this figure (true=horizontal;false=vertical) */ public void setHorizontalOrientation(final boolean isHorizontal) { _isHorizontal = isHorizontal; if (isHorizontal) { _width = 3; _height = 5; } else { _width = 5; _height = 3; } } /** * Sets the alignment of this figure. * @param topLeft * The alignment of this figure (true=top/left;false=bottom/right) */ public void setTopLeftAlignment(final boolean topLeft) { if (topLeft) { _direction = -1; } else { _direction = 1; } } } } /** * This class represents a scale. * * @author Kai Meyer * */ private final class Scale extends RectangleFigure { /** * The length of this Scale. */ private int _length; /** * The count of sections in this Scale. */ private int _sectionCount = -1; /** * The direction of this Scale. */ private boolean _isHorizontal; /** * The start position. */ private int _start = 10; /** * True, if the negativ sections should be draan, false otherwise. */ private boolean _showNegativSections = false; /** * Sets the length of this Scale. * @param length * The lenght of this Scale */ public void setLength(final int length) { _length = length; } /** * Sets the orientation of this Scale. * @param isHorizontal * The orientation of this Scale (true=horizontal;false=vertical) */ public void setHorizontalOrientation(final boolean isHorizontal) { _isHorizontal = isHorizontal; } /** * Sets the count of setcion in this Scale. * @param sectionCount * The count of setcion in this Scale */ public void setSectionCount(final int sectionCount) { _sectionCount = sectionCount; } /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { int sectionWidth = 0; int sectionHeight = 0; int height = 0; int width = 0; graphics.setForegroundColor(this.getForegroundColor()); graphics.setBackgroundColor(this.getBackgroundColor()); if (_isHorizontal) { height = _scaleWideness; if (_sectionCount>0) { sectionWidth = _length/_sectionCount; for (int i=0;i<_sectionCount+1;i++) { graphics.drawLine(this.getBounds().x+_start+i*sectionWidth, this.getBounds().y, this.getBounds().x+_start+i*sectionWidth+width , this.getBounds().y+height); } } else { int pos = _start; while (pos<this.getBounds().width) { graphics.drawLine(this.getBounds().x+pos, this.getBounds().y, this.getBounds().x+pos , this.getBounds().y+height); pos = pos +_length; } if (_showNegativSections) { pos = _start; while (pos>0) { graphics.drawLine(this.getBounds().x, this.getBounds().y+pos, this.getBounds().x+width , this.getBounds().y+pos); pos = pos - _length; } } } } else { width = _scaleWideness; if (_sectionCount>0) { sectionHeight = _length/_sectionCount; for (int i=0;i<_sectionCount+1;i++) { graphics.drawLine(this.getBounds().x, this.getBounds().y+_start+i*sectionHeight, this.getBounds().x+width , this.getBounds().y+_start+i*sectionHeight); } } else { int pos = _start; while (pos<this.getBounds().height) { graphics.drawLine(this.getBounds().x, this.getBounds().y+pos, this.getBounds().x+width , this.getBounds().y+pos); pos = pos +_length; } if (_showNegativSections) { pos = _start; while (pos>0) { graphics.drawLine(this.getBounds().x, this.getBounds().y+pos, this.getBounds().x+width , this.getBounds().y+pos); pos = pos - _length; } } } } } /** * Sets the reference values for this figure. * @param start * The start value */ public void setReferencePositions(final int start) { _start = start; } /** * Sets if the negative sections should be drawn. * @param showNegativ * True, if the negativ sections should be drawn, false otherwise. */ public void setShowNegativeSections(final boolean showNegativ) { _showNegativSections = showNegativ; } } // /** // * This class represents a scale. // * // * @author Kai Meyer // * // */ // private final class Scale extends RectangleFigure { // /** // * The length of this Scale. // */ // private int _length; // /** // * The count of sections in this Scale. // */ // private int _sectionCount; // /** // * The direction of this Scale. // */ // private boolean _isHorizontal; // /** // * The start position. // */ // private int _start = 10; // // /** // * Sets the length of this Scale. // * @param length // * The lenght of this Scale // */ // public void setLength(final int length) { // _length = length; // } // // /** // * Sets the orientation of this Scale. // * @param isHorizontal // * The orientation of this Scale (true=horizontal;false=vertical) // */ // public void setHorizontalOrientation(final boolean isHorizontal) { // _isHorizontal = isHorizontal; // } // // /** // * Sets the count of setcion in this Scale. // * @param sectionCount // * The count of setcion in this Scale // */ // public void setSectionCount(final int sectionCount) { // _sectionCount = sectionCount; // } // // /** // * {@inheritDoc} // */ // @Override // public void paintFigure(final Graphics graphics) { // int sectionWidth = 0; // int sectionHeight = 0; // int height = 0; // int width = 0; // graphics.setForegroundColor(this.getForegroundColor()); // graphics.setBackgroundColor(this.getBackgroundColor()); // if (_isHorizontal) { // height = _scaleWideness; // sectionWidth = _length/_sectionCount; // for (int i=0;i<_sectionCount+1;i++) { // graphics.drawLine(this.getBounds().x+_start+i*sectionWidth, this.getBounds().y, this.getBounds().x+_start+i*sectionWidth+width , this.getBounds().y+height); // } // } else { // width = _scaleWideness; // sectionHeight = _length/_sectionCount; // for (int i=0;i<_sectionCount+1;i++) { // graphics.drawLine(this.getBounds().x, this.getBounds().y+_start+i*sectionHeight, this.getBounds().x+width , this.getBounds().y+_start+i*sectionHeight); // } // } // } // // /** // * Sets the reference values for this figure. // * @param start // * The start value // */ // public void setReferencePositions(final int start) { // _start = start; // } // } }
applications/plugins/org.csstudio.sds.components.ui/src/org/csstudio/sds/components/ui/internal/figures/RefreshableBargraphFigure.java
/* * Copyright (c) 2006 Stiftung Deutsches Elektronen-Synchroton, * Member of the Helmholtz Association, (DESY), HAMBURG, GERMANY. * * THIS SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN "../AS IS" BASIS. * WITHOUT WARRANTY OF ANY KIND, EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR PARTICULAR PURPOSE AND * NON-INFRINGEMENT. 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. SHOULD THE SOFTWARE PROVE DEFECTIVE * IN ANY RESPECT, THE USER ASSUMES THE COST OF ANY NECESSARY SERVICING, REPAIR OR * CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. * NO USE OF ANY SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. * DESY HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, * OR MODIFICATIONS. * THE FULL LICENSE SPECIFYING FOR THE SOFTWARE THE REDISTRIBUTION, MODIFICATION, * USAGE AND OTHER RIGHTS AND OBLIGATIONS IS INCLUDED WITH THE DISTRIBUTION OF THIS * PROJECT IN THE FILE LICENSE.HTML. IF THE LICENSE IS NOT INCLUDED YOU MAY FIND A COPY * AT HTTP://WWW.DESY.DE/LEGAL/LICENSE.HTM */ package org.csstudio.sds.components.ui.internal.figures; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.csstudio.sds.ui.figures.IBorderEquippedWidget; import org.csstudio.sds.ui.figures.IRefreshableFigure; import org.csstudio.sds.uil.CustomMediaFactory; import org.eclipse.draw2d.BorderLayout; import org.eclipse.draw2d.ColorConstants; import org.eclipse.draw2d.FigureListener; import org.eclipse.draw2d.Graphics; import org.eclipse.draw2d.IFigure; import org.eclipse.draw2d.Label; import org.eclipse.draw2d.Panel; import org.eclipse.draw2d.RectangleFigure; import org.eclipse.draw2d.ToolbarLayout; import org.eclipse.draw2d.XYLayout; import org.eclipse.draw2d.geometry.Dimension; import org.eclipse.draw2d.geometry.PointList; import org.eclipse.draw2d.geometry.Rectangle; import org.eclipse.swt.graphics.Color; import org.eclipse.swt.graphics.RGB; /** * A bargraph figure. * * @author Kai Meyer * */ public final class RefreshableBargraphFigure extends RectangleFigure implements IRefreshableFigure { /** * Height of the text. */ private static final int TEXTHEIGHT = 24; /** * Width of the text. */ private static final int TEXTWIDTH = 46; /** * The Strings, which are displayed in this figure. */ private static final String[] LABELS = new String[] {"LOLO", "LO", "M", "HI", "HIHI"}; // /** // * Don't show markers. // */ // private static final int NONE = 0; /** * Show markers at bottom or right. */ private static final int BOTTOM_RIGHT = 1; /** * Show markers at top or left. */ private static final int TOP_LEFT = 2; /** * Minimum value for this figure. */ private double _minimum = 0.0; /** * Maximum value for this figure. */ private double _maximum = 1.0; /** * The boolean, which indicates, if the values should be shown or not. */ private boolean _showValues = false; /** * The int, which indicates, how the marks should be shown. */ private int _showMarks = BOTTOM_RIGHT; /** * The int, which indicates, how the scale should be shown. */ private int _showScale = BOTTOM_RIGHT; /** * The count of sections in the scale. */ private int _scaleSectionCount = 1; /** * The default height of this figure. */ private static final int DEFAULT_HEIGHT = 30; /** * The default width of this figure. */ private static final int DEFAULT_WIDTH = 200; /** * The orientation (horizontal==true | vertical==false). */ private boolean _orientationHorizontal = true; /** * The Color for the border. */ private Color _borderColor; /** * The Map for the Colors. */ private final Map<String, Color> _colorMap = new HashMap<String, Color>(); /** * The Map for the levels. */ private final Map<String, Double> _levelMap = new HashMap<String, Double>(); /** * A border adapter, which covers all border handlings. */ private IBorderEquippedWidget _borderAdapter; /** * The Scale of this figure. */ private Scale _scale; /** * The MarkerPanel of this figure. */ private MarkerPanel _markerPanel; /** * The FillRectangle of this figure. */ private FillRectangleFigure _fillRectangleFigure; /** * The Rectangle for the FillRectangleFigure. */ private Rectangle _barRectangle; /** * The wideness of the Scale. */ private int _scaleWideness = 10; /** * Constructor. * */ public RefreshableBargraphFigure() { super(); this.setSize(DEFAULT_WIDTH, DEFAULT_HEIGHT); this.initColorMap(); this.initLevelMap(); this.setLayoutManager(new XYLayout()); _fillRectangleFigure = new FillRectangleFigure(); _markerPanel = new MarkerPanel(_showMarks==TOP_LEFT, _orientationHorizontal); _scale = new Scale(); this.add(_fillRectangleFigure); this.add(_markerPanel); this.add(_scale); this.refreshConstraints(); // listen to figure movement events addFigureListener(new FigureListener() { public void figureMoved(final IFigure source) { refreshConstraints(); } }); } /** * Initializes the Map of Colors. */ private void initColorMap() { _colorMap.put(LABELS[0], CustomMediaFactory.getInstance().getColor(new RGB(255,0,0))); _colorMap.put(LABELS[1], CustomMediaFactory.getInstance().getColor(new RGB(255,100,100))); _colorMap.put(LABELS[2], CustomMediaFactory.getInstance().getColor(new RGB(0,255,0))); _colorMap.put(LABELS[3], CustomMediaFactory.getInstance().getColor(new RGB(255,255,0))); _colorMap.put(LABELS[4], CustomMediaFactory.getInstance().getColor(new RGB(255,255,255))); } /** * Initializes the Map of levels. */ private void initLevelMap() { _levelMap.put(LABELS[0], Double.valueOf(0.1)); _levelMap.put(LABELS[1], Double.valueOf(0.3)); _levelMap.put(LABELS[2], Double.valueOf(0.5)); _levelMap.put(LABELS[3], Double.valueOf(0.7)); _levelMap.put(LABELS[4], Double.valueOf(0.9)); } /** * {@inheritDoc} */ public synchronized void paintFigure(final Graphics graphics) { graphics.setBackgroundColor(this.getBackgroundColor()); graphics.fillRectangle(this.getBounds()); this.refreshConstraints(); graphics.setBackgroundColor(this.getBackgroundColor()); graphics.setForegroundColor(this.getBorderColor()); this.setToolTip(this.getToolTipFigure()); } /** * Gets the IFigure for the tooltip. * @return IFigure * The IFigure for the tooltip */ private IFigure getToolTipFigure() { Panel panel = new Panel(); panel.setLayoutManager(new ToolbarLayout(false)); panel.add(new Label("Fill level: "+this.getFill()+"%")); panel.add(new Label("Minimum value: "+_minimum)); panel.add(new Label("Maximum value: "+_maximum)); for (int i=0;i<LABELS.length;i++) { panel.add(new Label(LABELS[i]+" level: "+_levelMap.get(LABELS[i]))); } panel.setBackgroundColor(ColorConstants.tooltipBackground); return panel; } /** * Refreshes the Constraints. */ private void refreshConstraints() { _barRectangle = this.getBarRectangle(); this.setConstraint(_fillRectangleFigure, _barRectangle); this.setConstraint(_markerPanel, this.getMarkerPanelConstraint(this.getBounds())); this.setConstraint(_scale, this.getScaleConstraint(this.getBounds())); } /** * Gets the Constraints for the MarkerPanel. * @param bounds * The bounds for the MarkerPanel * @return The constraints for the MarkerPanel */ private Rectangle getMarkerPanelConstraint(final Rectangle bounds) { if (_orientationHorizontal) { _markerPanel.setReferencePositions(_barRectangle.x, _barRectangle.x+_barRectangle.width); if (_showMarks==BOTTOM_RIGHT) { return new Rectangle(1,bounds.height-TEXTHEIGHT,bounds.width-2,TEXTHEIGHT-2); } if (_showMarks==TOP_LEFT) { return new Rectangle(1,1,bounds.width-2,TEXTHEIGHT-1); } } else { _markerPanel.setReferencePositions(_barRectangle.y, _barRectangle.y+_barRectangle.height); if (_showMarks==BOTTOM_RIGHT) { return new Rectangle(_barRectangle.width,1,TEXTWIDTH-1,bounds.height-2); } if (_showMarks==TOP_LEFT) { return new Rectangle(1,1,TEXTWIDTH-1,bounds.height-2); } } return new Rectangle(0,0,0,0); } /** * Gets the constraints for the Scale. * @param bounds * The bounds for the Scale * @return Rectangle * The Constraints for the Scale */ private Rectangle getScaleConstraint(final Rectangle bounds) { _scale.setHorizontalOrientation(_orientationHorizontal); if (_orientationHorizontal) { _scale.setLength(_barRectangle.width); _scale.setReferencePositions(_barRectangle.x); if (_showScale==BOTTOM_RIGHT) { return new Rectangle(0,_barRectangle.y+_barRectangle.height-_scaleWideness-1,bounds.width,_scaleWideness); } if (_showScale==TOP_LEFT) { return new Rectangle(0,_barRectangle.y,bounds.width,_scaleWideness); } } else { _scale.setLength(_fillRectangleFigure.getBounds().height); _scale.setReferencePositions(_barRectangle.y); if (_showScale==BOTTOM_RIGHT) { return new Rectangle(_barRectangle.x+_barRectangle.width-_scaleWideness,0,_scaleWideness,bounds.height); } if (_showScale==TOP_LEFT) { return new Rectangle(_barRectangle.x,0,_scaleWideness,bounds.height); } } return new Rectangle(0,0,0,0); } /** * Calculate the real length of this bargraph. * The value is calculated, to fit the scale completly into the bargraph * @param length * The given length * @return int * The new length */ private int calculateRealLength(final int length) { int neededScaleLines = _scaleSectionCount + 1; return length - ((length - neededScaleLines) % _scaleSectionCount); } /** * Gets the rectangle for the bargraph. * @return Rectangle * The rectangle for the bargraph */ private Rectangle getBarRectangle() { Rectangle bounds = this.getBounds(); int yCorrection = 0; int heightCorrection = 0; int xCorrection = 0; int widthCorrection = 0; if (_orientationHorizontal) { if (_showMarks==TOP_LEFT) { yCorrection = TEXTHEIGHT; xCorrection = (TEXTWIDTH/2); } if (_showMarks==BOTTOM_RIGHT) { heightCorrection = TEXTHEIGHT; xCorrection = (TEXTWIDTH/2); } // if (_showValues) { // yCorrection = yCorrection*2; // heightCorrection = heightCorrection*2; // } return new Rectangle(xCorrection,yCorrection,this.calculateRealLength(bounds.width-2*xCorrection),bounds.height-(yCorrection+heightCorrection)); } if (_showMarks==TOP_LEFT) { xCorrection = TEXTWIDTH; yCorrection = TEXTHEIGHT/2; } if (_showMarks==BOTTOM_RIGHT) { widthCorrection = TEXTWIDTH; yCorrection = TEXTHEIGHT/2; } // if (_showValues) { // xCorrection = xCorrection*2-10; // widthCorrection = widthCorrection*2; // } return new Rectangle(xCorrection,yCorrection,bounds.width-(xCorrection+widthCorrection),this.calculateRealLength(bounds.height-2*yCorrection)); } /** * Gets the weight (0.0 - 1.0) for the value. * @param value * The value, which weight should be calculated. * @return double * The weight for the value */ private double getWeight(final double value) { double max = _maximum-_minimum; if (max==0) { max = 0.001; } return (value-_minimum) / max; } /** * {@inheritDoc} */ public void randomNoiseRefresh() { this.setFill(Math.random() * 100); repaint(); } /** * {@inheritDoc} */ @Override public void setBackgroundColor(final Color bg) { _markerPanel.setBackgroundColor(bg); super.setBackgroundColor(bg); } /** * Sets the color for the border. * @param borderRGB * The RGB-value of the Color for the border */ public void setBorderColor(final RGB borderRGB) { _borderColor = CustomMediaFactory.getInstance().getColor(borderRGB); _fillRectangleFigure.setBorderColor(_borderColor); } /** * Gets the color for the border. * @return Color * The color for the border */ public Color getBorderColor() { return _borderColor; } /** * Sets the default fill Color. * @param defaultFillRGB * The RGB-value of the default fill Color */ public void setDefaultFillColor(final RGB defaultFillRGB) { _fillRectangleFigure.setDefaultFillColor(CustomMediaFactory.getInstance().getColor(defaultFillRGB)); } /** * Gets the default fill Color. * @return Color * The color default fill Color */ public Color getDefaultFillColor() { return _fillRectangleFigure.getDefaultFillColor(); } /** * Sets the color for the backgrounf of the fill-area. * @param fillBackgroundRGB * The RGB-value of the Color for the backgrounf of the fill-area */ public void setFillBackgroundColor(final RGB fillBackgroundRGB) { _fillRectangleFigure.setBackgroundColor(CustomMediaFactory.getInstance().getColor(fillBackgroundRGB)); } /** * Gets the color for the backgrounf of the fill-area. * @return Color * The color for the backgrounf of the fill-area */ public Color getFillBackgroundColor() { return _fillRectangleFigure.getBackgroundColor(); } /** * Sets the fill grade. * * @param fill * The fill grade. */ public void setFill(final double fill) { _fillRectangleFigure.setFill(fill/100); } /** * Gets the fill grade. * * @return double * The fill grade */ public double getFill() { return _fillRectangleFigure.getFill(); } /** * Sets the orientation (horizontal==true | vertical==false). * * @param horizontal * The orientation. */ public void setOrientation(final boolean horizontal) { _orientationHorizontal = horizontal; _scale.setHorizontalOrientation(_orientationHorizontal); _markerPanel.setHorizontalOrientation(horizontal); this.refreshConstraints(); } /** * Gets the orientation (horizontal==true | vertical==false). * * @return boolean * The orientation */ public boolean getOrientation() { return _orientationHorizontal; } /** * Sets the color for lolo fill level. * @param rgb * The color for lolo fill level */ public void setLoloColor(final RGB rgb) { _colorMap.put(LABELS[0], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for lolo fill level. * @return Color * The color for lolo fill level */ public Color getLoloColor() { return _colorMap.get(LABELS[0]); } /** * Sets the color for lo fill level. * @param rgb * The color for lo fill level */ public void setLoColor(final RGB rgb) { _colorMap.put(LABELS[1], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for lo fill level. * @return Color * The color for lo fill level */ public Color getLoColor() { return _colorMap.get(LABELS[1]); } /** * Sets the color for m fill level. * @param rgb * The color for m fill level */ public void setMColor(final RGB rgb) { _colorMap.put(LABELS[2], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for m fill level. * @return Color * The color for m fill level */ public Color getMColor() { return _colorMap.get(LABELS[2]); } /** * Sets the color for hi fill level. * @param rgb * The color for hi fill level */ public void setHiColor(final RGB rgb) { _colorMap.put(LABELS[3], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for hi fill level. * @return Color * The color for hi fill level */ public Color getHiColor() { return _colorMap.get(LABELS[3]); } /** * Sets the color for hihi fill level. * @param rgb * The color for hihi fill level */ public void setHihiColor(final RGB rgb) { _colorMap.put(LABELS[4], CustomMediaFactory.getInstance().getColor(rgb)); } /** * Gets the color for hihi fill level. * @return Color * The color for hihi fill level */ public Color getHihiColor() { return _colorMap.get(LABELS[4]); } /** * Sets the minimum value. * @param min * The minimum value */ public void setMinimum(final double min) { _minimum = min; this.refreshConstraints(); } /** * Gets the minimum value. * @return double * The minimum value */ public double getMinimum() { return _minimum; } /** * Sets the lolo level. * @param loloLevel * The lolo level */ public void setLoloLevel(final double loloLevel) { _levelMap.put(LABELS[0], loloLevel); this.refreshConstraints(); } /** * Gets the lolo level. * @return double * The lolo level */ public double getLoloLevel() { return _levelMap.get(LABELS[0]); } /** * Sets the lo level. * @param loLevel * The lo level */ public void setLoLevel(final double loLevel) { _levelMap.put(LABELS[1], loLevel); this.refreshConstraints(); } /** * Gets the lo level. * @return double * The lo level */ public double getLoLevel() { return _levelMap.get(LABELS[1]); } /** * Sets the m level. * @param mLevel * The m level */ public void setMLevel(final double mLevel) { _levelMap.put(LABELS[2], mLevel); this.refreshConstraints(); } /** * Gets the m level. * @return double * The m level */ public double getMLevel() { return _levelMap.get(LABELS[2]); } /** * Sets the hi level. * @param hiLevel * The hi level */ public void setHiLevel(final double hiLevel) { _levelMap.put(LABELS[3], hiLevel); this.refreshConstraints(); } /** * Gets the hi level. * @return double * The hi level */ public double getHiLevel() { return _levelMap.get(LABELS[3]); } /** * Sets the hihi level. * @param hihiLevel * The hihi level */ public void setHihiLevel(final double hihiLevel) { _levelMap.put(LABELS[4], hihiLevel); this.refreshConstraints(); } /** * Gets the hihi level. * @return double * The hihi level */ public double getHihiLevel() { return _levelMap.get(LABELS[4]); } /** * Sets the maximum value. * @param max * The maximum value */ public void setMaximum(final double max) { _maximum = max; this.refreshConstraints(); } /** * Gets the maximum value. * @return double * The maximum value */ public double getMaximum() { return _maximum; } /** * Sets, if the values should be shown. * @param showValues * True, if the values should be shown, false otherwise */ public void setShowValues(final boolean showValues) { _showValues = showValues; } /** * Gets, if the values should be shown. * @return boolean * True, if the values should be shown, false otherwise */ public boolean getShowValues() { return _showValues; } /** * Sets, how the marks should be shown. * @param showMarks * 0 = don't show, 1 = show Bottom/Right, 2 = show Top/Left */ public void setShowMarks(final int showMarks) { _showMarks = showMarks; _markerPanel.setTopLeftAlignment(showMarks==TOP_LEFT); this.refreshConstraints(); } /** * Gets, how the marks should be shown. * @return boolean * 0 = don't show, 1 = show Bottom/Right, 2 = show Top/Left */ public int getShowMarks() { return _showMarks; } /** * Sets, how the scale should be shown. * @param showScale * 0 = don't show, 1 = show Bottom/Right, 2 = show Top/Left */ public void setShowScale(final int showScale) { _showScale = showScale; this.refreshConstraints(); } /** * Gets, how the scale should be shown. * @return int * 0 = don't show, 1 = show Bottom/Right, 2 = show Top/Left */ public int getShowScale() { return _showScale; } /** * Sets the count of sections in the scale. * @param scaleSectionCount * The count of sections in the scale */ public void setScaleSectionCount(final int scaleSectionCount) { _scaleSectionCount = scaleSectionCount; _scale.setSectionCount(scaleSectionCount); this.refreshConstraints(); } /** * Gets the count of sections in the scale. * @return int * The count of sections in the scale. */ public int getScaleSectionCount() { return _scaleSectionCount; } /** * {@inheritDoc} */ public Object getAdapter(final Class adapter) { if (adapter == IBorderEquippedWidget.class) { if(_borderAdapter==null) { _borderAdapter = new BorderAdapter(this); } return _borderAdapter; } return null; } /** * This class represents the bargraph. * * @author Kai Meyer */ private final class FillRectangleFigure extends RectangleFigure { /** * The fill grade (0 - 1). */ private double _fillGrade = 0.5; /** * The default fill Color. */ private Color _defaultFillColor; /** * The Color for the border. */ private Color _borderColor; /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { Rectangle bounds = this.getBounds(); graphics.setForegroundColor(this.getForegroundColor()); graphics.setBackgroundColor(this.getBackgroundColor()); graphics.fillRectangle(bounds); graphics.setBackgroundColor(this.getFillColor()); Rectangle fillRectangle = this.getFillLevelRectangle(bounds); graphics.fillRectangle(fillRectangle); graphics.setForegroundColor(this.getBorderColor()); graphics.drawRectangle(new Rectangle(bounds.x,bounds.y,bounds.width-1,bounds.height-1)); graphics.drawRectangle(new Rectangle(fillRectangle.x,fillRectangle.y,fillRectangle.width-1,fillRectangle.height-1)); } /** * Gets the fill Color. * @return Color * The Color for the fill-area */ private Color getFillColor() { List<String> labelList = new LinkedList<String>(); for (int i=0;i<LABELS.length;i++) { if (labelList.isEmpty()) { labelList.add(LABELS[i]); } else { labelList.add(this.getLabelIndex(labelList, LABELS[i]), LABELS[i]); } } String[] tempLabels = labelList.toArray(new String[labelList.size()]); if (_minimum<_maximum) { for (int i=0; i<tempLabels.length;i++) { if (this.getFill()<=getWeight(_levelMap.get(tempLabels[i]))) { return _colorMap.get(tempLabels[i]); } } return this.getDefaultFillColor(); } else { for (int i=tempLabels.length-1; i>=0;i--) { if (this.getFill()<=getWeight(_levelMap.get(tempLabels[i]))) { return _colorMap.get(tempLabels[i]); } } return this.getDefaultFillColor(); } } /** * Gets the index for the label. * @param labelList * The list, where the label should be added * @param label * The label, which should be added * @return int * The index for the label */ private int getLabelIndex(final List<String> labelList, final String label) { for (int j=0;j<labelList.size();j++) { if (_levelMap.get(label)<_levelMap.get(labelList.get(j))) { return j; } } return labelList.size(); } /** * Gets the rectangle for the fill level. * @param area * The rectangle of the bargraph * @return Rectangle * The rectangle for the fill level */ private Rectangle getFillLevelRectangle(final Rectangle area) { if (_orientationHorizontal) { int newW = (int) Math.round(area.width * (this.getFill())); return new Rectangle(area.getLocation(),new Dimension(newW, area.height)); } int newH = (int) Math.round(area.height * (this.getFill())); return new Rectangle(area.x,area.y+area.height-newH,area.width,newH); } /** * Sets the fill grade. * * @param fill * The fill grade. */ public void setFill(final double fill) { _fillGrade = fill; } /** * Gets the fill grade. * * @return double * The fill grade */ public double getFill() { return _fillGrade; } /** * Sets the default fill Color. * @param defaultFillColor * The default fill Color */ public void setDefaultFillColor(final Color defaultFillColor) { _defaultFillColor = defaultFillColor; } /** * Gets the default fill Color. * @return Color * The color default fill Color */ public Color getDefaultFillColor() { return _defaultFillColor; } /** * Sets the color for the border. * @param borderColor * The Color for the border */ public void setBorderColor(final Color borderColor) { _borderColor = borderColor; } /** * Gets the color for the border. * @return Color * The color for the border */ public Color getBorderColor() { return _borderColor; } } /** * This Figure contains the Markers. * * @author Kai Meyer */ private final class MarkerPanel extends Panel { /** * The List of Markers. */ private final List<Marker> _markerList = new LinkedList<Marker>(); /** * The alignment for the Markers. */ private boolean _topLeft; /** * The orientation of theis figure. */ private boolean _isHorizontal; /** * The start position. */ private int _start = 10; /** * The end position. */ private int _end = 100; /** * Constructor. * @param topLeft * true, if the Marker is on top/left of the bargraph, false otherwise * @param isHorizontal * true, if the Marker has a horizontal orientation */ public MarkerPanel(final boolean topLeft, final boolean isHorizontal) { this.setLayoutManager(new XYLayout()); _topLeft = topLeft; _isHorizontal = isHorizontal; Marker marker = null; for (int i=0;i<LABELS.length;i++) { marker = new Marker(LABELS[i], _topLeft, _isHorizontal); marker.setForegroundColor(this.getForegroundColor()); this.add(marker); _markerList.add(marker); } } /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { Rectangle bounds = this.getBounds(); graphics.setBackgroundColor(this.getBackgroundColor()); graphics.setForegroundColor(ColorConstants.black); graphics.fillRectangle(bounds); if (_isHorizontal) { for (int i=0;i<_markerList.size();i++) { double weight = getWeight(_levelMap.get(LABELS[i])); if (weight<0 || weight>1) { this.setConstraint(_markerList.get(i), new Rectangle(0,0,0,0)); } else { int x = _start + (int)((_end-_start)*weight)-1 - TEXTWIDTH/2; this.setConstraint(_markerList.get(i), new Rectangle(x,0,TEXTWIDTH, bounds.height )); } } } else { for (int i=0;i<_markerList.size();i++) { double weight = getWeight(_levelMap.get(LABELS[i])); if (weight<0 || weight>1) { this.setConstraint(_markerList.get(i), new Rectangle(0,0,0,0)); } else { int y = _start + (int) ((_end-_start)*(1-weight)) - TEXTHEIGHT/2; this.setConstraint(_markerList.get(i), new Rectangle(1, y, bounds.width, TEXTHEIGHT)); } } } } /** * Sets the reference values for this figure. * @param start * The start value * @param end * The end value */ public void setReferencePositions(final int start, final int end) { _start = start; _end = end; } /** * Sets the orientation of this figure. * @param isHorizontal * The orientation of this figure (true=horizontal;false=vertical) */ public void setHorizontalOrientation(final boolean isHorizontal) { _isHorizontal = isHorizontal; for (Marker marker : _markerList) { marker.setHorizontalOrientation(isHorizontal); } } /** * Sets the alignment of this figure. * @param topLeft * The alignment of this figure (true=top/left;false=bottom/right) */ public void setTopLeftAlignment(final boolean topLeft) { _topLeft = topLeft; for (Marker marker : _markerList) { marker.setTopLeftAlignment(topLeft); } } } /** * This class represents a Marker. * * @author Kai Meyer * */ private final class Marker extends RectangleFigure { /** * The key of this Marker, which is the drwaed text. */ private String _key; /** * The orientation of this Marker. */ private boolean _isHorizontal; /** * The alignment of this Marker. */ private boolean _topLeft; /** * The Label for the text. */ private Label _textLabel; /** * The Tipmark. */ private TipMark _tipMark; /** * Construktor. * @param key * The text to display * @param topLeft * True, if the marker should be above the y value, false otherwise * @param isHorizontal * True, if the marker should have a horizontal orientation, false otherwise */ public Marker(final String key, final boolean topLeft, final boolean isHorizontal) { BorderLayout borderLayout = new BorderLayout(); this.setLayoutManager(borderLayout); _key = key; _textLabel = new Label(key.toString()); _textLabel.setForegroundColor(this.getForegroundColor()); _tipMark = new TipMark(); _tipMark.setForegroundColor(this.getForegroundColor()); _tipMark.setBackgroundColor(_colorMap.get(_key)); this.add(_tipMark, BorderLayout.CENTER); this.refreshLabel(); } /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { //nothing to do; }; /** * Sets the orientation of this figure. * @param isHorizontal * The orientation of this figure (true=horizontal;false=vertical) */ public void setHorizontalOrientation(final boolean isHorizontal) { _isHorizontal = isHorizontal; _tipMark.setHorizontalOrientation(isHorizontal); this.refreshLabel(); } /** * Sets the alignment of this figure. * @param topLeft * The alignment of this figure (true=top/left;false=bottom/right) */ public void setTopLeftAlignment(final boolean topLeft) { _topLeft = topLeft; _tipMark.setTopLeftAlignment(topLeft); this.refreshLabel(); } /** * Refreshes the Label. */ private void refreshLabel() { if (this.getChildren().contains(_textLabel)) { this.remove(_textLabel); } Integer place; if (_isHorizontal) { if (_topLeft) { place = BorderLayout.TOP; } else { place = BorderLayout.BOTTOM; } } else { if (_topLeft) { place = BorderLayout.LEFT; } else { place = BorderLayout.RIGHT; } } this.add(_textLabel, place); } /** * This class represents a tipmark. * @author Kai Meyer */ private final class TipMark extends RectangleFigure { /** * The width of this marker. */ private int _width; /** * The height of this marker. */ private int _height; /** * The direction of this Marker. */ private int _direction = 1; /** * The orientation of this Marker. */ private boolean _isHorizontal; /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { Rectangle bounds = this.getBounds(); graphics.setForegroundColor(this.getForegroundColor()); graphics.setBackgroundColor(_colorMap.get(_key)); PointList pointList = new PointList(); int x; int y; if (_isHorizontal) { x = bounds.x+bounds.width/2; y = bounds.y; if (_direction<0) { y = y + bounds.height; } pointList.addPoint(x, y); pointList.addPoint(x-_width, y+_height*_direction); pointList.addPoint(x+_width, y+_height*_direction); pointList.addPoint(x, y); } else { x = bounds.x; y = bounds.y+bounds.height/2; if (_direction<0) { x = x + bounds.width-2; } pointList.addPoint(x, y); pointList.addPoint(x+_width*_direction, y-_height); pointList.addPoint(x+_width*_direction, y+_height); pointList.addPoint(x, y); } graphics.fillPolygon(pointList); graphics.drawPolyline(pointList); } /** * Sets the orientation of this figure. * @param isHorizontal * The orientation of this figure (true=horizontal;false=vertical) */ public void setHorizontalOrientation(final boolean isHorizontal) { _isHorizontal = isHorizontal; if (isHorizontal) { _width = 3; _height = 5; } else { _width = 5; _height = 3; } } /** * Sets the alignment of this figure. * @param topLeft * The alignment of this figure (true=top/left;false=bottom/right) */ public void setTopLeftAlignment(final boolean topLeft) { if (topLeft) { _direction = -1; } else { _direction = 1; } } } } /** * This class represents a scale. * * @author Kai Meyer * */ private final class Scale extends RectangleFigure { /** * The length of this Scale. */ private int _length; /** * The count of sections in this Scale. */ private int _sectionCount = -1; /** * The direction of this Scale. */ private boolean _isHorizontal; /** * The start position. */ private int _start = 10; /** * True, if the negativ sections should be draan, false otherwise. */ private boolean _showNegativSections = false; /** * Sets the length of this Scale. * @param length * The lenght of this Scale */ public void setLength(final int length) { _length = length; } /** * Sets the orientation of this Scale. * @param isHorizontal * The orientation of this Scale (true=horizontal;false=vertical) */ public void setHorizontalOrientation(final boolean isHorizontal) { _isHorizontal = isHorizontal; } /** * Sets the count of setcion in this Scale. * @param sectionCount * The count of setcion in this Scale */ public void setSectionCount(final int sectionCount) { _sectionCount = sectionCount; } /** * {@inheritDoc} */ @Override public void paintFigure(final Graphics graphics) { int sectionWidth = 0; int sectionHeight = 0; int height = 0; int width = 0; graphics.setForegroundColor(this.getForegroundColor()); graphics.setBackgroundColor(this.getBackgroundColor()); if (_isHorizontal) { height = _scaleWideness; if (_sectionCount>0) { sectionWidth = _length/_sectionCount; for (int i=0;i<_sectionCount+1;i++) { graphics.drawLine(this.getBounds().x+_start+i*sectionWidth, this.getBounds().y, this.getBounds().x+_start+i*sectionWidth+width , this.getBounds().y+height); } } else { int pos = _start; while (pos<this.getBounds().width) { graphics.drawLine(this.getBounds().x+pos, this.getBounds().y, this.getBounds().x+pos , this.getBounds().y+height); pos = pos +_length; } if (_showNegativSections) { pos = _start; while (pos>0) { graphics.drawLine(this.getBounds().x, this.getBounds().y+pos, this.getBounds().x+width , this.getBounds().y+pos); pos = pos - _length; } } } } else { width = _scaleWideness; if (_sectionCount>0) { sectionHeight = _length/_sectionCount; for (int i=0;i<_sectionCount+1;i++) { graphics.drawLine(this.getBounds().x, this.getBounds().y+_start+i*sectionHeight, this.getBounds().x+width , this.getBounds().y+_start+i*sectionHeight); } } else { int pos = _start; while (pos<this.getBounds().height) { graphics.drawLine(this.getBounds().x, this.getBounds().y+pos, this.getBounds().x+width , this.getBounds().y+pos); pos = pos +_length; } if (_showNegativSections) { pos = _start; while (pos>0) { graphics.drawLine(this.getBounds().x, this.getBounds().y+pos, this.getBounds().x+width , this.getBounds().y+pos); pos = pos - _length; } } } } } /** * Sets the reference values for this figure. * @param start * The start value */ public void setReferencePositions(final int start) { _start = start; } /** * Sets if the negative sections should be drawn. * @param showNegativ * True, if the negativ sections should be drawn, false otherwise. */ public void setShowNegativeSections(final boolean showNegativ) { _showNegativSections = showNegativ; } } // /** // * This class represents a scale. // * // * @author Kai Meyer // * // */ // private final class Scale extends RectangleFigure { // /** // * The length of this Scale. // */ // private int _length; // /** // * The count of sections in this Scale. // */ // private int _sectionCount; // /** // * The direction of this Scale. // */ // private boolean _isHorizontal; // /** // * The start position. // */ // private int _start = 10; // // /** // * Sets the length of this Scale. // * @param length // * The lenght of this Scale // */ // public void setLength(final int length) { // _length = length; // } // // /** // * Sets the orientation of this Scale. // * @param isHorizontal // * The orientation of this Scale (true=horizontal;false=vertical) // */ // public void setHorizontalOrientation(final boolean isHorizontal) { // _isHorizontal = isHorizontal; // } // // /** // * Sets the count of setcion in this Scale. // * @param sectionCount // * The count of setcion in this Scale // */ // public void setSectionCount(final int sectionCount) { // _sectionCount = sectionCount; // } // // /** // * {@inheritDoc} // */ // @Override // public void paintFigure(final Graphics graphics) { // int sectionWidth = 0; // int sectionHeight = 0; // int height = 0; // int width = 0; // graphics.setForegroundColor(this.getForegroundColor()); // graphics.setBackgroundColor(this.getBackgroundColor()); // if (_isHorizontal) { // height = _scaleWideness; // sectionWidth = _length/_sectionCount; // for (int i=0;i<_sectionCount+1;i++) { // graphics.drawLine(this.getBounds().x+_start+i*sectionWidth, this.getBounds().y, this.getBounds().x+_start+i*sectionWidth+width , this.getBounds().y+height); // } // } else { // width = _scaleWideness; // sectionHeight = _length/_sectionCount; // for (int i=0;i<_sectionCount+1;i++) { // graphics.drawLine(this.getBounds().x, this.getBounds().y+_start+i*sectionHeight, this.getBounds().x+width , this.getBounds().y+_start+i*sectionHeight); // } // } // } // // /** // * Sets the reference values for this figure. // * @param start // * The start value // */ // public void setReferencePositions(final int start) { // _start = start; // } // } }
Bugfixing und Performance-Steigerung
applications/plugins/org.csstudio.sds.components.ui/src/org/csstudio/sds/components/ui/internal/figures/RefreshableBargraphFigure.java
Bugfixing und Performance-Steigerung
<ide><path>pplications/plugins/org.csstudio.sds.components.ui/src/org/csstudio/sds/components/ui/internal/figures/RefreshableBargraphFigure.java <ide> public synchronized void paintFigure(final Graphics graphics) { <ide> graphics.setBackgroundColor(this.getBackgroundColor()); <ide> graphics.fillRectangle(this.getBounds()); <del> this.refreshConstraints(); <add> //this.refreshConstraints(); <ide> graphics.setBackgroundColor(this.getBackgroundColor()); <ide> graphics.setForegroundColor(this.getBorderColor()); <ide> this.setToolTip(this.getToolTipFigure()); <ide> return new Rectangle(0,_barRectangle.y,bounds.width,_scaleWideness); <ide> } <ide> } else { <del> _scale.setLength(_fillRectangleFigure.getBounds().height); <add> _scale.setLength(_barRectangle.height); <ide> _scale.setReferencePositions(_barRectangle.y); <ide> if (_showScale==BOTTOM_RIGHT) { <ide> return new Rectangle(_barRectangle.x+_barRectangle.width-_scaleWideness,0,_scaleWideness,bounds.height); <ide> this.add(marker); <ide> _markerList.add(marker); <ide> } <del> } <del> <del> /** <del> * {@inheritDoc} <del> */ <del> @Override <del> public void paintFigure(final Graphics graphics) { <del> Rectangle bounds = this.getBounds(); <del> graphics.setBackgroundColor(this.getBackgroundColor()); <del> graphics.setForegroundColor(ColorConstants.black); <del> graphics.fillRectangle(bounds); <add>// listen to figure movement events <add> addFigureListener(new FigureListener() { <add> public void figureMoved(final IFigure source) { <add> refreshConstraints(); <add> } <add> }); <add> <add> this.refreshConstraints(); <add> } <add> <add> /** <add> * Refreshes the constraints. <add> */ <add> private void refreshConstraints() { <ide> if (_isHorizontal) { <ide> for (int i=0;i<_markerList.size();i++) { <ide> double weight = getWeight(_levelMap.get(LABELS[i])); <ide> } <ide> <ide> /** <add> * {@inheritDoc} <add> */ <add> @Override <add> public void paintFigure(final Graphics graphics) { <add> Rectangle bounds = this.getBounds(); <add> graphics.setBackgroundColor(this.getBackgroundColor()); <add> graphics.setForegroundColor(ColorConstants.black); <add> graphics.fillRectangle(bounds); <add> } <add> <add> /** <ide> * Sets the reference values for this figure. <ide> * @param start <ide> * The start value <ide> public void setReferencePositions(final int start, final int end) { <ide> _start = start; <ide> _end = end; <add> this.refreshConstraints(); <ide> } <ide> <ide> /** <ide> for (Marker marker : _markerList) { <ide> marker.setHorizontalOrientation(isHorizontal); <ide> } <add> this.refreshConstraints(); <ide> } <ide> <ide> /** <ide> for (Marker marker : _markerList) { <ide> marker.setTopLeftAlignment(topLeft); <ide> } <add> this.refreshConstraints(); <ide> } <ide> } <ide> <ide> */ <ide> @Override <ide> public void paintFigure(final Graphics graphics) { <add> //System.out.println("TipMark.paintFigure()"); <ide> Rectangle bounds = this.getBounds(); <ide> graphics.setForegroundColor(this.getForegroundColor()); <ide> graphics.setBackgroundColor(_colorMap.get(_key));
Java
apache-2.0
8a18cf5b8faac26559f0798e597fa2764ad2b533
0
pushtechnology/diffusion-transform
/******************************************************************************* * Copyright (C) 2016 Push Technology Ltd. * * 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.pushtechnology.diffusion.transform.transformer; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.pushtechnology.diffusion.client.Diffusion; import com.pushtechnology.diffusion.datatype.Bytes; import com.pushtechnology.diffusion.datatype.InvalidDataException; import com.pushtechnology.diffusion.datatype.binary.Binary; import com.pushtechnology.diffusion.datatype.binary.BinaryDataType; import com.pushtechnology.diffusion.datatype.json.JSON; import com.pushtechnology.diffusion.datatype.json.JSONDataType; /** * Common {@link Transformer}s. * * @author Push Technology Limited */ public final class Transformers { private static final BinaryDataType BINARY_DATA_TYPE = Diffusion.dataTypes().binary(); private static final JSONDataType JSON_DATA_TYPE = Diffusion.dataTypes().json(); private static final SafeTransformer IDENTITY = new SafeTransformer() { @Override public Object transform(Object value) { return value; } }; private static final SafeTransformer<byte[], Binary> BYTE_ARRAY_TO_BINARY = new SafeTransformer<byte[], Binary>() { @Override public Binary transform(byte[] value) { if (value == null) { return null; } return BINARY_DATA_TYPE.readValue(value); } }; private static final Transformer FROM_POJO = new Transformer() { @Override public Object transform(Object value) throws TransformationException { if (value == null) { return null; } return JacksonContext.fromPojo(value); } }; @SuppressWarnings("unchecked") private static final Transformer FROM_MAP = new Transformer() { @Override public Object transform(Object value) throws TransformationException { if (value == null) { return null; } return JacksonContext.fromMap((Map<String, ?>) value); } }; private static final Transformer<String, JSON> PARSE_JSON = toTransformer( new UnsafeTransformer<String, JSON>() { @Override public JSON transform(String value) throws InvalidDataException { return JSON_DATA_TYPE.fromJsonString(value); } }); private static final Transformer<JSON, String> STRINGIFY_JSON = toTransformer( new UnsafeTransformer<JSON, String>() { @Override public String transform(JSON value) throws InvalidDataException { return value.toJsonString(); } }); private static final SafeTransformer<Bytes, byte[]> TO_BYTE_ARRAY = new SafeTransformer<Bytes, byte[]>() { @Override public byte[] transform(Bytes value) { return value.toByteArray(); } }; private Transformers() { } /** * Identity transformer. * * @param <T> the type of value * @return a transformer that transforms values to themselves. */ @SuppressWarnings("unchecked") public static <T> SafeTransformer<T, T> identity() { return (SafeTransformer<T, T>) IDENTITY; } /** * Identity transformer. * * @param type the type of value * @param <T> the type of value * @return a transformer that transforms values to themselves. */ @SuppressWarnings("unchecked") public static <T> SafeTransformer<T, T> identity(Class<T> type) { return IDENTITY; } /** * To super class transformer. * * @param <S> the type of value * @param <T> the super type of value * @return a transformer that transforms values to a super class. */ @SuppressWarnings("unchecked") public static <S, T extends S> SafeTransformer<T, S> toSuperClass() { return IDENTITY; } /** * @return transformer from byte[] to {@link Binary}. */ public static SafeTransformer<byte[], Binary> byteArrayToBinary() { return BYTE_ARRAY_TO_BINARY; } /** * Chain two transformers together. * * @param transformer0 the first transformer * @param transformer1 the second transformer * @param <S> the source value type * @param <M> the intermediate value type * @param <T> the target value type * @return the composed transformer */ public static <S, M, T> Transformer<S, T> chain( final Transformer<S, M> transformer0, final Transformer<M, T> transformer1) { return new Transformer<S, T>() { @Override public T transform(S value) throws TransformationException { if (value == null) { return null; } final M transientValue = transformer0.transform(value); return transformer1.transform(transientValue); } }; } /** * Chain two safe transformers together. * * @param transformer0 the first transformer * @param transformer1 the second transformer * @param <S> the source value type * @param <M> the intermediate value type * @param <T> the target value type * @return the composed transformer */ public static <S, M, T> SafeTransformer<S, T> chain( final SafeTransformer<S, M> transformer0, final SafeTransformer<M, T> transformer1) { return new SafeTransformer<S, T>() { @Override public T transform(S value) { if (value == null) { return null; } final M transientValue = transformer0.transform(value); return transformer1.transform(transientValue); } }; } /** * A transformer that projects map values. * * @param key the key to project * @param <K> the key type * @param <V> the value type * @return a transformer that creates a projection of a map */ public static <K, V> SafeTransformer<Map<K, V>, V> project(final K key) { return new SafeTransformer<Map<K, V>, V>() { @Override public V transform(Map<K, V> value) { if (value == null) { return null; } return value.get(key); } }; } /** * A transformer that casts to the target type. * * @param type the type value describing the type to cast to * @param <S> the type to cast from * @param <T> the type to cast to * @return a transformer that casts the object */ public static <S, T> Transformer<S, T> cast(Class<T> type) { return new Transformer<S, T>() { // Cast exceptions are caught so they can be propagated as transformation exceptions @SuppressWarnings("unchecked") @Override public T transform(S value) throws TransformationException { try { return (T) value; } catch (ClassCastException e) { throw new TransformationException(e); } } }; } /** * A transformer that casts to the target type. * * @param type the type reference describing the type to cast to * @param <S> the type to cast from * @param <T> the type to cast to * @return a transformer that casts the object */ public static <S, T> Transformer<S, T> cast(TypeReference<T> type) { return new Transformer<S, T>() { // Cast exceptions are caught so they can be propagated as transformation exceptions @SuppressWarnings("unchecked") @Override public T transform(S value) throws TransformationException { try { return (T) value; } catch (ClassCastException e) { throw new TransformationException(e); } } }; } /** * Transformer to convert JSON to a type with Jackson. * * @param type the class to convert to * @param <T> the target type * @return a transformer that converts JSON to the provided type */ public static <T> Transformer<JSON, T> toObject(final Class<T> type) { return new Transformer<JSON, T>() { @Override public T transform(JSON value) throws TransformationException { if (value == null) { return null; } return JacksonContext.toObject(value, type); } }; } /** * Transformer to convert JSON to a type with Jackson. * * @param typeReference the type reference to convert to * @param <T> the target type * @return a transformer that converts JSON to the provided type */ public static <T> Transformer<JSON, T> toType(final TypeReference<T> typeReference) { return new Transformer<JSON, T>() { @Override public T transform(JSON value) throws TransformationException { if (value == null) { return null; } return JacksonContext.toType(value, typeReference); } }; } /** * Transformer to convert JSON to a map of a specific type of value. * * @param type the type of value contained by the map * @param <T> the type of value contained by the map * @return a transformer that converts JSON to a map */ public static <T> Transformer<JSON, Map<String, T>> toMapOf(final Class<T> type) { return new Transformer<JSON, Map<String, T>>() { @Override public Map<String, T> transform(JSON value) throws TransformationException { if (value == null) { return null; } return JacksonContext.toMapOf(value, type); } }; } /** * Transformer from pojo to JSON. * * @param <T> the type of pojo * @return the transformer to JSON */ @SuppressWarnings("unchecked") public static <T> Transformer<T, JSON> fromPojo() { return FROM_POJO; } /** * Transformer from map to JSON. * * @param <T> the value type of map * @return the transformer to JSON */ @SuppressWarnings("unchecked") public static <T> Transformer<Map<String, T>, JSON> fromMap() { return FROM_MAP; } /** * Transformer from integer to Binary. * * @return the transformer to Binary */ public static Transformer<Integer, Binary> integerToBinary() { return IntegerToBinaryTransformer.INSTANCE; } /** * Transformer from Binary to integer. * * @return the transformer to integer */ public static Transformer<Binary, Integer> binaryToInteger() { return BinaryToIntegerTransformer.INSTANCE; } /** * Transformer from double to Binary. * * @return the transformer to Binary */ public static Transformer<Double, Binary> doubleToBinary() { return DoubleToBinaryTransformer.INSTANCE; } /** * Transformer from Binary to double. * * @return the transformer to double */ public static Transformer<Binary, Double> binaryToDouble() { return BinaryToDoubleTransformer.INSTANCE; } /** * Transformer from big integer to Binary. * * @return the transformer to Binary */ public static Transformer<BigInteger, Binary> bigIntegerToBinary() { return BigIntegerToBinaryTransformer.INSTANCE; } /** * Transformer from Binary to big integer. * * @return the transformer to integer */ public static Transformer<Binary, BigInteger> binaryToBigInteger() { return BinaryToBigIntegerTransformer.INSTANCE; } /** * Transformer from String to Binary. * * @param charset the character set to encode the string with * @return the transformer to Binary */ public static SafeTransformer<String, Binary> stringToBinary(Charset charset) { return new StringToBinaryTransformer(charset); } /** * Transformer from Binary to String. * * @param charset the character set to decode the string with * @return the transformer to String */ public static SafeTransformer<Binary, String> binaryToString(Charset charset) { return new BinaryToStringTransformer(charset); } /** * Transformer from String to JSON. * @return the transformer to JSON */ public static Transformer<String, JSON> parseJSON() { return PARSE_JSON; } /** * Transformer from JSON to String. * @return the transformer to String */ public static Transformer<JSON, String> stringify() { return STRINGIFY_JSON; } /** * Transformer from any implementation of Bytes to a byte array. * @param <T> the implementation of bytes * @return the transformer to byte array */ @SuppressWarnings("unchecked") public static <T extends Bytes> SafeTransformer<T, byte[]> toByteArray() { return (SafeTransformer<T, byte[]>) TO_BYTE_ARRAY; } /** * Create a {@link Transformer} from a {@link UnsafeTransformer}. * @param transformer the uncaught transformer * @param <S> the source value type * @param <T> the target value type * @return the transformer */ public static <S, T> Transformer<S, T> toTransformer(final UnsafeTransformer<S, T> transformer) { return new Transformer<S, T>() { @Override public T transform(S value) throws TransformationException { if (value == null) { return null; } try { return transformer.transform(value); } catch (TransformationException e) { throw e; } // CHECKSTYLE.OFF: IllegalCatch // Bulkhead catch (Exception e) { throw new TransformationException(e); } // CHECKSTYLE.ON: IllegalCatch // Bulkhead } }; } }
transformers/src/main/java/com/pushtechnology/diffusion/transform/transformer/Transformers.java
/******************************************************************************* * Copyright (C) 2016 Push Technology Ltd. * * 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.pushtechnology.diffusion.transform.transformer; import java.math.BigInteger; import java.nio.charset.Charset; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.pushtechnology.diffusion.client.Diffusion; import com.pushtechnology.diffusion.datatype.Bytes; import com.pushtechnology.diffusion.datatype.InvalidDataException; import com.pushtechnology.diffusion.datatype.binary.Binary; import com.pushtechnology.diffusion.datatype.binary.BinaryDataType; import com.pushtechnology.diffusion.datatype.json.JSON; import com.pushtechnology.diffusion.datatype.json.JSONDataType; /** * Common {@link Transformer}s. * * @author Push Technology Limited */ public final class Transformers { private static final BinaryDataType BINARY_DATA_TYPE = Diffusion.dataTypes().binary(); private static final JSONDataType JSON_DATA_TYPE = Diffusion.dataTypes().json(); private static final SafeTransformer IDENTITY = new SafeTransformer() { @Override public Object transform(Object value) { return value; } }; private static final SafeTransformer<byte[], Binary> BYTE_ARRAY_TO_BINARY = new SafeTransformer<byte[], Binary>() { @Override public Binary transform(byte[] value) { if (value == null) { return null; } return BINARY_DATA_TYPE.readValue(value); } }; private static final Transformer FROM_POJO_TRANSFORMER = new Transformer() { @Override public Object transform(Object value) throws TransformationException { if (value == null) { return null; } return JacksonContext.fromPojo(value); } }; @SuppressWarnings("unchecked") private static final Transformer FROM_MAP_TRANSFORMER = new Transformer() { @Override public Object transform(Object value) throws TransformationException { if (value == null) { return null; } return JacksonContext.fromMap((Map<String, ?>) value); } }; private static final Transformer<String, JSON> PARSE_JSON_TRANSFORMER = toTransformer( new UnsafeTransformer<String, JSON>() { @Override public JSON transform(String value) throws InvalidDataException { return JSON_DATA_TYPE.fromJsonString(value); } }); private static final Transformer<JSON, String> STRINGIFY_TRANSFORMER = toTransformer( new UnsafeTransformer<JSON, String>() { @Override public String transform(JSON value) throws InvalidDataException { return value.toJsonString(); } }); private static final SafeTransformer<Bytes, byte[]> TO_BYTE_ARRAY = new SafeTransformer<Bytes, byte[]>() { @Override public byte[] transform(Bytes value) { return value.toByteArray(); } }; private Transformers() { } /** * Identity transformer. * * @param <T> the type of value * @return a transformer that transforms values to themselves. */ @SuppressWarnings("unchecked") public static <T> SafeTransformer<T, T> identity() { return (SafeTransformer<T, T>) IDENTITY; } /** * Identity transformer. * * @param type the type of value * @param <T> the type of value * @return a transformer that transforms values to themselves. */ @SuppressWarnings("unchecked") public static <T> SafeTransformer<T, T> identity(Class<T> type) { return IDENTITY; } /** * To super class transformer. * * @param <S> the type of value * @param <T> the super type of value * @return a transformer that transforms values to a super class. */ @SuppressWarnings("unchecked") public static <S, T extends S> SafeTransformer<T, S> toSuperClass() { return IDENTITY; } /** * @return transformer from byte[] to {@link Binary}. */ public static SafeTransformer<byte[], Binary> byteArrayToBinary() { return BYTE_ARRAY_TO_BINARY; } /** * Chain two transformers together. * * @param transformer0 the first transformer * @param transformer1 the second transformer * @param <S> the source value type * @param <M> the intermediate value type * @param <T> the target value type * @return the composed transformer */ public static <S, M, T> Transformer<S, T> chain( final Transformer<S, M> transformer0, final Transformer<M, T> transformer1) { return new Transformer<S, T>() { @Override public T transform(S value) throws TransformationException { if (value == null) { return null; } final M transientValue = transformer0.transform(value); return transformer1.transform(transientValue); } }; } /** * Chain two safe transformers together. * * @param transformer0 the first transformer * @param transformer1 the second transformer * @param <S> the source value type * @param <M> the intermediate value type * @param <T> the target value type * @return the composed transformer */ public static <S, M, T> SafeTransformer<S, T> chain( final SafeTransformer<S, M> transformer0, final SafeTransformer<M, T> transformer1) { return new SafeTransformer<S, T>() { @Override public T transform(S value) { if (value == null) { return null; } final M transientValue = transformer0.transform(value); return transformer1.transform(transientValue); } }; } /** * A transformer that projects map values. * * @param key the key to project * @param <K> the key type * @param <V> the value type * @return a transformer that creates a projection of a map */ public static <K, V> SafeTransformer<Map<K, V>, V> project(final K key) { return new SafeTransformer<Map<K, V>, V>() { @Override public V transform(Map<K, V> value) { if (value == null) { return null; } return value.get(key); } }; } /** * A transformer that casts to the target type. * * @param type the type value describing the type to cast to * @param <S> the type to cast from * @param <T> the type to cast to * @return a transformer that casts the object */ public static <S, T> Transformer<S, T> cast(Class<T> type) { return new Transformer<S, T>() { // Cast exceptions are caught so they can be propagated as transformation exceptions @SuppressWarnings("unchecked") @Override public T transform(S value) throws TransformationException { try { return (T) value; } catch (ClassCastException e) { throw new TransformationException(e); } } }; } /** * A transformer that casts to the target type. * * @param type the type reference describing the type to cast to * @param <S> the type to cast from * @param <T> the type to cast to * @return a transformer that casts the object */ public static <S, T> Transformer<S, T> cast(TypeReference<T> type) { return new Transformer<S, T>() { // Cast exceptions are caught so they can be propagated as transformation exceptions @SuppressWarnings("unchecked") @Override public T transform(S value) throws TransformationException { try { return (T) value; } catch (ClassCastException e) { throw new TransformationException(e); } } }; } /** * Transformer to convert JSON to a type with Jackson. * * @param type the class to convert to * @param <T> the target type * @return a transformer that converts JSON to the provided type */ public static <T> Transformer<JSON, T> toObject(final Class<T> type) { return new Transformer<JSON, T>() { @Override public T transform(JSON value) throws TransformationException { if (value == null) { return null; } return JacksonContext.toObject(value, type); } }; } /** * Transformer to convert JSON to a type with Jackson. * * @param typeReference the type reference to convert to * @param <T> the target type * @return a transformer that converts JSON to the provided type */ public static <T> Transformer<JSON, T> toType(final TypeReference<T> typeReference) { return new Transformer<JSON, T>() { @Override public T transform(JSON value) throws TransformationException { if (value == null) { return null; } return JacksonContext.toType(value, typeReference); } }; } /** * Transformer to convert JSON to a map of a specific type of value. * * @param type the type of value contained by the map * @param <T> the type of value contained by the map * @return a transformer that converts JSON to a map */ public static <T> Transformer<JSON, Map<String, T>> toMapOf(final Class<T> type) { return new Transformer<JSON, Map<String, T>>() { @Override public Map<String, T> transform(JSON value) throws TransformationException { if (value == null) { return null; } return JacksonContext.toMapOf(value, type); } }; } /** * Transformer from pojo to JSON. * * @param <T> the type of pojo * @return the transformer to JSON */ @SuppressWarnings("unchecked") public static <T> Transformer<T, JSON> fromPojo() { return FROM_POJO_TRANSFORMER; } /** * Transformer from map to JSON. * * @param <T> the value type of map * @return the transformer to JSON */ @SuppressWarnings("unchecked") public static <T> Transformer<Map<String, T>, JSON> fromMap() { return FROM_MAP_TRANSFORMER; } /** * Transformer from integer to Binary. * * @return the transformer to Binary */ public static Transformer<Integer, Binary> integerToBinary() { return IntegerToBinaryTransformer.INSTANCE; } /** * Transformer from Binary to integer. * * @return the transformer to integer */ public static Transformer<Binary, Integer> binaryToInteger() { return BinaryToIntegerTransformer.INSTANCE; } /** * Transformer from double to Binary. * * @return the transformer to Binary */ public static Transformer<Double, Binary> doubleToBinary() { return DoubleToBinaryTransformer.INSTANCE; } /** * Transformer from Binary to double. * * @return the transformer to double */ public static Transformer<Binary, Double> binaryToDouble() { return BinaryToDoubleTransformer.INSTANCE; } /** * Transformer from big integer to Binary. * * @return the transformer to Binary */ public static Transformer<BigInteger, Binary> bigIntegerToBinary() { return BigIntegerToBinaryTransformer.INSTANCE; } /** * Transformer from Binary to big integer. * * @return the transformer to integer */ public static Transformer<Binary, BigInteger> binaryToBigInteger() { return BinaryToBigIntegerTransformer.INSTANCE; } /** * Transformer from String to Binary. * * @param charset the character set to encode the string with * @return the transformer to Binary */ public static SafeTransformer<String, Binary> stringToBinary(Charset charset) { return new StringToBinaryTransformer(charset); } /** * Transformer from Binary to String. * * @param charset the character set to decode the string with * @return the transformer to String */ public static SafeTransformer<Binary, String> binaryToString(Charset charset) { return new BinaryToStringTransformer(charset); } /** * Transformer from String to JSON. * @return the transformer to JSON */ public static Transformer<String, JSON> parseJSON() { return PARSE_JSON_TRANSFORMER; } /** * Transformer from JSON to String. * @return the transformer to String */ public static Transformer<JSON, String> stringify() { return STRINGIFY_TRANSFORMER; } /** * Transformer from any implementation of Bytes to a byte array. * @param <T> the implementation of bytes * @return the transformer to byte array */ @SuppressWarnings("unchecked") public static <T extends Bytes> SafeTransformer<T, byte[]> toByteArray() { return (SafeTransformer<T, byte[]>) TO_BYTE_ARRAY; } /** * Create a {@link Transformer} from a {@link UnsafeTransformer}. * @param transformer the uncaught transformer * @param <S> the source value type * @param <T> the target value type * @return the transformer */ public static <S, T> Transformer<S, T> toTransformer(final UnsafeTransformer<S, T> transformer) { return new Transformer<S, T>() { @Override public T transform(S value) throws TransformationException { if (value == null) { return null; } try { return transformer.transform(value); } catch (TransformationException e) { throw e; } // CHECKSTYLE.OFF: IllegalCatch // Bulkhead catch (Exception e) { throw new TransformationException(e); } // CHECKSTYLE.ON: IllegalCatch // Bulkhead } }; } }
Remove redundant information from internal constant names.
transformers/src/main/java/com/pushtechnology/diffusion/transform/transformer/Transformers.java
Remove redundant information from internal constant names.
<ide><path>ransformers/src/main/java/com/pushtechnology/diffusion/transform/transformer/Transformers.java <ide> return BINARY_DATA_TYPE.readValue(value); <ide> } <ide> }; <del> private static final Transformer FROM_POJO_TRANSFORMER = new Transformer() { <add> private static final Transformer FROM_POJO = new Transformer() { <ide> @Override <ide> public Object transform(Object value) throws TransformationException { <ide> if (value == null) { <ide> } <ide> }; <ide> @SuppressWarnings("unchecked") <del> private static final Transformer FROM_MAP_TRANSFORMER = new Transformer() { <add> private static final Transformer FROM_MAP = new Transformer() { <ide> @Override <ide> public Object transform(Object value) throws TransformationException { <ide> if (value == null) { <ide> return JacksonContext.fromMap((Map<String, ?>) value); <ide> } <ide> }; <del> private static final Transformer<String, JSON> PARSE_JSON_TRANSFORMER = toTransformer( <add> private static final Transformer<String, JSON> PARSE_JSON = toTransformer( <ide> new UnsafeTransformer<String, JSON>() { <ide> @Override <ide> public JSON transform(String value) throws InvalidDataException { <ide> return JSON_DATA_TYPE.fromJsonString(value); <ide> } <ide> }); <del> private static final Transformer<JSON, String> STRINGIFY_TRANSFORMER = toTransformer( <add> private static final Transformer<JSON, String> STRINGIFY_JSON = toTransformer( <ide> new UnsafeTransformer<JSON, String>() { <ide> @Override <ide> public String transform(JSON value) throws InvalidDataException { <ide> */ <ide> @SuppressWarnings("unchecked") <ide> public static <T> Transformer<T, JSON> fromPojo() { <del> return FROM_POJO_TRANSFORMER; <add> return FROM_POJO; <ide> } <ide> <ide> /** <ide> */ <ide> @SuppressWarnings("unchecked") <ide> public static <T> Transformer<Map<String, T>, JSON> fromMap() { <del> return FROM_MAP_TRANSFORMER; <add> return FROM_MAP; <ide> } <ide> <ide> /** <ide> * @return the transformer to JSON <ide> */ <ide> public static Transformer<String, JSON> parseJSON() { <del> return PARSE_JSON_TRANSFORMER; <add> return PARSE_JSON; <ide> } <ide> <ide> /** <ide> * @return the transformer to String <ide> */ <ide> public static Transformer<JSON, String> stringify() { <del> return STRINGIFY_TRANSFORMER; <add> return STRINGIFY_JSON; <ide> } <ide> <ide> /**
JavaScript
mit
6b1233824d30896371e96766dfa38449657c9eaf
0
ngageoint/geopackage-js,ngageoint/geopackage-js,ngageoint/geopackage-node,ngageoint/geopackage-js
var java = require('java') , mvn = require('node-java-maven') , proj4 = require('proj4') , async = require('async') , toArray = require('stream-to-array') , BufferStream = require('simple-bufferstream') , q = require('q'); // this is necessary for the ImageIO calls within the GeoPackage library java.options.push("-Djava.awt.headless=true"); Math.radians = function(degrees) { return degrees * Math.PI / 180; }; Math.degrees = function(radians) { return radians * 180 / Math.PI; }; function tile2lon(x,z) { return (x/Math.pow(2,z)*360-180); } function tile2lat(y,z) { var n=Math.PI-2*Math.PI*y/Math.pow(2,z); return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n)))); } var getX = function(lon, zoom) { if (zoom == 0) return 0; var xtile = Math.floor((lon + 180) / 360 * (1 << zoom)); return xtile; } var getY = function(lat, zoom) { if (zoom == 0) return 0; var ytile = Math.floor((1 - Math.log(Math.tan(Math.radians(parseFloat(lat))) + 1 / Math.cos(Math.radians(parseFloat(lat)))) / Math.PI) /2 * (1 << zoom)); return ytile; } var xCalculator = function(bbox,z) { var x = []; var x1 = getX(Number(bbox[0]), z); var x2 = getX(Number(bbox[2]), z); x.max = Math.max(x1, x2); x.min = Math.max(0,Math.min(x1, x2)); if (z == 0){ x.current = Math.min(x1, x2); } return x; } var yCalculator = function(bbox,z) { var y = []; var y1 = getY(Number(bbox[1]), z); var y2 = getY(Number(bbox[3]), z); y.max = Math.max(y1, y2); y.min = Math.max(0,Math.min(y1, y2)); y.current = Math.min(y1, y2); return y; } var tileBboxCalculator = function(x, y, z) { x = Number(x); y = Number(y); var tileBounds = { north: tile2lat(y, z), east: tile2lon(x+1, z), south: tile2lat(y+1, z), west: tile2lon(x, z) }; return tileBounds; } /** * Constructor for the GeoPackage API object that can be used to operate on the GeoPackage. * @constructor * @param {Object} configuration object * @returns {Object} GeoPackage API object. */ var GeoPackage = function(config) { config = config || {}; this.featureDaos = {}; this.tileDaos = {}; this.tableProperties = {}; this.initDefer = q.defer(); this.initPromise = this.initDefer.promise; this._initialize(); this.initPromise.then(function(self){ // set up the log4j library to log to the console. var ConsoleAppender = java.import('org.apache.log4j.ConsoleAppender'); var PatternLayout = java.import('org.apache.log4j.PatternLayout'); var consoleAppender = new ConsoleAppender(); //create appender var PATTERN = "%d [%p|%c|%C{1}] %m%n"; consoleAppender.setLayoutSync(new PatternLayout(PATTERN)); consoleAppender.setThresholdSync(java.callStaticMethodSync('org.apache.log4j.Level', 'toLevel', config.log4jLevel || 'INFO')); consoleAppender.activateOptionsSync(); java.callStaticMethodSync('org.apache.log4j.Logger', 'getRootLogger').addAppenderSync(consoleAppender); }); } /** * Initialize the GeoPackage API. Pulls down and adds maven artifacts to the java classpath * @private */ GeoPackage.prototype._initialize = function() { console.log('Initializing the GeoPackage with the package json', __dirname+'/package.json'); var self = this; try { mvn({ packageJsonPath: __dirname+'/package.json' }, function(err, mvnResults) { console.log('retrieved the maven atrifacts'); if (err) { return console.error('could not resolve maven dependencies', err); } mvnResults.classpath.forEach(function(c) { console.log('adding ' + c + ' to classpath'); java.classpath.push(c); }); console.log('resolving promise'); self.initDefer.resolve(self); }); } catch (e) { console.error('e', e); } } /** * Callback for general GeoPackage operations. * * @callback geoPackageCallback * @param {Object} err - Any error that occurred. * @param {Object} geoPackageAPI - this GeoPackageAPI object */ /** * Progress callback for GeoPackage operations. This function must call the callback passed to it * to continue processing. * * @callback progressCallback * @param {Object} progress - the current progress. * @param {Function} callback - callback to be called to continue processing */ /** * Creates a new GeoPackage at the path specified and opens that GeoPackage for editing * @param {string} filePath Absolute path to the GeoPackage to create * @param {geoPackageCallback} callback function to callback when created * @return {undefined} calls callback */ GeoPackage.prototype.createAndOpenGeoPackageFile = function(filePath, callback) { console.log('opening geopackage ' + filePath); this.initPromise.then(function(self) { var File = java.import('java.io.File'); var gpkgFile = new File(filePath); java.callStaticMethodSync('mil.nga.geopackage.manager.GeoPackageManager', 'create', gpkgFile); self.geoPackage = java.callStaticMethodSync('mil.nga.geopackage.manager.GeoPackageManager', 'open', gpkgFile); self.geoPackage.createTileMatrixSetTableSync(); self.geoPackage.createTileMatrixTableSync(); var srsDao = self.geoPackage.getSpatialReferenceSystemDaoSync(); var srsWgs84 = srsDao.getOrCreateSync(4326); var srsEpsg3857 = srsDao.getOrCreateSync(3857); callback(null, self); }).done(); } /** * Opens an existing GeoPackage at the path specified for reading and writing * @param {string} filePath Absolute path to the GeoPackage to create * @param {geoPackageCallback} callback function to callback when created * @return {undefined} calls callback */ GeoPackage.prototype.openGeoPackageFile = function(filePath, callback) { console.log('opening geopackage ' + filePath); this.initPromise.then(function(self) { console.log('promise inited'); var File = java.import('java.io.File'); var gpkgFile = new File(filePath); var canRead = gpkgFile.canReadSync(); console.log('can read the geopackage file? ', canRead); self.geoPackage = java.callStaticMethodSync('mil.nga.geopackage.manager.GeoPackageManager', 'open', gpkgFile); callback(null, self); }).done(); } /** * Adds a tile to the GeoPackage * @param {Object} tileStream Stream to the tile file * @param {string} tableName Name of the table to add the tile to * @param {Number} zoom Zoom level of the tile * @param {Number} tileRow Tile row * @param {Number} tileColumn Tile columns * @param {geoPackageCallback} callback function to call when complete * @return {undefined} calls callback */ GeoPackage.prototype.addTileToGeoPackage = function(tileStream, tableName, zoom, tileRow, tileColumn, callback) { this.initPromise.then(function(self) { var tileDao = self.tileDaos[tableName]; var newRow = tileDao.newRowSync(); newRow.setZoomLevelSync(java.newLong(zoom)); newRow.setTileColumnSync(java.newLong(tileColumn)); newRow.setTileRowSync(java.newLong(tileRow)); toArray(tileStream, function (err, parts) { var byteArray = []; for (var k = 0; k < parts.length; k++) { var part = parts[k]; for (var i = 0; i < part.length; i++) { var bufferPiece = part[i]; var byte = java.newByte(bufferPiece); byteArray.push(byte); } } var bytes = java.newArray('byte', byteArray); newRow.setTileDataSync(bytes); tileDao.createSync(newRow); callback(null, self); }); }).done(); } /** * Adds an array of GeoJSON features to the GeoPackage * @param {array} features GeoJSON features to add * @param {string} tableName Name of the table to add the feature to * @param {geoPackageCallback} callback function to call when complete * @param {progressCallback} [progressCallback] function to call to report progress * @return {undefined} calls callback */ GeoPackage.prototype.addFeaturesToGeoPackage = function(features, tableName, callback, progressCallback) { progressCallback = progressCallback || function(progress, callback) { callback(null); }; console.log('adding %d features to geopackage table %s', features.length, tableName); this.initPromise.then(function(self) { var featureDao = self.featureDaos[tableName]; var index = 0; var progress = { featuresAdded: 0, totalFeatures: features.length }; async.eachSeries(features, function iterator(feature, featureComplete) { async.setImmediate(function() { var featureRow = featureDao.newRowSync(); for (var propertyKey in feature.properties) { featureRow.setValue(self.tableProperties[tableName][propertyKey], ''+feature.properties[propertyKey]); } var featureGeometry = typeof feature.geometry === 'string' ? JSON.parse(feature.geometry) : feature.geometry; var geom = featureGeometry.coordinates; var type = featureGeometry.type; var geometryAddComplete = function() { featureDao.createSync(featureRow); progress.featuresAdded++; progressCallback(progress, function(err) { featureComplete(err, featureRow); }); } if (type === 'Point') { self._addPoint(geom, featureRow, geometryAddComplete); } else if (type === 'MultiPoint') { self._addMultiPoint(geom, featureRow, geometryAddComplete); } else if (type === 'LineString') { self._addLine(geom, featureRow, geometryAddComplete); } else if (type === 'MultiLineString') { self._addMultiLine(geom, featureRow, geometryAddComplete); } else if (type === 'Polygon') { self._addPolygon(geom, featureRow, geometryAddComplete); } else if (type === 'MultiPolygon') { self._addMultiPolygon(geom, featureRow, geometryAddComplete); } }); }, function done() { callback(); }); }).done(); } /** * Indexes the GeoPackage using the NGA Table Index extension * @param {string} tableName table to index * @param {geoPackageCallback} callback called when complete * @return {undefined} calls callback */ GeoPackage.prototype.indexGeoPackage = function(tableName, callback) { this.initPromise.then(function(self) { var featureDao = self.featureDaos[tableName]; var FeatureTableIndex = java.import('mil.nga.geopackage.extension.index.FeatureTableIndex'); var featureTableIndex = new FeatureTableIndex(self.geoPackage, featureDao); var indexedFeatures = 0; var max = featureDao.countSync(); var progress = java.newProxy('mil.nga.geopackage.io.GeoPackageProgress', { setMax: function(max) { }, addProgress: function(progress) { console.log('features indexed:', indexedFeatures++); }, isActive: function() { return indexedFeatures < featureCount; }, cleanupOnCancel: function() { return false; } }); featureTableIndex.setProgress(progress); featureTableIndex.index(function(err, indexCount) { console.log('finished indexing %d features', indexCount); callback(); }); }).done(); } GeoPackage.prototype._addPoint = function(point, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createPoint(point)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addMultiPoint = function(multiPoint, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createMultiPoint(multiPoint)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addLine = function(line, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createLine(line)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addMultiLine = function(multiLine, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createMultiLine(multiLine)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addPolygon = function(polygon, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createPolygon(polygon)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addMultiPolygon = function(multiPolygon, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createMultiPolygon(multiPolygon)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } /** * Gets the names of all the feature tables in the GeoPackage * @param {Function} callback called with err, array of table names * @return {undefined} calls callback */ GeoPackage.prototype.getFeatureTables = function(callback) { this.initPromise.then(function(self) { var featureTables = self.geoPackage.getFeatureTablesSync(); var featureTableNames = [] for (var i = 0; i < featureTables.sizeSync(); i++) { featureTableNames.push(featureTables.getSync(i)); } callback(null, featureTableNames); }); } /** * Iterates the features from a table and calls the callback with the GeoJSON feature * @param {string} table table to Iterates * @param {Function} featureCallback called with err, GeoJSON feature, callback. Callback must be called to continue processing * @param {Function} doneCallback called when iteration is complete * @return {undefined} calls callback */ GeoPackage.prototype.iterateFeaturesFromTable = function(table, featureCallback, doneCallback) { this.initPromise.then(function(self) { var dataColumnsDao = self.geoPackage.getDataColumnsDaoSync(); var columnMap = {}; var featureDao = self.geoPackage.getFeatureDaoSync(table); var featureTable = featureDao.getTableSync(); var columnNames = featureTable.getColumnNamesSync(); for (var i = 0; i < columnNames.length; i++) { var dc = dataColumnsDao.getDataColumnSync(table, columnNames[i]); if (dc) { columnMap[columnNames[i]] = dc.getNameSync(); } } var featureResultSet = featureDao.queryForAllSync(); async.whilst( function() { var move = featureResultSet.moveToNextSync(); return move; }, function(callback) { var row = featureResultSet.getRowSync(); self._rowToJson(row, columnMap, function(err, json) { featureCallback(null, json, callback); }); }, function(err) { featureResultSet.closeSync(); doneCallback(); } ) }); } GeoPackage.prototype._rowToJson = function(row, columnMap, callback) { var jsonRow = { properties: { }, geometry: { } }; var columnNames = row.getColumnNamesSync(); var values = row.getValuesSync(); var pkIndex = row.getPkColumnIndexSync(); var geometryIndex = row.getGeometryColumnIndexSync(); for (var i = 0; i < values.length; i++) { if (i == pkIndex || i == geometryIndex) { // ignore these fields } else if (values[i] != null && values[i] != 'null') { jsonRow.properties[columnMap[columnNames[i]]] = values[i]; } } var gpkgGeometryData = row.getGeometrySync(); var srsId = gpkgGeometryData.getSrsIdSync(); var projection = java.callStaticMethodSync('mil.nga.geopackage.projection.ProjectionFactory', 'getProjection', srsId); var transformation = projection.getTransformationSync(4326); var geometry = gpkgGeometryData.getGeometrySync(); var type = geometry.getGeometryTypeSync().nameSync(); var geomCoordinates; switch (type) { case 'POINT': jsonRow.geometry.type = 'Point'; jsonRow.geometry.coordinates = this._readPoint(geometry, transformation); break; case 'MULTIPOINT': jsonRow.geometry.type = 'MultiPoint'; jsonRow.geometry.coordinates = this._readMultiPoint(geometry, transformation); break; case 'LINESTRING': jsonRow.geometry.type = 'LineString'; jsonRow.geometry.coordinates = this._readLine(geometry, transformation); break; case 'MULTILINESTRING': jsonRow.geometry.type = 'MultiLineString'; jsonRow.geometry.coordinates = this._readMultiLine(geometry, transformation); break; case 'POLYGON': jsonRow.geometry.type = 'Polygon'; jsonRow.geometry.coordinates = this._readPolygon(geometry, transformation); break; case 'MULTIPOLYGON': jsonRow.geometry.type = 'MultiPolygon'; jsonRow.geometry.coordinates = this._readMultiPolygon(geometry, transformation); break; } callback(null, jsonRow); } /** * Gets the names of all tile tables in the GeoPackage * @param {Function} callback called with err, array of tile table names * @return {undefined} calls callback */ GeoPackage.prototype.getTileTables = function(callback) { this.initPromise.then(function(self) { var tileTables = self.geoPackage.getTileTablesSync(); var tileTableNames = [] for (var i = 0; i < tileTables.sizeSync(); i++) { tileTableNames.push(tileTables.getSync(i)); } callback(null, tileTableNames); }); } /** * Gets the tile bytes as a stream for the xyz tile specified * @param {string} table table name to get the tile from * @param {Number} z zoom level of tile * @param {Number} x x coordinate of tile * @param {Number} y y coordinate of tile * @param {Function} callback called with err, stream * @return {undefined} calls callback */ GeoPackage.prototype.getTileFromTable = function(table, z, x, y, callback) { this.initPromise.then(function(self) { var tileDao = self.geoPackage.getTileDaoSync(table); var maxZoom = tileDao.getMaxZoomSync(); var minZoom = tileDao.getMinZoomSync(); try { var bytes = java.callStaticMethodSync('mil.nga.geopackage.tiles.TileDraw', 'drawTileBytes', self.geoPackage, table, 'png', java.newLong(x), java.newLong(y), java.newLong(z)); var buffer = new Buffer(bytes); callback(null, BufferStream(buffer)); } catch (e) { console.log('e', e); callback(e, null); } }); } /** * Creates a tile table in the GeoPackage * @param {Object} extent extent of the tile table * @param {string} tableName name of the tile table * @param {Number} minZoom minimum zoom level of the table * @param {Number} maxZoom maxiumum zoom level of the table * @param {geoPackageCallback} callback called when the table is created * @return {undefined} calls callback */ GeoPackage.prototype.createTileTable = function(extent, tableName, minZoom, maxZoom, callback) { this.initPromise.then(function(self) { var TileTable = java.import('mil.nga.geopackage.tiles.user.TileTable'); var columns = java.callStaticMethodSync('mil.nga.geopackage.tiles.user.TileTable', 'createRequiredColumns'); var tileTable = new TileTable(tableName, columns); self.geoPackage.createTileTableSync(tileTable); var xRangeMinZoom = xCalculator(extent, minZoom); var yRangeMinZoom = yCalculator(extent, minZoom); var llCorner = tileBboxCalculator(xRangeMinZoom.min, yRangeMinZoom.max, minZoom); var urCorner = tileBboxCalculator(xRangeMinZoom.max, yRangeMinZoom.min, minZoom); var totalTileExtent = [llCorner.west, llCorner.south, urCorner.east, urCorner.north]; console.log('ur ', urCorner); console.log('yrange', yRangeMinZoom); console.log('xrange', xRangeMinZoom); var epsg3857ll = proj4('EPSG:3857', [llCorner.west, llCorner.south]); var epsg3857ur = proj4('EPSG:3857', [urCorner.east, urCorner.north]); console.log('epsgur', epsg3857ur); // Create new Contents var Contents = java.import('mil.nga.geopackage.core.contents.Contents'); var contents = new Contents(); contents.setTableNameSync(tableName); contents.setDataTypeSync(java.callStaticMethodSync('mil.nga.geopackage.core.contents.ContentsDataType', 'fromName', 'tiles')); contents.setIdentifierSync(tableName); var srsDao = self.geoPackage.getSpatialReferenceSystemDaoSync(); var srsWgs84 = srsDao.getOrCreateSync(4326); var Date = java.import('java.util.Date'); contents.setLastChange(new Date()); contents.setMinXSync(java.newDouble(llCorner.west)); contents.setMinYSync(java.newDouble(llCorner.south)); contents.setMaxXSync(java.newDouble(urCorner.east)); contents.setMaxYSync(java.newDouble(urCorner.north)); contents.setSrsSync(srsWgs84); // Create the contents self.geoPackage.getContentsDaoSync().createSync(contents); // Create new Tile Matrix Set var tileMatrixSetDao = self.geoPackage.getTileMatrixSetDaoSync(); var srsDao = self.geoPackage.getSpatialReferenceSystemDaoSync(); var srsEpsg3857 = srsDao.getOrCreateSync(3857); var TileMatrixSet = java.import('mil.nga.geopackage.tiles.matrixset.TileMatrixSet'); var tileMatrixSet = new TileMatrixSet(); tileMatrixSet.setContentsSync(contents); tileMatrixSet.setSrsSync(srsEpsg3857); tileMatrixSet.setMinXSync(java.newDouble(epsg3857ll[0])); tileMatrixSet.setMinYSync(java.newDouble(epsg3857ll[1])); tileMatrixSet.setMaxXSync(java.newDouble(epsg3857ur[0])); tileMatrixSet.setMaxYSync(java.newDouble(epsg3857ur[1])); tileMatrixSetDao.createSync(tileMatrixSet); // Create new Tile Matrix and tile table rows by going through each zoom // level var tileMatrixDao = self.geoPackage.getTileMatrixDaoSync(); self.tileDaos[tableName] = self.geoPackage.getTileDaoSync(tileMatrixSet); for (var zoom = minZoom; zoom <= maxZoom; zoom++) { var xRange = xCalculator(totalTileExtent, zoom); var yRange = yCalculator(totalTileExtent, zoom); var matrixWidth = ((xRangeMinZoom.max - xRangeMinZoom.min) + 1) * Math.pow(2,(zoom - minZoom)); var matrixHeight = ((yRangeMinZoom.max - yRangeMinZoom.min) + 1) * Math.pow(2,(zoom - minZoom)); console.log('zoom: %d, matrixheight: %d, matrixwidth: %d', zoom, matrixHeight, matrixWidth); var pixelXSize = ((epsg3857ur[0] - epsg3857ll[0]) / matrixWidth) / 256; var pixelYSize = ((epsg3857ur[1] - epsg3857ll[1]) / matrixHeight) / 256; var TileMatrix = java.import('mil.nga.geopackage.tiles.matrix.TileMatrix'); var tileMatrix = new TileMatrix(); tileMatrix.setContentsSync(contents); tileMatrix.setZoomLevelSync(java.newLong(zoom)); tileMatrix.setMatrixWidthSync(java.newLong(matrixWidth)); tileMatrix.setMatrixHeightSync(java.newLong(matrixHeight)); tileMatrix.setTileWidthSync(java.newLong(256)); tileMatrix.setTileHeightSync(java.newLong(256)); tileMatrix.setPixelXSizeSync(java.newDouble(pixelXSize)); tileMatrix.setPixelYSizeSync(java.newDouble(pixelYSize)); tileMatrixDao.createSync(tileMatrix); } callback(null, self); }).done(); } /** * Adds the tile matricies for the tile table * @param {Object} extent extent of the tile table * @param {string} tableName name of the table * @param {Number} minZoom minimum zoom level of the table * @param {Number} maxZoom maxiumum zoom level of the table * @param {geoPackageCallback} callback called when the matricies are complete * @return {undefined} calls callback */ GeoPackage.prototype.addTileMatrices = function(extent, tableName, minZoom, maxZoom, callback) { this.initPromise.then(function(self) { var xRangeMinZoom = xCalculator(extent, minZoom); var yRangeMinZoom = yCalculator(extent, minZoom); var llCorner = tileBboxCalculator(xRangeMinZoom.min, yRangeMinZoom.max, minZoom); var urCorner = tileBboxCalculator(xRangeMinZoom.max, yRangeMinZoom.min, minZoom); var totalTileExtent = [llCorner.west, llCorner.south, urCorner.east, urCorner.north]; var tileMatrixDao = self.geoPackage.getTileMatrixDaoSync(); for (var zoom = minZoom; zoom <= maxZoom; zoom++) { var xRange = xCalculator(totalTileExtent, zoom); var yRange = yCalculator(totalTileExtent, zoom); var matrixWidth = ((xRangeMinZoom.max - xRangeMinZoom.min) + 1) * Math.pow(2,(zoom - minZoom)); var matrixHeight = ((yRangeMinZoom.max - yRangeMinZoom.min) + 1) * Math.pow(2,(zoom - minZoom)); console.log('zoom: %d, matrixheight: %d, matrixwidth: %d', zoom, matrixHeight, matrixWidth); var pixelXSize = ((epsg3857ur[0] - epsg3857ll[0]) / matrixWidth) / 256; var pixelYSize = ((epsg3857ur[1] - epsg3857ll[1]) / matrixHeight) / 256; var TileMatrix = java.import('mil.nga.geopackage.tiles.matrix.TileMatrix'); var tileMatrix = new TileMatrix(); tileMatrix.setContentsSync(contents); tileMatrix.setZoomLevelSync(java.newLong(zoom)); tileMatrix.setMatrixWidthSync(java.newLong(matrixWidth)); tileMatrix.setMatrixHeightSync(java.newLong(matrixHeight)); tileMatrix.setTileWidthSync(java.newLong(256)); tileMatrix.setTileHeightSync(java.newLong(256)); tileMatrix.setPixelXSizeSync(java.newDouble(pixelXSize)); tileMatrix.setPixelYSizeSync(java.newDouble(pixelYSize)); tileMatrixDao.createSync(tileMatrix); } callback(null, self); }).done(); } /** * Creates a feature table in the GeoPackage * @param {Object} extent extent of the table * @param {string} tableName name of the table * @param {Array} propertyColumnNames names of the properties * @param {geoPackageCallback} callback called when the feature table is created * @return {undefined} calls callback */ GeoPackage.prototype.createFeatureTable = function(extent, tableName, propertyColumnNames, callback) { console.log('creating feature table', tableName); this.initPromise.then(function(self) { var ArrayList = java.import('java.util.ArrayList'); var FeatureTable = java.import('mil.nga.geopackage.features.user.FeatureTable'); var Date = java.import('java.util.Date'); var GeometryColumns = java.import('mil.nga.geopackage.features.columns.GeometryColumns'); var BoundingBox = java.import('mil.nga.geopackage.BoundingBox'); var Contents = java.import('mil.nga.geopackage.core.contents.Contents'); var DataColumns = java.import('mil.nga.geopackage.schema.columns.DataColumns'); var srsDao = self.geoPackage.getSpatialReferenceSystemDaoSync(); var srsEpsg3857 = srsDao.getOrCreateSync(3857); self.geoPackage.createGeometryColumnsTableSync(); var columns = new ArrayList(); columns.addSync(java.callStaticMethodSync('mil.nga.geopackage.features.user.FeatureColumn', 'createPrimaryKeyColumn', 0, 'id')); columns.addSync(java.callStaticMethodSync('mil.nga.geopackage.features.user.FeatureColumn', 'createGeometryColumn', 1, 'geom', java.callStaticMethodSync('mil.nga.wkb.geom.GeometryType', 'fromName', 'GEOMETRY'), false, null)); self.tableProperties[tableName] = {}; for (var i = 0; i < propertyColumnNames.length; i++) { self.tableProperties[tableName][propertyColumnNames[i]] = 'property_'+i; columns.addSync(java.callStaticMethodSync('mil.nga.geopackage.features.user.FeatureColumn', 'createColumn', i+2, 'property_'+i, java.callStaticMethodSync('mil.nga.geopackage.db.GeoPackageDataType', 'fromName', 'TEXT'), false, null)); } var featureTable = new FeatureTable(tableName, columns); self.geoPackage.createFeatureTableSync(featureTable); var epsg3857ll = proj4('EPSG:3857', [extent[0], extent[1]]); var epsg3857ur = proj4('EPSG:3857', [extent[2], extent[3]]); var contents = new Contents(); contents.setTableNameSync(tableName); contents.setDataTypeSync(java.callStaticMethodSync('mil.nga.geopackage.core.contents.ContentsDataType', 'fromName', 'features')); contents.setIdentifierSync(tableName); // contents.setDescription(""); contents.setLastChange(new Date()); contents.setMinXSync(java.newDouble(epsg3857ll[0])); contents.setMinYSync(java.newDouble(epsg3857ll[1])); contents.setMaxXSync(java.newDouble(epsg3857ur[0])); contents.setMaxYSync(java.newDouble(epsg3857ur[1])); contents.setSrsSync(srsEpsg3857); self.geoPackage.getContentsDaoSync().createSync(contents); var geometryColumns = new GeometryColumns(); geometryColumns.setContentsSync(contents); geometryColumns.setSrsSync(contents.getSrsSync()); geometryColumns.setGeometryTypeSync(java.callStaticMethodSync('mil.nga.wkb.geom.GeometryType', 'fromName', 'GEOMETRY')); geometryColumns.setColumnNameSync('geom'); self.geoPackage.getGeometryColumnsDaoSync().create(geometryColumns); self.featureDaos[tableName] = self.geoPackage.getFeatureDaoSync(geometryColumns); self.geoPackage.createDataColumnsTableSync(); var dataColumnsDao = self.geoPackage.getDataColumnsDaoSync(); for (var i = 0; i < propertyColumnNames.length; i++) { var dataColumns = new DataColumns(); dataColumns.setContentsSync(contents); dataColumns.setColumnNameSync('property_'+i); dataColumns.setNameSync(propertyColumnNames[i]); dataColumns.setTitleSync(propertyColumnNames[i]); dataColumns.setDescriptionSync(propertyColumnNames[i]); dataColumnsDao.createSync(dataColumns); } callback(null, self); }).done(); } GeoPackage.prototype._readPoint = function(point, transformation) { return transformation.transformSync(point.getXSync(), point.getYSync()); } GeoPackage.prototype._createPoint = function(point) { var Point = java.import('mil.nga.wkb.geom.Point'); return new Point(java.newDouble(point[0]), java.newDouble(point[1])); } GeoPackage.prototype._readMultiPoint = function(multiPoint, transformation) { var points = multiPoint.getPointsSync(); var numPoints = multiPoint.numPointsSync(); var jsonPoints = []; for (var i = 0; i < numPoints; i++) { jsonPoints.push(this._readPoint(points.getSync(i), transformation)); } return jsonPoints; } GeoPackage.prototype._createMultiPoint = function(multiPoint) { var MultiPoint = java.import('mil.nga.wkb.geom.MultiPoint'); var multiPointGeom = new MultiPoint(false, false); for (var i = 0; i < multiPoint.length; i++) { multiPointGeom.addPointSync(this._createPoint(multiPoint[i])); } return multiPointGeom; } GeoPackage.prototype._readLine = function(line, transformation) { var points = line.getPointsSync(); var numPoints = line.numPointsSync(); var jsonPoints = []; for (var i = 0; i < numPoints; i++) { jsonPoints.push(this._readPoint(points.getSync(i), transformation)); } return jsonPoints; } GeoPackage.prototype._createLine = function(line) { var LineString = java.import('mil.nga.wkb.geom.LineString'); var lineGeom = new LineString(false, false); for (var i = 0; i < line.length; i++) { var point = line[i]; if (point[0] == null || point[1] == null) continue; lineGeom.addPointSync(this._createPoint(point)); } return lineGeom; } GeoPackage.prototype._readMultiLine = function(multiLine, transformation) { var lineStrings = multiLine.getLineStringsSync(); var numStrings = multiLine.numLineStringsSync(); var jsonLines = []; for (var i = 0; i < numStrings; i++) { var line = lineStrings.getSync(i); jsonLines.push(this._readLine(line, transformation)); } return jsonLines; } GeoPackage.prototype._createMultiLine = function(multiLine) { var MultiLineString = java.import('mil.nga.wkb.geom.MultiLineString'); var multiLineGeom = new MultiLineString(false, false); for (var i = 0; i < multiLine.length; i++) { var line = multiLine[i]; multiLineGeom.addLineStringSync(this._createLine(line)); } return multiLineGeom; } GeoPackage.prototype._readPolygon = function(polygon, transformation) { var rings = polygon.getRingsSync(); var numRings = polygon.getNumRingsSync(); var jsonRings = []; for (var i = 0; i < numRings; i++) { var ring = rings.getSync(i); jsonRings.push(this._readLine(ring, transformation)); } return jsonRings; } GeoPackage.prototype._createPolygon = function(polygon) { var Polygon = java.import('mil.nga.wkb.geom.Polygon'); var polygonGeom = new Polygon(false, false); for (var ring = 0; ring < polygon.length; ring++) { var linearRing = polygon[ring]; polygonGeom.addRingSync(this._createLine(linearRing)); } return polygonGeom; } GeoPackage.prototype._readMultiPolygon = function(multiPolygon, transformation) { var polygons = multiPolygon.getPolygonsSync(); var numPolygons = multiPolygon.getNumPolygonsSync(); var jsonPolygons = []; for (var i = 0; i < numPolygons; i++) { var polygon = polygons.getSync(i); jsonPolygons.push(this._readPolygon(polygon, transformation)); } return jsonPolygons; } GeoPackage.prototype._createMultiPolygon = function(multiPolygon) { var MultiPolygon = java.import('mil.nga.wkb.geom.MultiPolygon'); var multiPolygonGeom = new MultiPolygon(false, false); for (var polygon = 0; polygon < multiPolygon.length; polygon++) { multiPolygonGeom.addPolygonSync(this._createPolygon(multiPolygon[polygon])); } return multiPolygonGeom; } module.exports = GeoPackage;
geopackage.js
var java = require('java') , mvn = require('node-java-maven') , proj4 = require('proj4') , async = require('async') , toArray = require('stream-to-array') , BufferStream = require('simple-bufferstream') , q = require('q'); // this is necessary for the ImageIO calls within the GeoPackage library java.options.push("-Djava.awt.headless=true"); Math.radians = function(degrees) { return degrees * Math.PI / 180; }; Math.degrees = function(radians) { return radians * 180 / Math.PI; }; function tile2lon(x,z) { return (x/Math.pow(2,z)*360-180); } function tile2lat(y,z) { var n=Math.PI-2*Math.PI*y/Math.pow(2,z); return (180/Math.PI*Math.atan(0.5*(Math.exp(n)-Math.exp(-n)))); } var getX = function(lon, zoom) { if (zoom == 0) return 0; var xtile = Math.floor((lon + 180) / 360 * (1 << zoom)); return xtile; } var getY = function(lat, zoom) { if (zoom == 0) return 0; var ytile = Math.floor((1 - Math.log(Math.tan(Math.radians(parseFloat(lat))) + 1 / Math.cos(Math.radians(parseFloat(lat)))) / Math.PI) /2 * (1 << zoom)); return ytile; } var xCalculator = function(bbox,z) { var x = []; var x1 = getX(Number(bbox[0]), z); var x2 = getX(Number(bbox[2]), z); x.max = Math.max(x1, x2); x.min = Math.max(0,Math.min(x1, x2)); if (z == 0){ x.current = Math.min(x1, x2); } return x; } var yCalculator = function(bbox,z) { var y = []; var y1 = getY(Number(bbox[1]), z); var y2 = getY(Number(bbox[3]), z); y.max = Math.max(y1, y2); y.min = Math.max(0,Math.min(y1, y2)); y.current = Math.min(y1, y2); return y; } var tileBboxCalculator = function(x, y, z) { x = Number(x); y = Number(y); var tileBounds = { north: tile2lat(y, z), east: tile2lon(x+1, z), south: tile2lat(y+1, z), west: tile2lon(x, z) }; return tileBounds; } /** * Constructor for the GeoPackage API object that can be used to operate on the GeoPackage. * @constructor * @param {Object} configuration object * @returns {Object} GeoPackage API object. */ var GeoPackage = function(config) { config = config || {}; this.featureDaos = {}; this.tileDaos = {}; this.tableProperties = {}; this.initDefer = q.defer(); this.initPromise = this.initDefer.promise; this._initialize(); this.initPromise.then(function(self){ // set up the log4j library to log to the console. var ConsoleAppender = java.import('org.apache.log4j.ConsoleAppender'); var PatternLayout = java.import('org.apache.log4j.PatternLayout'); var consoleAppender = new ConsoleAppender(); //create appender var PATTERN = "%d [%p|%c|%C{1}] %m%n"; consoleAppender.setLayoutSync(new PatternLayout(PATTERN)); consoleAppender.setThresholdSync(java.callStaticMethodSync('org.apache.log4j.Level', 'toLevel', config.log4jLevel || 'INFO')); consoleAppender.activateOptionsSync(); java.callStaticMethodSync('org.apache.log4j.Logger', 'getRootLogger').addAppenderSync(consoleAppender); }); } /** * Initialize the GeoPackage API. Pulls down and adds maven artifacts to the java classpath * @private */ GeoPackage.prototype._initialize = function() { console.log('Initializing the GeoPackage with the package json', __dirname+'/package.json'); var self = this; try { mvn({ packageJsonPath: __dirname+'/package.json' }, function(err, mvnResults) { console.log('retrieved the maven atrifacts'); if (err) { return console.error('could not resolve maven dependencies', err); } mvnResults.classpath.forEach(function(c) { console.log('adding ' + c + ' to classpath'); java.classpath.push(c); }); console.log('resolving promise'); self.initDefer.resolve(self); }); } catch (e) { console.error('e', e); } } /** * Callback for general GeoPackage operations. * * @callback geoPackageCallback * @param {Object} err - Any error that occurred. * @param {Object} geoPackageAPI - this GeoPackageAPI object */ /** * Progress callback for GeoPackage operations. This function must call the callback passed to it * to continue processing. * * @callback progressCallback * @param {Object} progress - the current progress. * @param {Function} callback - callback to be called to continue processing */ /** * Creates a new GeoPackage at the path specified and opens that GeoPackage for editing * @param {string} filePath Absolute path to the GeoPackage to create * @param {geoPackageCallback} callback function to callback when created * @return {undefined} calls callback */ GeoPackage.prototype.createAndOpenGeoPackageFile = function(filePath, callback) { console.log('opening geopackage ' + filePath); this.initPromise.then(function(self) { var File = java.import('java.io.File'); var gpkgFile = new File(filePath); java.callStaticMethodSync('mil.nga.geopackage.manager.GeoPackageManager', 'create', gpkgFile); self.geoPackage = java.callStaticMethodSync('mil.nga.geopackage.manager.GeoPackageManager', 'open', gpkgFile); self.geoPackage.createTileMatrixSetTableSync(); self.geoPackage.createTileMatrixTableSync(); var srsDao = self.geoPackage.getSpatialReferenceSystemDaoSync(); var srsWgs84 = srsDao.getOrCreateSync(4326); var srsEpsg3857 = srsDao.getOrCreateSync(3857); callback(null, self); }).done(); } /** * Opens an existing GeoPackage at the path specified for reading and writing * @param {string} filePath Absolute path to the GeoPackage to create * @param {geoPackageCallback} callback function to callback when created * @return {undefined} calls callback */ GeoPackage.prototype.openGeoPackageFile = function(filePath, callback) { console.log('opening geopackage ' + filePath); this.initPromise.then(function(self) { console.log('promise inited'); var File = java.import('java.io.File'); var gpkgFile = new File(filePath); var canRead = gpkgFile.canReadSync(); console.log('can read the geopackage file? ', canRead); self.geoPackage = java.callStaticMethodSync('mil.nga.geopackage.manager.GeoPackageManager', 'open', gpkgFile); callback(null, self); }).done(); } /** * Adds a tile to the GeoPackage * @param {Object} tileStream Stream to the tile file * @param {string} tableName Name of the table to add the tile to * @param {Number} zoom Zoom level of the tile * @param {Number} tileRow Tile row * @param {Number} tileColumn Tile columns * @param {geoPackageCallback} callback function to call when complete * @return {undefined} calls callback */ GeoPackage.prototype.addTileToGeoPackage = function(tileStream, tableName, zoom, tileRow, tileColumn, callback) { this.initPromise.then(function(self) { var tileDao = self.tileDaos[tableName]; var newRow = tileDao.newRowSync(); newRow.setZoomLevelSync(java.newLong(zoom)); newRow.setTileColumnSync(java.newLong(tileColumn)); newRow.setTileRowSync(java.newLong(tileRow)); toArray(tileStream, function (err, parts) { var byteArray = []; for (var k = 0; k < parts.length; k++) { var part = parts[k]; for (var i = 0; i < part.length; i++) { var bufferPiece = part[i]; var byte = java.newByte(bufferPiece); byteArray.push(byte); } } var bytes = java.newArray('byte', byteArray); newRow.setTileDataSync(bytes); tileDao.createSync(newRow); callback(null, self); }); }).done(); } /** * Adds an array of GeoJSON features to the GeoPackage * @param {array} features GeoJSON features to add * @param {string} tableName Name of the table to add the feature to * @param {geoPackageCallback} callback function to call when complete * @param {progressCallback} [progressCallback] function to call to report progress * @return {undefined} calls callback */ GeoPackage.prototype.addFeaturesToGeoPackage = function(features, tableName, callback, progressCallback) { progressCallback = progressCallback || function(progress, callback) { callback(null); }; console.log('adding %d features to geopackage table %s', features.length, tableName); this.initPromise.then(function(self) { var featureDao = self.featureDaos[tableName]; var index = 0; var progress = { featuresAdded: 0, totalFeatures: features.length }; async.eachSeries(features, function iterator(feature, featureComplete) { async.setImmediate(function() { var featureRow = featureDao.newRowSync(); for (var propertyKey in feature.properties) { featureRow.setValue(self.tableProperties[tableName][propertyKey], ''+feature.properties[propertyKey]); } var featureGeometry = JSON.parse(feature.geometry); var geom = featureGeometry.coordinates; var type = featureGeometry.type; var geometryAddComplete = function() { featureDao.createSync(featureRow); progress.featuresAdded++; progressCallback(progress, function(err) { featureComplete(err, featureRow); }); } if (type === 'Point') { self._addPoint(geom, featureRow, geometryAddComplete); } else if (type === 'MultiPoint') { self._addMultiPoint(geom, featureRow, geometryAddComplete); } else if (type === 'LineString') { self._addLine(geom, featureRow, geometryAddComplete); } else if (type === 'MultiLineString') { self._addMultiLine(geom, featureRow, geometryAddComplete); } else if (type === 'Polygon') { self._addPolygon(geom, featureRow, geometryAddComplete); } else if (type === 'MultiPolygon') { self._addMultiPolygon(geom, featureRow, geometryAddComplete); } }); }, function done() { callback(); }); }).done(); } /** * Indexes the GeoPackage using the NGA Table Index extension * @param {string} tableName table to index * @param {geoPackageCallback} callback called when complete * @return {undefined} calls callback */ GeoPackage.prototype.indexGeoPackage = function(tableName, callback) { this.initPromise.then(function(self) { var featureDao = self.featureDaos[tableName]; var FeatureTableIndex = java.import('mil.nga.geopackage.extension.index.FeatureTableIndex'); var featureTableIndex = new FeatureTableIndex(self.geoPackage, featureDao); var indexedFeatures = 0; var max = featureDao.countSync(); var progress = java.newProxy('mil.nga.geopackage.io.GeoPackageProgress', { setMax: function(max) { }, addProgress: function(progress) { console.log('features indexed:', indexedFeatures++); }, isActive: function() { return indexedFeatures < featureCount; }, cleanupOnCancel: function() { return false; } }); featureTableIndex.setProgress(progress); featureTableIndex.index(function(err, indexCount) { console.log('finished indexing %d features', indexCount); callback(); }); }).done(); } GeoPackage.prototype._addPoint = function(point, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createPoint(point)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addMultiPoint = function(multiPoint, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createMultiPoint(multiPoint)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addLine = function(line, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createLine(line)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addMultiLine = function(multiLine, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createMultiLine(multiLine)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addPolygon = function(polygon, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createPolygon(polygon)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } GeoPackage.prototype._addMultiPolygon = function(multiPolygon, featureRow, callback) { this.initPromise.then(function(self) { var GeoPackageGeometryData = java.import('mil.nga.geopackage.geom.GeoPackageGeometryData'); var geometryData = new GeoPackageGeometryData(3857); geometryData.setGeometrySync(self._createMultiPolygon(multiPolygon)); featureRow.setGeometrySync(geometryData); callback(); }).done(); } /** * Gets the names of all the feature tables in the GeoPackage * @param {Function} callback called with err, array of table names * @return {undefined} calls callback */ GeoPackage.prototype.getFeatureTables = function(callback) { this.initPromise.then(function(self) { var featureTables = self.geoPackage.getFeatureTablesSync(); var featureTableNames = [] for (var i = 0; i < featureTables.sizeSync(); i++) { featureTableNames.push(featureTables.getSync(i)); } callback(null, featureTableNames); }); } /** * Iterates the features from a table and calls the callback with the GeoJSON feature * @param {string} table table to Iterates * @param {Function} featureCallback called with err, GeoJSON feature, callback. Callback must be called to continue processing * @param {Function} doneCallback called when iteration is complete * @return {undefined} calls callback */ GeoPackage.prototype.iterateFeaturesFromTable = function(table, featureCallback, doneCallback) { this.initPromise.then(function(self) { var dataColumnsDao = self.geoPackage.getDataColumnsDaoSync(); var columnMap = {}; var featureDao = self.geoPackage.getFeatureDaoSync(table); var featureTable = featureDao.getTableSync(); var columnNames = featureTable.getColumnNamesSync(); for (var i = 0; i < columnNames.length; i++) { var dc = dataColumnsDao.getDataColumnSync(table, columnNames[i]); if (dc) { columnMap[columnNames[i]] = dc.getNameSync(); } } var featureResultSet = featureDao.queryForAllSync(); async.whilst( function() { var move = featureResultSet.moveToNextSync(); return move; }, function(callback) { var row = featureResultSet.getRowSync(); self._rowToJson(row, columnMap, function(err, json) { featureCallback(null, json, callback); }); }, function(err) { featureResultSet.closeSync(); doneCallback(); } ) }); } GeoPackage.prototype._rowToJson = function(row, columnMap, callback) { var jsonRow = { properties: { }, geometry: { } }; var columnNames = row.getColumnNamesSync(); var values = row.getValuesSync(); var pkIndex = row.getPkColumnIndexSync(); var geometryIndex = row.getGeometryColumnIndexSync(); for (var i = 0; i < values.length; i++) { if (i == pkIndex || i == geometryIndex) { // ignore these fields } else if (values[i] != null && values[i] != 'null') { jsonRow.properties[columnMap[columnNames[i]]] = values[i]; } } var gpkgGeometryData = row.getGeometrySync(); var srsId = gpkgGeometryData.getSrsIdSync(); var projection = java.callStaticMethodSync('mil.nga.geopackage.projection.ProjectionFactory', 'getProjection', srsId); var transformation = projection.getTransformationSync(4326); var geometry = gpkgGeometryData.getGeometrySync(); var type = geometry.getGeometryTypeSync().nameSync(); var geomCoordinates; switch (type) { case 'POINT': jsonRow.geometry.type = 'Point'; jsonRow.geometry.coordinates = this._readPoint(geometry, transformation); break; case 'MULTIPOINT': jsonRow.geometry.type = 'MultiPoint'; jsonRow.geometry.coordinates = this._readMultiPoint(geometry, transformation); break; case 'LINESTRING': jsonRow.geometry.type = 'LineString'; jsonRow.geometry.coordinates = this._readLine(geometry, transformation); break; case 'MULTILINESTRING': jsonRow.geometry.type = 'MultiLineString'; jsonRow.geometry.coordinates = this._readMultiLine(geometry, transformation); break; case 'POLYGON': jsonRow.geometry.type = 'Polygon'; jsonRow.geometry.coordinates = this._readPolygon(geometry, transformation); break; case 'MULTIPOLYGON': jsonRow.geometry.type = 'MultiPolygon'; jsonRow.geometry.coordinates = this._readMultiPolygon(geometry, transformation); break; } callback(null, jsonRow); } /** * Gets the names of all tile tables in the GeoPackage * @param {Function} callback called with err, array of tile table names * @return {undefined} calls callback */ GeoPackage.prototype.getTileTables = function(callback) { this.initPromise.then(function(self) { var tileTables = self.geoPackage.getTileTablesSync(); var tileTableNames = [] for (var i = 0; i < tileTables.sizeSync(); i++) { tileTableNames.push(tileTables.getSync(i)); } callback(null, tileTableNames); }); } /** * Gets the tile bytes as a stream for the xyz tile specified * @param {string} table table name to get the tile from * @param {Number} z zoom level of tile * @param {Number} x x coordinate of tile * @param {Number} y y coordinate of tile * @param {Function} callback called with err, stream * @return {undefined} calls callback */ GeoPackage.prototype.getTileFromTable = function(table, z, x, y, callback) { this.initPromise.then(function(self) { var tileDao = self.geoPackage.getTileDaoSync(table); var maxZoom = tileDao.getMaxZoomSync(); var minZoom = tileDao.getMinZoomSync(); try { var bytes = java.callStaticMethodSync('mil.nga.geopackage.tiles.TileDraw', 'drawTileBytes', self.geoPackage, table, 'png', java.newLong(x), java.newLong(y), java.newLong(z)); var buffer = new Buffer(bytes); callback(null, BufferStream(buffer)); } catch (e) { console.log('e', e); callback(e, null); } }); } /** * Creates a tile table in the GeoPackage * @param {Object} extent extent of the tile table * @param {string} tableName name of the tile table * @param {Number} minZoom minimum zoom level of the table * @param {Number} maxZoom maxiumum zoom level of the table * @param {geoPackageCallback} callback called when the table is created * @return {undefined} calls callback */ GeoPackage.prototype.createTileTable = function(extent, tableName, minZoom, maxZoom, callback) { this.initPromise.then(function(self) { var TileTable = java.import('mil.nga.geopackage.tiles.user.TileTable'); var columns = java.callStaticMethodSync('mil.nga.geopackage.tiles.user.TileTable', 'createRequiredColumns'); var tileTable = new TileTable(tableName, columns); self.geoPackage.createTileTableSync(tileTable); var xRangeMinZoom = xCalculator(extent, minZoom); var yRangeMinZoom = yCalculator(extent, minZoom); var llCorner = tileBboxCalculator(xRangeMinZoom.min, yRangeMinZoom.max, minZoom); var urCorner = tileBboxCalculator(xRangeMinZoom.max, yRangeMinZoom.min, minZoom); var totalTileExtent = [llCorner.west, llCorner.south, urCorner.east, urCorner.north]; console.log('ur ', urCorner); console.log('yrange', yRangeMinZoom); console.log('xrange', xRangeMinZoom); var epsg3857ll = proj4('EPSG:3857', [llCorner.west, llCorner.south]); var epsg3857ur = proj4('EPSG:3857', [urCorner.east, urCorner.north]); console.log('epsgur', epsg3857ur); // Create new Contents var Contents = java.import('mil.nga.geopackage.core.contents.Contents'); var contents = new Contents(); contents.setTableNameSync(tableName); contents.setDataTypeSync(java.callStaticMethodSync('mil.nga.geopackage.core.contents.ContentsDataType', 'fromName', 'tiles')); contents.setIdentifierSync(tableName); var srsDao = self.geoPackage.getSpatialReferenceSystemDaoSync(); var srsWgs84 = srsDao.getOrCreateSync(4326); var Date = java.import('java.util.Date'); contents.setLastChange(new Date()); contents.setMinXSync(java.newDouble(llCorner.west)); contents.setMinYSync(java.newDouble(llCorner.south)); contents.setMaxXSync(java.newDouble(urCorner.east)); contents.setMaxYSync(java.newDouble(urCorner.north)); contents.setSrsSync(srsWgs84); // Create the contents self.geoPackage.getContentsDaoSync().createSync(contents); // Create new Tile Matrix Set var tileMatrixSetDao = self.geoPackage.getTileMatrixSetDaoSync(); var srsDao = self.geoPackage.getSpatialReferenceSystemDaoSync(); var srsEpsg3857 = srsDao.getOrCreateSync(3857); var TileMatrixSet = java.import('mil.nga.geopackage.tiles.matrixset.TileMatrixSet'); var tileMatrixSet = new TileMatrixSet(); tileMatrixSet.setContentsSync(contents); tileMatrixSet.setSrsSync(srsEpsg3857); tileMatrixSet.setMinXSync(java.newDouble(epsg3857ll[0])); tileMatrixSet.setMinYSync(java.newDouble(epsg3857ll[1])); tileMatrixSet.setMaxXSync(java.newDouble(epsg3857ur[0])); tileMatrixSet.setMaxYSync(java.newDouble(epsg3857ur[1])); tileMatrixSetDao.createSync(tileMatrixSet); // Create new Tile Matrix and tile table rows by going through each zoom // level var tileMatrixDao = self.geoPackage.getTileMatrixDaoSync(); self.tileDaos[tableName] = self.geoPackage.getTileDaoSync(tileMatrixSet); for (var zoom = minZoom; zoom <= maxZoom; zoom++) { var xRange = xCalculator(totalTileExtent, zoom); var yRange = yCalculator(totalTileExtent, zoom); var matrixWidth = ((xRangeMinZoom.max - xRangeMinZoom.min) + 1) * Math.pow(2,(zoom - minZoom)); var matrixHeight = ((yRangeMinZoom.max - yRangeMinZoom.min) + 1) * Math.pow(2,(zoom - minZoom)); console.log('zoom: %d, matrixheight: %d, matrixwidth: %d', zoom, matrixHeight, matrixWidth); var pixelXSize = ((epsg3857ur[0] - epsg3857ll[0]) / matrixWidth) / 256; var pixelYSize = ((epsg3857ur[1] - epsg3857ll[1]) / matrixHeight) / 256; var TileMatrix = java.import('mil.nga.geopackage.tiles.matrix.TileMatrix'); var tileMatrix = new TileMatrix(); tileMatrix.setContentsSync(contents); tileMatrix.setZoomLevelSync(java.newLong(zoom)); tileMatrix.setMatrixWidthSync(java.newLong(matrixWidth)); tileMatrix.setMatrixHeightSync(java.newLong(matrixHeight)); tileMatrix.setTileWidthSync(java.newLong(256)); tileMatrix.setTileHeightSync(java.newLong(256)); tileMatrix.setPixelXSizeSync(java.newDouble(pixelXSize)); tileMatrix.setPixelYSizeSync(java.newDouble(pixelYSize)); tileMatrixDao.createSync(tileMatrix); } callback(null, self); }).done(); } /** * Adds the tile matricies for the tile table * @param {Object} extent extent of the tile table * @param {string} tableName name of the table * @param {Number} minZoom minimum zoom level of the table * @param {Number} maxZoom maxiumum zoom level of the table * @param {geoPackageCallback} callback called when the matricies are complete * @return {undefined} calls callback */ GeoPackage.prototype.addTileMatrices = function(extent, tableName, minZoom, maxZoom, callback) { this.initPromise.then(function(self) { var xRangeMinZoom = xCalculator(extent, minZoom); var yRangeMinZoom = yCalculator(extent, minZoom); var llCorner = tileBboxCalculator(xRangeMinZoom.min, yRangeMinZoom.max, minZoom); var urCorner = tileBboxCalculator(xRangeMinZoom.max, yRangeMinZoom.min, minZoom); var totalTileExtent = [llCorner.west, llCorner.south, urCorner.east, urCorner.north]; var tileMatrixDao = self.geoPackage.getTileMatrixDaoSync(); for (var zoom = minZoom; zoom <= maxZoom; zoom++) { var xRange = xCalculator(totalTileExtent, zoom); var yRange = yCalculator(totalTileExtent, zoom); var matrixWidth = ((xRangeMinZoom.max - xRangeMinZoom.min) + 1) * Math.pow(2,(zoom - minZoom)); var matrixHeight = ((yRangeMinZoom.max - yRangeMinZoom.min) + 1) * Math.pow(2,(zoom - minZoom)); console.log('zoom: %d, matrixheight: %d, matrixwidth: %d', zoom, matrixHeight, matrixWidth); var pixelXSize = ((epsg3857ur[0] - epsg3857ll[0]) / matrixWidth) / 256; var pixelYSize = ((epsg3857ur[1] - epsg3857ll[1]) / matrixHeight) / 256; var TileMatrix = java.import('mil.nga.geopackage.tiles.matrix.TileMatrix'); var tileMatrix = new TileMatrix(); tileMatrix.setContentsSync(contents); tileMatrix.setZoomLevelSync(java.newLong(zoom)); tileMatrix.setMatrixWidthSync(java.newLong(matrixWidth)); tileMatrix.setMatrixHeightSync(java.newLong(matrixHeight)); tileMatrix.setTileWidthSync(java.newLong(256)); tileMatrix.setTileHeightSync(java.newLong(256)); tileMatrix.setPixelXSizeSync(java.newDouble(pixelXSize)); tileMatrix.setPixelYSizeSync(java.newDouble(pixelYSize)); tileMatrixDao.createSync(tileMatrix); } callback(null, self); }).done(); } /** * Creates a feature table in the GeoPackage * @param {Object} extent extent of the table * @param {string} tableName name of the table * @param {Array} propertyColumnNames names of the properties * @param {geoPackageCallback} callback called when the feature table is created * @return {undefined} calls callback */ GeoPackage.prototype.createFeatureTable = function(extent, tableName, propertyColumnNames, callback) { console.log('creating feature table', tableName); this.initPromise.then(function(self) { var ArrayList = java.import('java.util.ArrayList'); var FeatureTable = java.import('mil.nga.geopackage.features.user.FeatureTable'); var Date = java.import('java.util.Date'); var GeometryColumns = java.import('mil.nga.geopackage.features.columns.GeometryColumns'); var BoundingBox = java.import('mil.nga.geopackage.BoundingBox'); var Contents = java.import('mil.nga.geopackage.core.contents.Contents'); var DataColumns = java.import('mil.nga.geopackage.schema.columns.DataColumns'); var srsDao = self.geoPackage.getSpatialReferenceSystemDaoSync(); var srsEpsg3857 = srsDao.getOrCreateSync(3857); self.geoPackage.createGeometryColumnsTableSync(); var columns = new ArrayList(); columns.addSync(java.callStaticMethodSync('mil.nga.geopackage.features.user.FeatureColumn', 'createPrimaryKeyColumn', 0, 'id')); columns.addSync(java.callStaticMethodSync('mil.nga.geopackage.features.user.FeatureColumn', 'createGeometryColumn', 1, 'geom', java.callStaticMethodSync('mil.nga.wkb.geom.GeometryType', 'fromName', 'GEOMETRY'), false, null)); self.tableProperties[tableName] = {}; for (var i = 0; i < propertyColumnNames.length; i++) { self.tableProperties[tableName][propertyColumnNames[i]] = 'property_'+i; columns.addSync(java.callStaticMethodSync('mil.nga.geopackage.features.user.FeatureColumn', 'createColumn', i+2, 'property_'+i, java.callStaticMethodSync('mil.nga.geopackage.db.GeoPackageDataType', 'fromName', 'TEXT'), false, null)); } var featureTable = new FeatureTable(tableName, columns); self.geoPackage.createFeatureTableSync(featureTable); var epsg3857ll = proj4('EPSG:3857', [extent[0], extent[1]]); var epsg3857ur = proj4('EPSG:3857', [extent[2], extent[3]]); var contents = new Contents(); contents.setTableNameSync(tableName); contents.setDataTypeSync(java.callStaticMethodSync('mil.nga.geopackage.core.contents.ContentsDataType', 'fromName', 'features')); contents.setIdentifierSync(tableName); // contents.setDescription(""); contents.setLastChange(new Date()); contents.setMinXSync(java.newDouble(epsg3857ll[0])); contents.setMinYSync(java.newDouble(epsg3857ll[1])); contents.setMaxXSync(java.newDouble(epsg3857ur[0])); contents.setMaxYSync(java.newDouble(epsg3857ur[1])); contents.setSrsSync(srsEpsg3857); self.geoPackage.getContentsDaoSync().createSync(contents); var geometryColumns = new GeometryColumns(); geometryColumns.setContentsSync(contents); geometryColumns.setSrsSync(contents.getSrsSync()); geometryColumns.setGeometryTypeSync(java.callStaticMethodSync('mil.nga.wkb.geom.GeometryType', 'fromName', 'GEOMETRY')); geometryColumns.setColumnNameSync('geom'); self.geoPackage.getGeometryColumnsDaoSync().create(geometryColumns); self.featureDaos[tableName] = self.geoPackage.getFeatureDaoSync(geometryColumns); self.geoPackage.createDataColumnsTableSync(); var dataColumnsDao = self.geoPackage.getDataColumnsDaoSync(); for (var i = 0; i < propertyColumnNames.length; i++) { var dataColumns = new DataColumns(); dataColumns.setContentsSync(contents); dataColumns.setColumnNameSync('property_'+i); dataColumns.setNameSync(propertyColumnNames[i]); dataColumns.setTitleSync(propertyColumnNames[i]); dataColumns.setDescriptionSync(propertyColumnNames[i]); dataColumnsDao.createSync(dataColumns); } callback(null, self); }).done(); } GeoPackage.prototype._readPoint = function(point, transformation) { return transformation.transformSync(point.getXSync(), point.getYSync()); } GeoPackage.prototype._createPoint = function(point) { var Point = java.import('mil.nga.wkb.geom.Point'); return new Point(java.newDouble(point[0]), java.newDouble(point[1])); } GeoPackage.prototype._readMultiPoint = function(multiPoint, transformation) { var points = multiPoint.getPointsSync(); var numPoints = multiPoint.numPointsSync(); var jsonPoints = []; for (var i = 0; i < numPoints; i++) { jsonPoints.push(this._readPoint(points.getSync(i), transformation)); } return jsonPoints; } GeoPackage.prototype._createMultiPoint = function(multiPoint) { var MultiPoint = java.import('mil.nga.wkb.geom.MultiPoint'); var multiPointGeom = new MultiPoint(false, false); for (var i = 0; i < multiPoint.length; i++) { multiPointGeom.addPointSync(this._createPoint(multiPoint[i])); } return multiPointGeom; } GeoPackage.prototype._readLine = function(line, transformation) { var points = line.getPointsSync(); var numPoints = line.numPointsSync(); var jsonPoints = []; for (var i = 0; i < numPoints; i++) { jsonPoints.push(this._readPoint(points.getSync(i), transformation)); } return jsonPoints; } GeoPackage.prototype._createLine = function(line) { var LineString = java.import('mil.nga.wkb.geom.LineString'); var lineGeom = new LineString(false, false); for (var i = 0; i < line.length; i++) { var point = line[i]; if (point[0] == null || point[1] == null) continue; lineGeom.addPointSync(this._createPoint(point)); } return lineGeom; } GeoPackage.prototype._readMultiLine = function(multiLine, transformation) { var lineStrings = multiLine.getLineStringsSync(); var numStrings = multiLine.numLineStringsSync(); var jsonLines = []; for (var i = 0; i < numStrings; i++) { var line = lineStrings.getSync(i); jsonLines.push(this._readLine(line, transformation)); } return jsonLines; } GeoPackage.prototype._createMultiLine = function(multiLine) { var MultiLineString = java.import('mil.nga.wkb.geom.MultiLineString'); var multiLineGeom = new MultiLineString(false, false); for (var i = 0; i < multiLine.length; i++) { var line = multiLine[i]; multiLineGeom.addLineStringSync(this._createLine(line)); } return multiLineGeom; } GeoPackage.prototype._readPolygon = function(polygon, transformation) { var rings = polygon.getRingsSync(); var numRings = polygon.getNumRingsSync(); var jsonRings = []; for (var i = 0; i < numRings; i++) { var ring = rings.getSync(i); jsonRings.push(this._readLine(ring, transformation)); } return jsonRings; } GeoPackage.prototype._createPolygon = function(polygon) { var Polygon = java.import('mil.nga.wkb.geom.Polygon'); var polygonGeom = new Polygon(false, false); for (var ring = 0; ring < polygon.length; ring++) { var linearRing = polygon[ring]; polygonGeom.addRingSync(this._createLine(linearRing)); } return polygonGeom; } GeoPackage.prototype._readMultiPolygon = function(multiPolygon, transformation) { var polygons = multiPolygon.getPolygonsSync(); var numPolygons = multiPolygon.getNumPolygonsSync(); var jsonPolygons = []; for (var i = 0; i < numPolygons; i++) { var polygon = polygons.getSync(i); jsonPolygons.push(this._readPolygon(polygon, transformation)); } return jsonPolygons; } GeoPackage.prototype._createMultiPolygon = function(multiPolygon) { var MultiPolygon = java.import('mil.nga.wkb.geom.MultiPolygon'); var multiPolygonGeom = new MultiPolygon(false, false); for (var polygon = 0; polygon < multiPolygon.length; polygon++) { multiPolygonGeom.addPolygonSync(this._createPolygon(multiPolygon[polygon])); } return multiPolygonGeom; } module.exports = GeoPackage;
only parse the feature geometry if it is actually a string
geopackage.js
only parse the feature geometry if it is actually a string
<ide><path>eopackage.js <ide> featureRow.setValue(self.tableProperties[tableName][propertyKey], ''+feature.properties[propertyKey]); <ide> } <ide> <del> var featureGeometry = JSON.parse(feature.geometry); <add> var featureGeometry = typeof feature.geometry === 'string' ? JSON.parse(feature.geometry) : feature.geometry; <ide> var geom = featureGeometry.coordinates; <ide> var type = featureGeometry.type; <ide>
Java
apache-2.0
b6c46ecb46e1a27d8a6f66fd7bb0f97cd2b45110
0
AlejandroVera/ProjectTwitter,AlejandroVera/ProjectTwitter
/** * Sample Skeleton for "preferencias.fxml" Controller Class * You can copy and paste this code into your favorite IDE **/ package cliente; import interfacesComunes.Twitter_Account; import interfacesComunes.User; import java.io.File; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.RadioButton; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.input.ContextMenuEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.FileChooser; public class AjustesController extends Controller{ @FXML // fx:id="descripcion" private TextArea descripcion; // Value injected by FXMLLoader @FXML // fx:id="examinarPerfil" private Button examinarPerfil; // Value injected by FXMLLoader @FXML // fx:id="examinarFondo" private Button examinarFondo; // Value injected by FXMLLoader @FXML // fx:id="fondoURL" private TextField fondoURL; // Value injected by FXMLLoader @FXML // fx:id="imagenFondo" private AnchorPane imagenFondo; // Value injected by FXMLLoader @FXML // fx:id="imagenPerfilURL" private TextField imagenPerfilURL; // Value injected by FXMLLoader @FXML // fx:id="name" private TextField name; // Value injected by FXMLLoader @FXML // fx:id="proteccionCuenta" private RadioButton proteccionCuenta; // Value injected by FXMLLoader //En el postinitialice le tendrás que dar un valor private boolean protegida; // Handler for RadioButton[fx:id="proteccionCuenta"] onMouseClicked public void activarProteccion(MouseEvent event) { if (proteccionCuenta.isArmed()){ this.protegida=true; proteccionCuenta.setText("Activada");//En el postinitialice tendrás que cargar su estado } else{ this.protegida=false; proteccionCuenta.setText("Desactivada"); } } // Handler for Label[id="numeroDe"] onMouseClicked public void cerrar(MouseEvent event) { this.hideWindow(); } // Handler for Button[id="examinarFondo"] onMouseClicked public void examinarImagenFondo(ContextMenuEvent event) { //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Imágenes (*.jpg *.png)", "*.jpg", "*.png"); FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(extFilter); //Show open file dialog File file = fileChooser.showOpenDialog(null); //Guardar la imagen en el servidor y obtener la ruta String url = ClientTools.saveImage(new File(file.getPath())); fondoURL.setText(url); } // Handler for Button[fx:id="examinarPerfil"] onMouseClicked public void examinarImagenPerfil(MouseEvent event) { //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Imágenes (*.jpg *.png)", "*.jpg", "*.png"); FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(extFilter); //Show open file dialog File file = fileChooser.showOpenDialog(null); //Guardar la imagen en el servidor y obtener la ruta String url = ClientTools.saveImage(new File(file.getPath())); imagenPerfilURL.setText(url); } // Handler for Button[id="twittear"] onMouseClicked //TODO: falta completar algunas cosillas public void guardarAjustes(MouseEvent event) { Twitter_Account account = super.getTwitter().account(); User user = super.getTwitter().getSelf(); account.setProfile(name.getText(), "UNKNOWN", imagenPerfilURL.getText(), user.getLocation(), descripcion.getText()); account.setProfileColors(null); //Tendrás que meter el cambio de proteger/desprotegercuenta this.hideWindow(); } @Override // This method is called by the FXMLLoader when initialization is complete public void initialize(URL fxmlFileLocation, ResourceBundle resources) { assert descripcion != null : "fx:id=\"descripcion\" was not injected: check your FXML file 'preferencias.fxml'."; assert examinarFondo != null : "fx:id=\"examinarFondo\" was not injected: check your FXML file 'preferencias.fxml'."; assert examinarPerfil != null : "fx:id=\"examinarPerfil\" was not injected: check your FXML file 'preferencias.fxml'."; assert fondoURL != null : "fx:id=\"fondoURL\" was not injected: check your FXML file 'preferencias.fxml'."; assert imagenFondo != null : "fx:id=\"imagenFondo\" was not injected: check your FXML file 'preferencias.fxml'."; assert imagenPerfilURL != null : "fx:id=\"imagenPerfilURL\" was not injected: check your FXML file 'preferencias.fxml'."; assert name != null : "fx:id=\"name\" was not injected: check your FXML file 'preferencias.fxml'."; // initialize your logic here: all @FXML variables will have been injected } @Override public void postInitialize() { User user = super.getTwitter().getSelf(); fondoURL.setText(user.getProfileBackgroundImageUrl().toString()); imagenPerfilURL.setText(user.getProfileImageUrl().toString()); name.setText(user.getName()); descripcion.setText(user.getDescription()); } @Override protected AnchorPane getContainer() { // TODO Auto-generated method stub return null; } protected void showWindow(){ imagenFondo.setVisible(true); } protected void hideWindow(){ imagenFondo.setVisible(false); } }
src/cliente/AjustesController.java
/** * Sample Skeleton for "preferencias.fxml" Controller Class * You can copy and paste this code into your favorite IDE **/ package cliente; import interfacesComunes.Twitter_Account; import interfacesComunes.User; import java.io.File; import java.net.URL; import java.util.ResourceBundle; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.input.ContextMenuEvent; import javafx.scene.input.MouseEvent; import javafx.scene.layout.AnchorPane; import javafx.stage.FileChooser; public class AjustesController extends Controller{ @FXML // fx:id="descripcion" private TextArea descripcion; // Value injected by FXMLLoader @FXML // fx:id="examinarPerfil" private Button examinarPerfil; // Value injected by FXMLLoader @FXML // fx:id="examinarFondo" private Button examinarFondo; // Value injected by FXMLLoader @FXML // fx:id="fondoURL" private TextField fondoURL; // Value injected by FXMLLoader @FXML // fx:id="imagenFondo" private AnchorPane imagenFondo; // Value injected by FXMLLoader @FXML // fx:id="imagenPerfilURL" private TextField imagenPerfilURL; // Value injected by FXMLLoader @FXML // fx:id="name" private TextField name; // Value injected by FXMLLoader // Handler for Label[id="numeroDe"] onMouseClicked public void cerrar(MouseEvent event) { this.hideWindow(); } // Handler for Button[id="examinarFondo"] onMouseClicked public void examinarImagenFondo(ContextMenuEvent event) { //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Imágenes (*.jpg *.png)", "*.jpg", "*.png"); FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(extFilter); //Show open file dialog File file = fileChooser.showOpenDialog(null); //Guardar la imagen en el servidor y obtener la ruta String url = ClientTools.saveImage(new File(file.getPath())); fondoURL.setText(url); } // Handler for Button[fx:id="examinarPerfil"] onMouseClicked public void examinarImagenPerfil(MouseEvent event) { //Set extension filter FileChooser.ExtensionFilter extFilter = new FileChooser.ExtensionFilter("Imágenes (*.jpg *.png)", "*.jpg", "*.png"); FileChooser fileChooser = new FileChooser(); fileChooser.getExtensionFilters().add(extFilter); //Show open file dialog File file = fileChooser.showOpenDialog(null); //Guardar la imagen en el servidor y obtener la ruta String url = ClientTools.saveImage(new File(file.getPath())); imagenPerfilURL.setText(url); } // Handler for Button[id="twittear"] onMouseClicked //TODO: falta completar algunas cosillas public void guardarAjustes(MouseEvent event) { Twitter_Account account = super.getTwitter().account(); User user = super.getTwitter().getSelf(); account.setProfile(name.getText(), "UNKNOWN", imagenPerfilURL.getText(), user.getLocation(), descripcion.getText()); account.setProfileColors(null); this.hideWindow(); } @Override // This method is called by the FXMLLoader when initialization is complete public void initialize(URL fxmlFileLocation, ResourceBundle resources) { assert descripcion != null : "fx:id=\"descripcion\" was not injected: check your FXML file 'preferencias.fxml'."; assert examinarFondo != null : "fx:id=\"examinarFondo\" was not injected: check your FXML file 'preferencias.fxml'."; assert examinarPerfil != null : "fx:id=\"examinarPerfil\" was not injected: check your FXML file 'preferencias.fxml'."; assert fondoURL != null : "fx:id=\"fondoURL\" was not injected: check your FXML file 'preferencias.fxml'."; assert imagenFondo != null : "fx:id=\"imagenFondo\" was not injected: check your FXML file 'preferencias.fxml'."; assert imagenPerfilURL != null : "fx:id=\"imagenPerfilURL\" was not injected: check your FXML file 'preferencias.fxml'."; assert name != null : "fx:id=\"name\" was not injected: check your FXML file 'preferencias.fxml'."; // initialize your logic here: all @FXML variables will have been injected } @Override public void postInitialize() { User user = super.getTwitter().getSelf(); fondoURL.setText(user.getProfileBackgroundImageUrl().toString()); imagenPerfilURL.setText(user.getProfileImageUrl().toString()); name.setText(user.getName()); descripcion.setText(user.getDescription()); } @Override protected AnchorPane getContainer() { // TODO Auto-generated method stub return null; } protected void showWindow(){ imagenFondo.setVisible(true); } protected void hideWindow(){ imagenFondo.setVisible(false); } }
Boton para proteger/desproteger cuenta en Ajustes.
src/cliente/AjustesController.java
Boton para proteger/desproteger cuenta en Ajustes.
<ide><path>rc/cliente/AjustesController.java <ide> import java.util.ResourceBundle; <ide> import javafx.fxml.FXML; <ide> import javafx.scene.control.Button; <add>import javafx.scene.control.RadioButton; <ide> import javafx.scene.control.TextArea; <ide> import javafx.scene.control.TextField; <ide> import javafx.scene.input.ContextMenuEvent; <ide> <ide> @FXML // fx:id="name" <ide> private TextField name; // Value injected by FXMLLoader <add> <add> @FXML // fx:id="proteccionCuenta" <add> private RadioButton proteccionCuenta; // Value injected by FXMLLoader <add> <add> //En el postinitialice le tendrás que dar un valor <add> private boolean protegida; <ide> <ide> <add> // Handler for RadioButton[fx:id="proteccionCuenta"] onMouseClicked <add> public void activarProteccion(MouseEvent event) { <add> if (proteccionCuenta.isArmed()){ <add> this.protegida=true; <add> proteccionCuenta.setText("Activada");//En el postinitialice tendrás que cargar su estado <add> } <add> else{ <add> this.protegida=false; <add> proteccionCuenta.setText("Desactivada"); <add> } <add> <add> <add> } <add> <ide> // Handler for Label[id="numeroDe"] onMouseClicked <ide> public void cerrar(MouseEvent event) { <ide> this.hideWindow(); <ide> User user = super.getTwitter().getSelf(); <ide> account.setProfile(name.getText(), "UNKNOWN", imagenPerfilURL.getText(), user.getLocation(), descripcion.getText()); <ide> account.setProfileColors(null); <add> //Tendrás que meter el cambio de proteger/desprotegercuenta <ide> this.hideWindow(); <ide> } <ide>
JavaScript
mit
669d990482b90ddc5b27bc3a1597065b54a36984
0
vorg/pex,vorg/pex,szymonkaliski/pex,pex-gl/pex,szymonkaliski/pex,pex-gl/pex
define(['pex/sys/Platform', 'pex/sys/EjectaPolyfills'], function(Platform, EjectaPolyfills) { var requestAnimFrameFps = 60; if (Platform.isBrowser) { window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function */ callback, /* DOMElement */ element){ window.setTimeout(callback, 1000 / requestAnimFrameFps); }; })(); } var eventListeners = []; function fireEvent(eventType, event) { for(var i=0; i<eventListeners.length; i++) { if (eventListeners[i].eventType == eventType) { eventListeners[i].handler(event); } } } function registerEvents(canvas) { makeMouseDownHandler(canvas); makeMouseUpHandler(canvas); makeMouseDraggedHandler(canvas); makeMouseMovedHandler(canvas); makeScrollWheelHandler(canvas); makeTouchDownHandler(canvas); makeTouchUpHandler(canvas); makeTouchMoveHandler(canvas); makeKeyDownHandler(canvas); } function makeMouseDownHandler(canvas) { canvas.addEventListener('mousedown', function(e) { fireEvent('leftMouseDown', { x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio, y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); }) } function makeMouseUpHandler(canvas) { canvas.addEventListener('mouseup', function(e) { fireEvent('leftMouseUp', { x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio, y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }) }) } function makeMouseDraggedHandler(canvas) { var down = false; var px = 0; var py = 0; canvas.addEventListener('mousedown', function(e) { down = true; px = (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio; py = (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio; }); canvas.addEventListener('mouseup', function(e) { down = false; }); canvas.addEventListener('mousemove', function(e) { if (down) { var x = (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio; var y = (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio; fireEvent('mouseDragged', { x: x, y: y, dx: x - px, dy: y - py, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); px = x; py = y; } }) } function makeMouseMovedHandler(canvas) { canvas.addEventListener('mousemove', function(e) { fireEvent('mouseMoved', { x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio, y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); }) } function makeScrollWheelHandler(canvas) { var mousewheelevt = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel' document.addEventListener(mousewheelevt, function(e) { fireEvent('scrollWheel', { x: (e.offsetX || e.layerX) * window.devicePixelRatio, y: (e.offsetY || e.layerY) * window.devicePixelRatio, dy: e.wheelDelta/10 || -e.detail/10, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); }); } var lastTouch = null; function makeTouchDownHandler(canvas) { canvas.addEventListener('touchstart', function(e) { lastTouch = { clientX : (e.touches[0].clientX) * window.devicePixelRatio, clientY : (e.touches[0].clientY) * window.devicePixelRatio }; fireEvent('leftMouseDown', { x: (e.touches[0].clientX) * window.devicePixelRatio, y: (e.touches[0].clientY) * window.devicePixelRatio, option: false, shift: false, control: false }); }) } function makeTouchUpHandler(canvas) { canvas.addEventListener('touchend', function(e) { fireEvent('leftMouseUp', { x: lastTouch ? lastTouch.clientX : 0, y: lastTouch ? lastTouch.clientY : 0, option: false, shift: false, control: false }); lastTouch = null; }) } function makeTouchMoveHandler(canvas) { canvas.addEventListener('touchmove', function(e) { lastTouch = { clientX : (e.touches[0].clientX) * window.devicePixelRatio, clientY : (e.touches[0].clientY) * window.devicePixelRatio }; fireEvent('mouseDragged', { x: (e.touches[0].clientX) * window.devicePixelRatio, y: (e.touches[0].clientY) * window.devicePixelRatio, option: false, shift: false, control: false }); }) } function makeKeyDownHandler(canvas) { var timeout = 0; window.addEventListener('keydown', function(e) { timeout = setTimeout(function() { fireEvent('keyDown', { str: '', keyCode: e.keyCode, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }, 1); }) }) window.addEventListener('keypress', function(e) { if (timeout) { clearTimeout(timeout); timeout = 0; } fireEvent('keyDown', { str: String.fromCharCode(e.charCode), keyCode: e.keyCode, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); }) } function simpleWindow(obj) { var canvas = obj.settings.canvas; if (obj.settings.fullscreen) { obj.settings.width = window.innerWidth; obj.settings.height = window.innerHeight; } if (!canvas) { canvas = document.getElementById('canvas'); } else if (obj.settings.width && obj.setttings.height) { canvas.width = obj.settings.width; canvas.height = obj.settings.height; } else { obj.settings.width = canvas.width; obj.settings.height = canvas.height; } if (!canvas) { canvas = document.createElement('canvas'); canvas.width = obj.settings.width; canvas.height = obj.settings.height; } if (Platform.isEjecta && (window.devicePixelRatio == 2)) { canvas.width = obj.settings.width * 2; canvas.height = obj.settings.height * 2; canvas.style.width = obj.settings.width; canvas.style.height = obj.settings.height; obj.settings.width *= 2; obj.settings.height *= 2; } obj.width = obj.settings.width; obj.height = obj.settings.height; obj.canvas = canvas; canvas.style.backgroundColor = '#000000'; function go() { if (obj.stencil === undefined) obj.stencil = false; if (obj.settings.fullscreen) { document.body.style.margin = '0'; document.body.style.padding = '0'; document.body.style.overflow = 'hidden'; } var gl = null; var ctx = null; if (obj.settings.type == '3d') { try { gl = canvas.getContext('experimental-webgl'); //, {antialias: true, premultipliedAlpha : true, stencil: obj.settings.stencil} } catch(err){ console.error(err.message); return; } } else if (obj.settings.type == '2d') { ctx = canvas.getContext('2d'); } obj.framerate = function(fps) { requestAnimFrameFps = fps; } obj.on = function(eventType, handler) { eventListeners.push({eventType:eventType, handler:handler}); } registerEvents(canvas); obj.dispose = function() { obj.__disposed = true; } obj.gl = gl; obj.ctx = ctx; obj.init(); function drawloop() { if (!obj.__disposed) { obj.draw(); requestAnimFrame(drawloop); } } requestAnimFrame(drawloop); } if (!canvas.parentNode) { if (document.body) { document.body.appendChild(canvas); go(); } else { window.addEventListener('load', function() { document.body.appendChild(canvas); go(); }, false); } } else { go(); } return obj; } var BrowserWindow = { simpleWindow : simpleWindow } return BrowserWindow; });
src/pex/sys/BrowserWindow.js
define(['pex/sys/Platform', 'pex/sys/EjectaPolyfills'], function(Platform, EjectaPolyfills) { var requestAnimFrameFps = 60; if (Platform.isBrowser) { window.requestAnimFrame = (function() { return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(/* function */ callback, /* DOMElement */ element){ window.setTimeout(callback, 1000 / requestAnimFrameFps); }; })(); } var eventListeners = []; function fireEvent(eventType, event) { for(var i=0; i<eventListeners.length; i++) { if (eventListeners[i].eventType == eventType) { eventListeners[i].handler(event); } } } function registerEvents(canvas) { makeMouseDownHandler(canvas); makeMouseUpHandler(canvas); makeMouseDraggedHandler(canvas); makeMouseMovedHandler(canvas); makeScrollWheelHandler(canvas); makeTouchDownHandler(canvas); makeTouchUpHandler(canvas); makeTouchMoveHandler(canvas); makeKeyDownHandler(canvas); } function makeMouseDownHandler(canvas) { canvas.addEventListener('mousedown', function(e) { fireEvent('leftMouseDown', { x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio, y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); }) } function makeMouseUpHandler(canvas) { canvas.addEventListener('mouseup', function(e) { fireEvent('leftMouseUp', { x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio, y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }) }) } function makeMouseDraggedHandler(canvas) { var down = false; var px = 0; var py = 0; canvas.addEventListener('mousedown', function(e) { down = true; px = (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio; py = (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio; }); canvas.addEventListener('mouseup', function(e) { down = false; }); canvas.addEventListener('mousemove', function(e) { if (down) { var x = (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio; var y = (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio; fireEvent('mouseDragged', { x: x, y: y, dx: x - px, dy: y - py, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); px = x; py = y; } }) } function makeMouseMovedHandler(canvas) { canvas.addEventListener('mousemove', function(e) { fireEvent('mouseMoved', { x: (e.offsetX || e.layerX || e.clientX - e.target.offsetLeft) * window.devicePixelRatio, y: (e.offsetY || e.layerY || e.clientY - e.target.offsetTop) * window.devicePixelRatio, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); }) } function makeScrollWheelHandler(canvas) { var mousewheelevt = (/Firefox/i.test(navigator.userAgent))? 'DOMMouseScroll' : 'mousewheel' document.addEventListener(mousewheelevt, function(e) { fireEvent('scrollWheel', { x: (e.offsetX || e.layerX) * window.devicePixelRatio, y: (e.offsetY || e.layerY) * window.devicePixelRatio, dy: e.wheelDelta/10 || -e.detail/10, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); }); } var lastTouch = null; function makeTouchDownHandler(canvas) { canvas.addEventListener('touchstart', function(e) { lastTouch = { clientX : (e.touches[0].clientX) * window.devicePixelRatio, clientY : (e.touches[0].clientY) * window.devicePixelRatio }; fireEvent('leftMouseDown', { x: (e.touches[0].clientX) * window.devicePixelRatio, y: (e.touches[0].clientY) * window.devicePixelRatio, option: false, shift: false, control: false }); }) } function makeTouchUpHandler(canvas) { canvas.addEventListener('touchend', function(e) { fireEvent('leftMouseUp', { x: lastTouch ? lastTouch.clientX : 0, y: lastTouch ? lastTouch.clientY : 0, option: false, shift: false, control: false }); lastTouch = null; }) } function makeTouchMoveHandler(canvas) { canvas.addEventListener('touchmove', function(e) { lastTouch = { clientX : (e.touches[0].clientX) * window.devicePixelRatio, clientY : (e.touches[0].clientY) * window.devicePixelRatio }; fireEvent('mouseDragged', { x: (e.touches[0].clientX) * window.devicePixelRatio, y: (e.touches[0].clientY) * window.devicePixelRatio, option: false, shift: false, control: false }); }) } function makeKeyDownHandler(canvas) { var timeout = 0; window.addEventListener('keydown', function(e) { timeout = setTimeout(function() { fireEvent('keyDown', { str: '', keyCode: e.keyCode, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }, 1); }) }) window.addEventListener('keypress', function(e) { if (timeout) { clearTimeout(timeout); timeout = 0; } fireEvent('keyDown', { str: String.fromCharCode(e.charCode), keyCode: e.keyCode, option: e.altKey, shift: e.shiftKey, control: e.ctrlKey }); }) } function simpleWindow(obj) { var canvas = obj.settings.canvas; if (obj.settings.fullscreen) { obj.settings.width = window.innerWidth; obj.settings.height = window.innerHeight; } if (!canvas) { canvas = document.getElementById('canvas'); if (canvas) { obj.settings.width = canvas.width; obj.settings.height = canvas.height; } } if (!canvas) { canvas = document.createElement('canvas'); canvas.width = obj.settings.width; canvas.height = obj.settings.height; } if (Platform.isEjecta && (window.devicePixelRatio == 2)) { canvas.width = obj.settings.width * 2; canvas.height = obj.settings.height * 2; canvas.style.width = obj.settings.width; canvas.style.height = obj.settings.height; obj.settings.width *= 2; obj.settings.height *= 2; } obj.width = obj.settings.width; obj.height = obj.settings.height; obj.canvas = canvas; canvas.style.backgroundColor = '#000000'; function go() { if (obj.stencil === undefined) obj.stencil = false; if (obj.settings.fullscreen) { document.body.style.margin = '0'; document.body.style.padding = '0'; document.body.style.overflow = 'hidden'; } var gl = null; var ctx = null; if (obj.settings.type == '3d') { try { gl = canvas.getContext('experimental-webgl'); //, {antialias: true, premultipliedAlpha : true, stencil: obj.settings.stencil} } catch(err){ console.error(err.message); return; } } else if (obj.settings.type == '2d') { ctx = canvas.getContext('2d'); } obj.framerate = function(fps) { requestAnimFrameFps = fps; } obj.on = function(eventType, handler) { eventListeners.push({eventType:eventType, handler:handler}); } registerEvents(canvas); obj.dispose = function() { obj.__disposed = true; } obj.gl = gl; obj.ctx = ctx; obj.init(); function drawloop() { if (!obj.__disposed) { obj.draw(); requestAnimFrame(drawloop); } } requestAnimFrame(drawloop); } if (!canvas.parentNode) { if (document.body) { document.body.appendChild(canvas); go(); } else { window.addEventListener('load', function() { document.body.appendChild(canvas); go(); }, false); } } else { go(); } return obj; } var BrowserWindow = { simpleWindow : simpleWindow } return BrowserWindow; });
Don't change existing canvas size in BrowserWindow
src/pex/sys/BrowserWindow.js
Don't change existing canvas size in BrowserWindow
<ide><path>rc/pex/sys/BrowserWindow.js <ide> <ide> if (!canvas) { <ide> canvas = document.getElementById('canvas'); <del> if (canvas) { <del> obj.settings.width = canvas.width; <del> obj.settings.height = canvas.height; <del> } <add> } <add> else if (obj.settings.width && obj.setttings.height) { <add> canvas.width = obj.settings.width; <add> canvas.height = obj.settings.height; <add> } <add> else { <add> obj.settings.width = canvas.width; <add> obj.settings.height = canvas.height; <ide> } <ide> <ide> if (!canvas) {
JavaScript
cc0-1.0
9a33e0e4f9eef06be7a9d7f19081c83da9ba7d0a
0
RUGSoftEng/Team-5,RUGSoftEng/Team-5
/* file: form.js * authors: H. Bouakaz, S. de Vliet, S. de Jong & E. Werkema * date: 19/3/2016 * version 1.1 * * Description: */ define(['app/config', 'app/database', 'jquery', 'bootstrap', 'parsley', 'app/selectLanguage', 'app/selectSubject', 'app/date'], function (config, db, $, bootstrap, parsley, language, subject, date) { var numberOfFormItems = 0; var formItemId = 0; // Function for removing elements from the form function remove_element(element) { if (numberOfFormItems > 1) { element.parents("tr").remove(); numberOfFormItems--; } } // Function for adding elements to the form function add_element() { var newElement = $('#item-layout').clone(true).appendTo("#items table").removeAttr("id"); newElement.html(giveId(newElement.html(), formItemId)); newElement.html(giveRequired(newElement.html())); newElement.on("click", ".remove", function() { remove_element($(this)); }); numberOfFormItems++; formItemId++; } // Auxiliary replace functions function giveId(string, formItemId) { return string.replace(/{i}/g, formItemId); } function giveRequired(string) { return string.replace(/{required}/g, 'required=""'); } // Auxiliary form function function getFormVal(formType, formName) { return $('#createForm').find(formType + '[name="' + formName + '"]').val(); } // Add the first element add_element(); $(".add").click(function(add) { add_element(); return false; }); $('#items input[type="text"]:last').on('keydown', function(e) { if (e.keyCode == config.key("TAB")) { add_element(); } }); // Check in the database if the name of the dataset already exists window.Parsley.addValidator('datasetName', { validateString: function(value, requirement) { var result = db.getQuery("getDatasetByName", [value]); return result.length == 0; }, messages: { en: 'This name is already used for another dataset.' } }); // Script for evaluating the input of the upload form $(function () { $('#createForm').parsley().on('field:validated', function() { // Initiate form error and success handling var ok = $('.parsley-error').length === 0; $('.bs-callout-info').toggleClass('hidden', !ok); $('.bs-callout-warning').toggleClass('hidden', ok); }) .on('form:submit', function() { return false; // Don't submit form }) .on('form:success', function() { // Save data into the database var name = getFormVal("input", "name"); var language = getFormVal("select", "language"); var subject = getFormVal("select", "subject"); var currentdate = new Date(); db.executeQuery("addDataset", [0, name, language, subject, 0, 0, date.formatDate(currentdate), date.formatDate(currentdate)]); var id = db.lastInsertRowId("tbldatasets", "dataset_id"); // Save all items in the dataset for (i = 0; i<=formItemId; i++) { var question = $("#items input[name='question"+i+"']").val(); var answer = $("#items input[name='answer"+i+"']").val(); var hint = $("#items input[name='hint"+i+"']").val(); hint = (hint==="undefined") ? "" : hint; db.executeQuery('addDatasetItem' , [id, question, answer, hint]); } db.close(); window.location = 'index.html'; }); }); });
app/create.js
/* file: form.js * authors: H. Bouakaz, S. de Vliet, S. de Jong & E. Werkema * date: 19/3/2016 * version 1.1 * * Description: */ define(['app/config', 'app/database', 'jquery', 'bootstrap', 'parsley', 'app/selectLanguage', 'app/selectSubject', 'app/date'], function (config, db, $, bootstrap, parsley, language, subject, date) { var numberOfFormItems = 0; var formItemId = 0; // Function for removing elements from the form function remove_element(element) { if (numberOfFormItems > 1) { element.parents("tr").remove(); numberOfFormItems--; } } // Auxiliary replace functions function giveId(string, formItemId) { return string.replace(/{i}/g, formItemId); } function giveRequired(string) { return string.replace(/{required}/g, 'required=""'); } // Function for adding elements to the form function add_element() { var newElement = $('#item-layout').clone(true).appendTo("#items table").removeAttr("id"); newElement.html(giveId(newElement.html(), formItemId)); newElement.html(giveRequired(newElement.html())); newElement.on("click", ".remove", function() { remove_element($(this)); }); numberOfFormItems++; formItemId++; } // Add the first element add_element(); $(".add").click(function(add) { add_element(); return false; }); $('#items input[type="text"]:last').on('keydown', function(e) { if (e.keyCode == config.key("TAB")) { add_element(); } }); // Check in the database if the name of the dataset already exists window.Parsley.addValidator('datasetName', { validateString: function(value, requirement) { var result = db.getQuery("getDatasetByName", [value]); return result.length == 0; }, messages: { en: 'This name is already used for another dataset.' } }); // Script for evaluating the input of the upload form $(function () { $('#createForm').parsley().on('field:validated', function() { // Initiate form error and success handling var ok = $('.parsley-error').length === 0; $('.bs-callout-info').toggleClass('hidden', !ok); $('.bs-callout-warning').toggleClass('hidden', ok); }) .on('form:submit', function() { return false; // Don't submit form }) .on('form:success', function() { // Save data into the database var name = $('#createForm').find('input[name="name"]').val(); var language = $('#createForm').find('select[name="language"]').val(); var subject = $('#createForm').find('select[name="subject"]').val(); var currentdate = new Date(); db.executeQuery("addDataset", [0, name, language, subject, 0, 0, date.formatDate(currentdate), date.formatDate(currentdate)]); var id = db.lastInsertRowId("tbldatasets", "dataset_id"); // Save all items in the dataset for (i = 0; i<=formItemId; i++) { var question = $("#items input[name='question"+i+"']").val(); var answer = $("#items input[name='answer"+i+"']").val(); var hint = $("#items input[name='hint"+i+"']").val(); hint = (hint==="undefined") ? "" : hint; db.executeQuery('addDatasetItem' , [id, question, answer, hint]); } db.close(); window.location = 'index.html'; }); }); });
Put form value reading in own function
app/create.js
Put form value reading in own function
<ide><path>pp/create.js <ide> } <ide> } <ide> <del> // Auxiliary replace functions <del> function giveId(string, formItemId) { <del> return string.replace(/{i}/g, formItemId); <del> } <del> function giveRequired(string) { <del> return string.replace(/{required}/g, 'required=""'); <del> } <del> <ide> // Function for adding elements to the form <ide> function add_element() { <ide> var newElement = $('#item-layout').clone(true).appendTo("#items table").removeAttr("id"); <ide> numberOfFormItems++; <ide> formItemId++; <ide> } <add> <add> // Auxiliary replace functions <add> function giveId(string, formItemId) { <add> return string.replace(/{i}/g, formItemId); <add> } <add> function giveRequired(string) { <add> return string.replace(/{required}/g, 'required=""'); <add> } <add> <add> // Auxiliary form function <add> function getFormVal(formType, formName) { <add> return $('#createForm').find(formType + '[name="' + formName + '"]').val(); <add> } <ide> <ide> // Add the first element <ide> add_element(); <ide> }) <ide> .on('form:success', function() { <ide> // Save data into the database <del> var name = $('#createForm').find('input[name="name"]').val(); <del> var language = $('#createForm').find('select[name="language"]').val(); <del> var subject = $('#createForm').find('select[name="subject"]').val(); <add> var name = getFormVal("input", "name"); <add> var language = getFormVal("select", "language"); <add> var subject = getFormVal("select", "subject"); <ide> var currentdate = new Date(); <ide> <ide> db.executeQuery("addDataset", [0, name, language, subject, 0, 0, date.formatDate(currentdate), date.formatDate(currentdate)]);
Java
mit
8d8fa5665256c793f7a2627b19af5052a8f08aa0
0
blackneck/react-native-webrtc,blackneck/react-native-webrtc,blackneck/react-native-webrtc
package com.oney.WebRTCModule; import android.content.Intent; import android.support.v4.content.LocalBroadcastManager; import android.util.Log; import org.webrtc.VideoCapturerAndroid; class CameraEventsHandler implements VideoCapturerAndroid.CameraEventsHandler { private final static String TAG = WebRTCModule.TAG; private void sendMessage(int cameraId) { Log.d("sender", "Broadcasting message"); if(WebRTCModule.staticContext != null) { Intent intent = new Intent("camera_id_detected"); // You can also include some extra data. Log.v(TAG, "SENT CAMERA ID: " + cameraId); intent.putExtra("message", cameraId); LocalBroadcastManager.getInstance(WebRTCModule.staticContext).sendBroadcast(intent); } } // Camera error handler - invoked when camera can not be opened // or any camera exception happens on camera thread. @Override public void onCameraError(String errorDescription) { Log.d(TAG, String.format("CameraEventsHandler.onCameraError: errorDescription=%s", errorDescription)); } // Invoked when camera stops receiving frames @Override public void onCameraFreezed(String errorDescription) { Log.d(TAG, String.format("CameraEventsHandler.onCameraFreezed: errorDescription=%s", errorDescription)); } // Callback invoked when camera is opening. @Override public void onCameraOpening(int cameraId) { Log.d(TAG, String.format("CameraEventsHandler.onCameraOpening: cameraId=%s", cameraId)); sendMessage(cameraId); } // Callback invoked when first camera frame is available after camera is opened. @Override public void onFirstFrameAvailable() { Log.d(TAG, "CameraEventsHandler.onFirstFrameAvailable"); } // Callback invoked when camera closed. @Override public void onCameraClosed() { Log.d(TAG, "CameraEventsHandler.onFirstFrameAvailable"); } }
android/src/main/java/com/oney/WebRTCModule/CameraEventsHandler.java
package com.oney.WebRTCModule; import android.util.Log; import org.webrtc.VideoCapturerAndroid; class CameraEventsHandler implements VideoCapturerAndroid.CameraEventsHandler { private final static String TAG = WebRTCModule.TAG; private void sendMessage(int cameraId) { Log.d("sender", "Broadcasting message"); if(WebRTCModule.staticContext != null) { Intent intent = new Intent("camera_id_detected"); // You can also include some extra data. Log.v(TAG, "SENT CAMERA ID: " + cameraId); intent.putExtra("message", cameraId); LocalBroadcastManager.getInstance(staticContext).sendBroadcast(intent); } } // Camera error handler - invoked when camera can not be opened // or any camera exception happens on camera thread. @Override public void onCameraError(String errorDescription) { Log.d(TAG, String.format("CameraEventsHandler.onCameraError: errorDescription=%s", errorDescription)); } // Invoked when camera stops receiving frames @Override public void onCameraFreezed(String errorDescription) { Log.d(TAG, String.format("CameraEventsHandler.onCameraFreezed: errorDescription=%s", errorDescription)); } // Callback invoked when camera is opening. @Override public void onCameraOpening(int cameraId) { Log.d(TAG, String.format("CameraEventsHandler.onCameraOpening: cameraId=%s", cameraId)); sendMessage(cameraId); } // Callback invoked when first camera frame is available after camera is opened. @Override public void onFirstFrameAvailable() { Log.d(TAG, "CameraEventsHandler.onFirstFrameAvailable"); } // Callback invoked when camera closed. @Override public void onCameraClosed() { Log.d(TAG, "CameraEventsHandler.onFirstFrameAvailable"); } }
Android fix
android/src/main/java/com/oney/WebRTCModule/CameraEventsHandler.java
Android fix
<ide><path>ndroid/src/main/java/com/oney/WebRTCModule/CameraEventsHandler.java <ide> package com.oney.WebRTCModule; <ide> <add>import android.content.Intent; <add>import android.support.v4.content.LocalBroadcastManager; <ide> import android.util.Log; <ide> <ide> import org.webrtc.VideoCapturerAndroid; <ide> // You can also include some extra data. <ide> Log.v(TAG, "SENT CAMERA ID: " + cameraId); <ide> intent.putExtra("message", cameraId); <del> LocalBroadcastManager.getInstance(staticContext).sendBroadcast(intent); <add> LocalBroadcastManager.getInstance(WebRTCModule.staticContext).sendBroadcast(intent); <ide> } <ide> } <ide>
Java
apache-2.0
65e5b15dd3b4df5bc80ca11398bde7f675db895f
0
vibur/vibur-dbcp
/** * Copyright 2013 Simeon Malchev * * 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.vibur.dbcp.proxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vibur.dbcp.ViburConfig; import org.vibur.dbcp.ViburDBCPException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import static org.vibur.dbcp.ViburConfig.SQLSTATE_OBJECT_CLOSED_ERROR; import static org.vibur.dbcp.ViburConfig.SQLSTATE_WRAPPER_ERROR; import static org.vibur.dbcp.util.ViburUtils.getPoolName; /** * @author Simeon Malchev * @param <T> the type of the object that we are dynamically proxy-ing */ abstract class AbstractInvocationHandler<T> implements TargetInvoker { private static final Logger logger = LoggerFactory.getLogger(AbstractInvocationHandler.class); /** The real (raw) object that we are dynamically proxy-ing. * For example, the underlying JDBC Connection, the underlying JDBC Statement, etc. */ private final T target; private final ViburConfig config; private final ExceptionCollector exceptionCollector; private final AtomicBoolean closed = new AtomicBoolean(false); AbstractInvocationHandler(T target, ViburConfig config, ExceptionCollector exceptionCollector) { assert target != null; assert exceptionCollector != null; this.target = target; this.config = config; this.exceptionCollector = exceptionCollector; } @Override @SuppressWarnings("unchecked") public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (logger.isTraceEnabled()) logger.trace("Calling {} with args {} on {}", method, args, target); String methodName = method.getName(); if (methodName == "equals") // comparing with == as the Method names are interned Strings return proxy == args[0]; if (methodName == "hashCode") return System.identityHashCode(proxy); if (methodName == "toString") return "Proxy for: " + target; if (methodName == "unwrap") return unwrap((Class<T>) args[0]); if (methodName == "isWrapperFor") return isWrapperFor((Class<?>) args[0]); try { return doInvoke((T) proxy, method, args); } catch (ViburDBCPException e) { logger.error("Pool {}, the invocation of {} with args {} on {} threw:", getPoolName(config), method, Arrays.toString(args), target, e); Throwable cause = e.getCause(); if (cause instanceof SQLException) throw cause; // throw the original SQLException which have caused the ViburDBCPException throw e; // not expected to happen } } /** * By default, forwards the call to the original method of the proxied object. This method will be overridden * in the {@code AbstractInvocationHandler} subclasses, and will be the place to implement the specific to these * subclasses logic for methods invocation handling. * * @param proxy see {@link java.lang.reflect.InvocationHandler#invoke(Object, Method, Object[])} * @param method as above * @param args as above * @return as above * @throws Throwable as above */ Object doInvoke(T proxy, Method method, Object[] args) throws Throwable { return targetInvoke(method, args); } @Override public final Object targetInvoke(Method method, Object[] args) throws Throwable { try { return method.invoke(target, args); // the real method call on the real underlying (proxied) object } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause == null) cause = e; logInvokeFailure(method, args, cause); exceptionCollector.addException(cause); if (cause instanceof SQLException || cause instanceof RuntimeException || cause instanceof Error) throw cause; throw new ViburDBCPException(cause); // not expected to happen } } void logInvokeFailure(Method method, Object[] args, Throwable t) { if (logger.isDebugEnabled()) logger.debug("Pool {}, the invocation of {} with args {} on {} threw:", getPoolName(config), method, Arrays.toString(args), target, t); } /** * Logically closes this invocation handler. Returns true only once when the handler state transitions * from open to close. */ boolean close() { return !closed.getAndSet(true); } boolean isClosed() { return closed.get(); } void ensureNotClosed() throws SQLException { if (isClosed()) throw new SQLException(target.getClass().getName() + " is closed.", SQLSTATE_OBJECT_CLOSED_ERROR); } ExceptionCollector getExceptionCollector() { return exceptionCollector; } T getTarget() { return target; } private T unwrap(Class<T> iface) throws SQLException { if (isWrapperFor(iface)) return target; throw new SQLException("not a wrapper for " + iface, SQLSTATE_WRAPPER_ERROR); } private boolean isWrapperFor(Class<?> iface) { return iface.isInstance(target); } }
src/main/java/org/vibur/dbcp/proxy/AbstractInvocationHandler.java
/** * Copyright 2013 Simeon Malchev * * 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.vibur.dbcp.proxy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.vibur.dbcp.ViburConfig; import org.vibur.dbcp.ViburDBCPException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.SQLException; import java.util.Arrays; import java.util.concurrent.atomic.AtomicBoolean; import static org.vibur.dbcp.ViburConfig.SQLSTATE_OBJECT_CLOSED_ERROR; import static org.vibur.dbcp.ViburConfig.SQLSTATE_WRAPPER_ERROR; import static org.vibur.dbcp.util.ViburUtils.getPoolName; /** * @author Simeon Malchev * @param <T> the type of the object that we are dynamically proxy-ing */ abstract class AbstractInvocationHandler<T> implements TargetInvoker { private static final Logger logger = LoggerFactory.getLogger(AbstractInvocationHandler.class); /** The real (raw) object that we are dynamically proxy-ing. * For example, the underlying JDBC Connection, the underlying JDBC Statement, etc. */ private final T target; private final ViburConfig config; private final ExceptionCollector exceptionCollector; private final AtomicBoolean closed = new AtomicBoolean(false); AbstractInvocationHandler(T target, ViburConfig config, ExceptionCollector exceptionCollector) { assert target != null; assert exceptionCollector != null; this.target = target; this.config = config; this.exceptionCollector = exceptionCollector; } @Override @SuppressWarnings("unchecked") public final Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (logger.isTraceEnabled()) logger.trace("Calling {} with args {} on {}", method, args, target); String methodName = method.getName(); if (methodName == "equals") // comparing with == as the Method names are interned Strings return proxy == args[0]; if (methodName == "hashCode") return System.identityHashCode(proxy); if (methodName == "toString") return "Proxy for: " + target; if (methodName == "unwrap") return unwrap((Class<T>) args[0]); if (methodName == "isWrapperFor") return isWrapperFor((Class<?>) args[0]); try { return doInvoke((T) proxy, method, args); } catch (ViburDBCPException e) { logger.error("Pool {}, the invocation of {} with args {} on {} threw:", getPoolName(config), method, Arrays.toString(args), target, e); Throwable cause = e.getCause(); if (cause instanceof SQLException) throw cause; // throw the original SQLException which have caused the ViburDBCPException throw e; // not expected to happen } } /** * By default, forwards the call to the original method of the proxied object. This method will be overridden * in the {@code AbstractInvocationHandler} subclasses, and will be the place to implement the specific to these * subclasses logic for methods invocation handling. * * @param proxy see {@link java.lang.reflect.InvocationHandler#invoke(Object, Method, Object[])} * @param method as above * @param args as above * @return as above * @throws Throwable as above */ Object doInvoke(T proxy, Method method, Object[] args) throws Throwable { return targetInvoke(method, args); } @Override public final Object targetInvoke(Method method, Object[] args) throws Throwable { try { return method.invoke(target, args); // the real method call on the real underlying (proxied) object } catch (InvocationTargetException e) { Throwable cause = e.getCause(); if (cause == null) cause = e; logInvokeFailure(method, args, cause); exceptionCollector.addException(cause); if (cause instanceof SQLException || cause instanceof RuntimeException || cause instanceof Error) throw cause; throw new ViburDBCPException(cause); // not expected to happen } } void logInvokeFailure(Method method, Object[] args, Throwable t) { if (logger.isDebugEnabled()) logger.debug("Pool {}, the invocation of {} with args {} on {} threw:", getPoolName(config), method, Arrays.toString(args), target, t); } boolean close() { return !closed.getAndSet(true); } boolean isClosed() { return closed.get(); } void ensureNotClosed() throws SQLException { if (isClosed()) throw new SQLException(target.getClass().getName() + " is closed.", SQLSTATE_OBJECT_CLOSED_ERROR); } ExceptionCollector getExceptionCollector() { return exceptionCollector; } T getTarget() { return target; } private T unwrap(Class<T> iface) throws SQLException { if (isWrapperFor(iface)) return target; throw new SQLException("not a wrapper for " + iface, SQLSTATE_WRAPPER_ERROR); } private boolean isWrapperFor(Class<?> iface) { return iface.isInstance(target); } }
comment
src/main/java/org/vibur/dbcp/proxy/AbstractInvocationHandler.java
comment
<ide><path>rc/main/java/org/vibur/dbcp/proxy/AbstractInvocationHandler.java <ide> getPoolName(config), method, Arrays.toString(args), target, t); <ide> } <ide> <add> /** <add> * Logically closes this invocation handler. Returns true only once when the handler state transitions <add> * from open to close. <add> */ <ide> boolean close() { <ide> return !closed.getAndSet(true); <ide> }
Java
agpl-3.0
f1ad1568d3b2dab56919ee82f852ff7cee723da5
0
Nivocer/webenq,Nivocer/webenq,Nivocer/webenq,Nivocer/webenq
package it.bisi.report.jasper; import it.bisi.Utils; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.data.category.CategoryDataset; public class MyStandardCategoryItemLabelGenerator extends StandardCategoryItemLabelGenerator { static int i = 0; public String generateLabel(CategoryDataset dataset, int series,int category) { String result = null; String label = (String) Utils.alPercentages.get(i); //@todo use DecimalFormat; if ( ExecuteReport.prop.get("Report_Label_Format").equals(",") ) label = label.replace('.', ','); i++; return label + "%"; } }
java/src/bisiLibJasperSrc/it/bisi/report/jasper/MyStandardCategoryItemLabelGenerator.java
package it.bisi.report.jasper; import it.bisi.Utils; import org.jfree.chart.labels.StandardCategoryItemLabelGenerator; import org.jfree.data.category.CategoryDataset; public class MyStandardCategoryItemLabelGenerator extends StandardCategoryItemLabelGenerator { static int i = 0; public String generateLabel(CategoryDataset dataset, int series,int category) { String result = null; String label = (String) Utils.alPercentages.get(i); if ( ExecuteReport.prop.get("Report_Label_Format").equals(",") ) label = label.replace('.', ','); i++; return label + "%"; } }
[5217] add comment to use decimalformat in stead of some custom code
java/src/bisiLibJasperSrc/it/bisi/report/jasper/MyStandardCategoryItemLabelGenerator.java
[5217] add comment to use decimalformat in stead of some custom code
<ide><path>ava/src/bisiLibJasperSrc/it/bisi/report/jasper/MyStandardCategoryItemLabelGenerator.java <ide> { <ide> String result = null; <ide> String label = (String) Utils.alPercentages.get(i); <add> //@todo use DecimalFormat; <ide> if ( ExecuteReport.prop.get("Report_Label_Format").equals(",") ) <ide> label = label.replace('.', ','); <ide>
JavaScript
mit
d4a979b635d273c7c984716d7edef68d078fc948
0
KleeGroup/front-end-spa,KleeGroup/front-end-spa,pierr/front-end-spa,pierr/front-end-spa
var Hapi = require('hapi'); ///var Types = require('hapi').Types; module.exports = [{ method: 'GET', path: '/reference', config: { handler: getRefs } }, { method: 'GET', path: '/vm', config: { handler: getVms // query: { // name: Types.String() // } } }, { method: 'GET', path: '/vm/{id}', config: { handler: getVm } }, { method: 'POST', path: '/vm', config: { handler: addVm, /*validate: { payload: { name: Hapi.types.String().required().min(3) } }*/ } }, { method: 'PUT', path: '/vm/{id}', config: { handler: updateVm } },{ method: 'DELETE', path: '/vm/{id}', config: { handler: deleteVm } }]; var references = [{ id: 1, name: 'Linux', translationKey: 'linux' }, { id: 2, name: 'Windows', translationKey: 'windows' }]; var vms = [{ id: 0, name: 'VM1', nbCpu: 2, memory: 1000, diskTypeId: 1, diskCapacity: 300, users: undefined, osId: 3 }, { id: 1, name: 'VM2', nbCpu: 4, memory: 2000, diskTypeId: 1, diskCapacity: 300, users: undefined, osId: 1 }]; function getRefs(request, reply) { reply(references); } function getVms(request, reply) { if (request.query.name) { reply(vms); } else { reply(vms); } } function getVm(request, reply) { reply(vms[request.params.id]); } function addVm(request, reply) { var vm = { id: vms[vms.length - 1].id + 1, name: request.payload.name, nbCpu: 4, memory: 2000, diskTypeId: 1, diskCapacity: 300, users: undefined, osId: 1 }; vms.push(vm); reply(vm).code(201); } function updateVm(request, reply) { console.log('Update VM', request, reply); //vms[vms.request.payload.id] = request.payload; //reply(request.payload).code(200); //error response reply({ errors : [{fieldName: "memory", message: "la memoire est insuffisante."},{fieldName:"" , message: "erreur globale de la VM."}] }).code(501); } function deleteVm(request,reply){ console.log('delete VM', request.params.id); reply(); }
example/api/routes.js
var Hapi = require('hapi'); ///var Types = require('hapi').Types; module.exports = [{ method: 'GET', path: '/reference', config: { handler: getRefs } }, { method: 'GET', path: '/vm', config: { handler: getVms // query: { // name: Types.String() // } } }, { method: 'GET', path: '/vm/{id}', config: { handler: getVm } }, { method: 'POST', path: '/vm', config: { handler: addVm, /*validate: { payload: { name: Hapi.types.String().required().min(3) } }*/ } }, { method: 'PUT', path: '/vm', config: { handler: updateVm } },{ method: 'DELETE', path: '/vm/{id}', config: { handler: deleteVm } }]; var references = [{ id: 1, name: 'Linux', translationKey: 'linux' }, { id: 2, name: 'Windows', translationKey: 'windows' }]; var vms = [{ id: 0, name: 'VM1', nbCpu: 2, memory: 1000, diskTypeId: 1, diskCapacity: 300, users: undefined, osId: 3 }, { id: 1, name: 'VM2', nbCpu: 4, memory: 2000, diskTypeId: 1, diskCapacity: 300, users: undefined, osId: 1 }]; function getRefs(request, reply) { reply(references); } function getVms(request, reply) { if (request.query.name) { reply(vms); } else { reply(vms); } } function getVm(request, reply) { reply(vms[request.params.id]); } function addVm(request, reply) { var vm = { id: vms[vms.length - 1].id + 1, name: request.payload.name, nbCpu: 4, memory: 2000, diskTypeId: 1, diskCapacity: 300, users: undefined, osId: 1 }; vms.push(vm); reply(vm).code(201); } function updateVm(request, reply) { console.log('Update VM', request, reply); vms[vms.request.payload.id] = request.payload; reply(request.payload).code(200); } function deleteVm(request,reply){ console.log('delete VM', request.params.id); reply(); }
ajout d'une erreur en dur sur le update
example/api/routes.js
ajout d'une erreur en dur sur le update
<ide><path>xample/api/routes.js <ide> } <ide> }, { <ide> method: 'PUT', <del> path: '/vm', <add> path: '/vm/{id}', <ide> config: { <ide> handler: updateVm <ide> } <ide> <ide> function updateVm(request, reply) { <ide> console.log('Update VM', request, reply); <del> vms[vms.request.payload.id] = request.payload; <del> reply(request.payload).code(200); <add> //vms[vms.request.payload.id] = request.payload; <add> //reply(request.payload).code(200); <add> <add> //error response <add> reply({ <add> errors : [{fieldName: "memory", message: "la memoire est insuffisante."},{fieldName:"" , message: "erreur globale de la VM."}] <add> }).code(501); <ide> } <ide> <ide> function deleteVm(request,reply){
Java
apache-2.0
3ebcfcaa0783cde7b62c009989f5fb0d556e9053
0
diydyq/velocity-engine,diydyq/velocity-engine,pcollaog/velocity-engine,pcollaog/velocity-engine
package org.apache.velocity.runtime.parser.node; /* Generated By:JJTree: Do not edit this line. ASTReference.java */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ import java.io.Writer; import java.io.IOException; import java.util.Map; import java.lang.reflect.Method; import org.apache.velocity.context.Context; import org.apache.velocity.context.InternalContextAdapter; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.exception.ReferenceException; import org.apache.velocity.runtime.parser.*; /** * This class is responsible for handling the references in * VTL ($foo). * * Please look at the Parser.jjt file which is * what controls the generation of this class. * * @author <a href="mailto:[email protected]">Jason van Zyl</a> * @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a> * @author <a href="mailto:[email protected]">Christoph Reck</a> * @version $Id: ASTReference.java,v 1.19 2001/01/18 05:08:18 geirm Exp $ */ public class ASTReference extends SimpleNode { /* Reference types */ private static final int NORMAL_REFERENCE = 1; private static final int FORMAL_REFERENCE = 2; private static final int QUIET_REFERENCE = 3; private int referenceType; private String nullString; private String rootString; private boolean escaped = false; private boolean computableReference = true; private String prefix = ""; public ASTReference(int id) { super(id); } public ASTReference(Parser p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public Object init( InternalContextAdapter context, Object data) throws Exception { /* * init our children */ super.init( context, data ); /* * the only thing we can do in init() is getRoot() * as that is template based, not context based, * so it's thread- and context-safe */ rootString = getRoot(); return data; } /** * gets an Object that 'is' the value of the reference * * @param o unused Object parameter * @param context context used to generate value */ public Object execute(Object o, InternalContextAdapter context) { /* * get the root object from the context */ Object result = getVariableValue(context, rootString); if (result == null) return null; /* * iteratively work 'down' (it's flat...) the reference * to get the value */ int children = jjtGetNumChildren(); for (int i = 0; i < children; i++) result = jjtGetChild(i).execute(result,context); return result; } /** * gets the value of the reference and outputs it to the * writer. * * @param context context of data to use in getting value * @param writer writer to render to */ public boolean render( InternalContextAdapter context, Writer writer) throws IOException { Object value = execute(null, context); /* * if this reference is escaped (\$foo) then we want to do one of two things : * 1) if this is a reference in the context, then we want to print $foo * 2) if not, then \$foo (its considered shmoo, not VTL) */ if ( escaped ) { if ( value == null ) writer.write( NodeUtils.specialText(getFirstToken()) + prefix + "\\" + nullString ); else writer.write( NodeUtils.specialText(getFirstToken()) + prefix + nullString ); return true; } /* * the normal processing */ if (value == null) { /* * write prefix twice, because it's shmoo, so the \ don't escape each other... */ writer.write(NodeUtils.specialText(getFirstToken()) + prefix + prefix + nullString); if (referenceType != QUIET_REFERENCE && Runtime.getBoolean( RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID, true) ) Runtime.warn(new ReferenceException("reference : template = " + context.getCurrentTemplateName(), this)); } else { writer.write(NodeUtils.specialText(getFirstToken()) + prefix + value.toString()); } return true; } /** * Computes boolean value of this reference * Returns the actual value of reference return type * boolean, and 'true' if value is not null * * @param context context to compute value with */ public boolean evaluate( InternalContextAdapter context) { Object value = execute(null, context); if (value == null) return false; else if (value instanceof Boolean) { if (((Boolean) value).booleanValue()) return true; else return false; } else return true; } public Object value( InternalContextAdapter context) { return ( computableReference ? execute(null, context) : null ); } /** * Sets the value of a complex reference (something like $foo.bar) * Currently used by ASTSetReference() * * @see ASTSetDirective * * @param context context object containing this reference * @param value Object to set as value * @return true if successful, false otherwise */ public boolean setValue( InternalContextAdapter context, Object value) { /* * The rootOfIntrospection is the object we will * retrieve from the Context. This is the base * object we will apply reflection to. */ Object result = getVariableValue(context, rootString); if (result == null) { Runtime.error(new ReferenceException("reference set : template = " + context.getCurrentTemplateName(), this)); return false; } /* * How many child nodes do we have? */ int children = jjtGetNumChildren(); for (int i = 0; i < children - 1; i++) { result = jjtGetChild(i).execute(result, context); if (result == null) { Runtime.error(new ReferenceException("reference set : template = " + context.getCurrentTemplateName(), this)); return false; } } /* * We support two ways of setting the value in a #set($ref.foo = $value ) : * 1) ref.setFoo( value ) * 2) ref,put("foo", value ) to parallel the get() map introspection */ String identifier = jjtGetChild(children - 1).getFirstToken().image; try { /* * first, we introspect for the set<identifier> setter method */ Class[] params = { value.getClass() }; Class c = result.getClass(); Method m = c.getMethod("set" + identifier, params); /* * and if we get here, getMethod() didn't chuck an exception... */ Object[] args = { value }; m.invoke(result, args); } catch (NoSuchMethodException nsme) { /* * right now, we only support the Map interface */ if (result instanceof Map) { try { ((Map) result).put(identifier, value); } catch (Exception ex) { Runtime.error("ASTReference Map.put : exception : " + ex + " template = " + context.getCurrentTemplateName() + " [" + this.getLine() + "," + this.getColumn() + "]"); return false; } } else { Runtime.error("ASTReference : cannot find " + identifier + " as settable property or key to Map in" + " template = " + context.getCurrentTemplateName() + " [" + this.getLine() + "," + this.getColumn() + "]"); return false; } } catch( Exception e ) { /* * maybe a security exception? */ Runtime.error("ASTReference setValue() : exception : " + e + " template = " + context.getCurrentTemplateName() + " [" + this.getLine() + "," + this.getColumn() + "]"); return false; } return true; } private String getRoot() { Token t = getFirstToken(); /* * we have a special case where something like * $(\\)*!, where the user want's to see something * like $!blargh in the output, but the ! prevents it from showing. * I think that at this point, this isn't a reference. */ /* so, see if we have "\\!" */ int slashbang = t.image.indexOf("\\!"); if ( slashbang != -1 ) { /* * lets do all the work here. I would argue that if this occurrs, it's * not a reference at all, so preceeding \ characters in front of the $ * are just schmoo. So we just do the escape processing trick (even | odd) * and move on. This kind of breaks the rule pattern of $ and # but '!' really * tosses a wrench into things. */ /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.length(); i = t.image.indexOf("$"); if (i == -1) { /* yikes! */ Runtime.error("ASTReference.getRoot() : internal error : no $ found for slashbang."); computableReference = false; nullString = t.image; return nullString; } while( i < len && t.image.charAt(i) != '\\') i++; /* ok, i is the first \ char */ int start = i; int count = 0; while( i < len && t.image.charAt(i++) == '\\' ) count++; /* * now construct the output string. We really don't care about leading * slashes as this is not a reference. It's quasi-schmoo */ nullString = t.image.substring(0,start); // prefix up to the first nullString += t.image.substring(start, start + count-1 ); // get the slashes nullString += t.image.substring(start+count); // and the rest, including the /* * this isn't a valid reference, so lets short circuit the value and set calcs */ computableReference = false; return nullString; } /* * we need to see if this reference is escaped. if so * we will clean off the leading \'s and let the * regular behavior determine if we should output this * as \$foo or $foo later on in render(). Lazyness.. */ escaped = false; if ( t.image.startsWith("\\")) { /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.length(); while( i < len && t.image.charAt(i) == '\\' ) i++; if ( (i % 2) != 0 ) escaped = true; if (i > 0) prefix = t.image.substring(0, i / 2 ); t.image = t.image.substring(i); } /* * get the literal in case this reference isn't backed by the context at runtime */ nullString = literal(); if (t.image.startsWith("$!")) { referenceType = QUIET_REFERENCE; /* * only if we aren't escaped do we want to null the output */ if (!escaped) nullString = ""; if (t.image.startsWith("$!{")) { /* * ex : $!{provider.Title} */ return t.next.image; } else { /* * ex : $!provider.Title */ return t.image.substring(2); } } else if (t.image.equals("${")) { /* * ex : ${provider.Title} */ referenceType = FORMAL_REFERENCE; return t.next.image; } else { /* * ex : $provider.Title */ referenceType = NORMAL_REFERENCE; return t.image.substring(1); } } public Object getVariableValue(Context context, String variable) { return context.get(variable); } }
src/java/org/apache/velocity/runtime/parser/node/ASTReference.java
/* Generated By:JJTree: Do not edit this line. ASTReference.java */ /* * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. 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. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact [email protected]. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR * ITS 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. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ /** * This class is responsible for handling the references in * VTL ($foo). * * Please look at the Parser.jjt file which is * what controls the generation of this class. * * @author <a href="mailto:[email protected]">Jason van Zyl</a> * @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a> * @version $Id: ASTReference.java,v 1.18 2001/01/03 05:27:37 geirm Exp $ */ package org.apache.velocity.runtime.parser.node; import java.io.Writer; import java.io.IOException; import java.util.Map; import java.lang.reflect.Method; import org.apache.velocity.context.Context; import org.apache.velocity.context.InternalContextAdapter; import org.apache.velocity.runtime.Runtime; import org.apache.velocity.runtime.RuntimeConstants; import org.apache.velocity.runtime.exception.ReferenceException; import org.apache.velocity.runtime.parser.*; public class ASTReference extends SimpleNode { /* Reference types */ private static final int NORMAL_REFERENCE = 1; private static final int FORMAL_REFERENCE = 2; private static final int QUIET_REFERENCE = 3; private int referenceType; private String nullString; private String rootString; private boolean escaped = false; private boolean computableReference = true; private String prefix = ""; public ASTReference(int id) { super(id); } public ASTReference(Parser p, int id) { super(p, id); } /** Accept the visitor. **/ public Object jjtAccept(ParserVisitor visitor, Object data) { return visitor.visit(this, data); } public Object init( InternalContextAdapter context, Object data) throws Exception { /* * init our children */ super.init( context, data ); /* * the only thing we can do in init() is getRoot() * as that is template based, not context based, * so it's thread- and context-safe */ rootString = getRoot(); return data; } /** * gets an Object that 'is' the value of the reference * * @param o unused Object parameter * @param context context used to generate value */ public Object execute(Object o, InternalContextAdapter context) { /* * get the root object from the context */ Object result = getVariableValue(context, rootString); if (result == null) return null; /* * iteratively work 'down' (it's flat...) the reference * to get the value */ int children = jjtGetNumChildren(); for (int i = 0; i < children; i++) result = jjtGetChild(i).execute(result,context); return result; } /** * gets the value of the reference and outputs it to the * writer. * * @param context context of data to use in getting value * @param writer writer to render to */ public boolean render( InternalContextAdapter context, Writer writer) throws IOException { Object value = execute(null, context); /* * if this reference is escaped (\$foo) then we want to do one of two things : * 1) if this is a reference in the context, then we want to print $foo * 2) if not, then \$foo (its considered shmoo, not VTL) */ if ( escaped ) { if ( value == null ) writer.write( NodeUtils.specialText(getFirstToken()) + prefix + "\\" + nullString ); else writer.write( NodeUtils.specialText(getFirstToken()) + prefix + nullString ); return true; } /* * the normal processing */ if (value == null) { /* * write prefix twice, because it's shmoo, so the \ don't escape each other... */ writer.write(NodeUtils.specialText(getFirstToken()) + prefix + prefix + nullString); if (referenceType != QUIET_REFERENCE && Runtime.getBoolean( RuntimeConstants.RUNTIME_LOG_REFERENCE_LOG_INVALID, true) ) Runtime.warn(new ReferenceException("reference : template = " + context.getCurrentTemplateName(), this)); } else { writer.write(NodeUtils.specialText(getFirstToken()) + prefix + value.toString()); } return true; } /** * Computes boolean value of this reference * Returns the actual value of reference return type * boolean, and 'true' if value is not null * * @param context context to compute value with */ public boolean evaluate( InternalContextAdapter context) { Object value = execute(null, context); if (value == null) return false; else if (value instanceof Boolean) { if (((Boolean) value).booleanValue()) return true; else return false; } else return true; } public Object value( InternalContextAdapter context) { return ( computableReference ? execute(null, context) : null ); } public boolean setValue( InternalContextAdapter context, Object value) { /* * The rootOfIntrospection is the object we will * retrieve from the Context. This is the base * object we will apply reflection to. */ Object result = getVariableValue(context, rootString); if (result == null) { Runtime.error(new ReferenceException("reference set : template = " + context.getCurrentTemplateName(), this)); return false; } /* * How many child nodes do we have? */ int children = jjtGetNumChildren(); for (int i = 0; i < children - 1; i++) { result = jjtGetChild(i).execute(result, context); if (result == null) { Runtime.error(new ReferenceException("reference set : template = " + context.getCurrentTemplateName(), this)); return false; } } Object[] args = { value }; Class[] params = { value.getClass() }; /* * This catches the last phase of setting a property * if we catch an exception we know that something * like $provider.Monkey is not a valid reference. * $provider may be in the context, but Monkey is * not a method of $provider. */ try { Class c = result.getClass(); Method m = c.getMethod("set" + jjtGetChild(children - 1).getFirstToken().image, params); m.invoke(result, args); } catch (Exception e) { Runtime.error(new ReferenceException("reference set : template = " + context.getCurrentTemplateName(), this)); return false; } return true; } private String getRoot() { Token t = getFirstToken(); /* * we have a special case where something like * $(\\)*!, where the user want's to see something * like $!blargh in the output, but the ! prevents it from showing. * I think that at this point, this isn't a reference. */ /* so, see if we have "\\!" */ int slashbang = t.image.indexOf("\\!"); if ( slashbang != -1 ) { /* * lets do all the work here. I would argue that if this occurrs, it's * not a reference at all, so preceeding \ characters in front of the $ * are just schmoo. So we just do the escape processing trick (even | odd) * and move on. This kind of breaks the rule pattern of $ and # but '!' really * tosses a wrench into things. */ /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.length(); i = t.image.indexOf("$"); if (i == -1) { /* yikes! */ Runtime.error("ASTReference.getRoot() : internal error : no $ found for slashbang."); computableReference = false; nullString = t.image; return nullString; } while( i < len && t.image.charAt(i) != '\\') i++; /* ok, i is the first \ char */ int start = i; int count = 0; while( i < len && t.image.charAt(i++) == '\\' ) count++; /* * now construct the output string. We really don't care about leading * slashes as this is not a reference. It's quasi-schmoo */ nullString = t.image.substring(0,start); // prefix up to the first nullString += t.image.substring(start, start + count-1 ); // get the slashes nullString += t.image.substring(start+count); // and the rest, including the /* * this isn't a valid reference, so lets short circuit the value and set calcs */ computableReference = false; return nullString; } /* * we need to see if this reference is escaped. if so * we will clean off the leading \'s and let the * regular behavior determine if we should output this * as \$foo or $foo later on in render(). Lazyness.. */ escaped = false; if ( t.image.startsWith("\\")) { /* * count the escapes : even # -> not escaped, odd -> escaped */ int i = 0; int len = t.image.length(); while( i < len && t.image.charAt(i) == '\\' ) i++; if ( (i % 2) != 0 ) escaped = true; if (i > 0) prefix = t.image.substring(0, i / 2 ); t.image = t.image.substring(i); } /* * get the literal in case this reference isn't backed by the context at runtime */ nullString = literal(); if (t.image.startsWith("$!")) { referenceType = QUIET_REFERENCE; /* * only if we aren't escaped do we want to null the output */ if (!escaped) nullString = ""; if (t.image.startsWith("$!{")) { /* * ex : $!{provider.Title} */ return t.next.image; } else { /* * ex : $!provider.Title */ return t.image.substring(2); } } else if (t.image.equals("${")) { /* * ex : ${provider.Title} */ referenceType = FORMAL_REFERENCE; return t.next.image; } else { /* * ex : $provider.Title */ referenceType = NORMAL_REFERENCE; return t.image.substring(1); } } public Object getVariableValue(Context context, String variable) { return context.get(variable); } }
Added the contribution from Christoph Reck <[email protected]> to support Map introspection on #set() So #set($foo.bar = "blargh") will attempt foo.put("bar", "blargh") if foo.setBar( "blargh" ) fails. PR: Obtained from: Submitted by: Reviewed by: git-svn-id: 7267684f36935cb3df12efc1f4c0216d758271d4@74142 13f79535-47bb-0310-9956-ffa450edef68
src/java/org/apache/velocity/runtime/parser/node/ASTReference.java
Added the contribution from Christoph Reck <[email protected]> to support Map introspection on #set()
<ide><path>rc/java/org/apache/velocity/runtime/parser/node/ASTReference.java <add>package org.apache.velocity.runtime.parser.node; <add> <ide> /* Generated By:JJTree: Do not edit this line. ASTReference.java */ <ide> <ide> /* <ide> * <http://www.apache.org/>. <ide> */ <ide> <add>import java.io.Writer; <add>import java.io.IOException; <add>import java.util.Map; <add>import java.lang.reflect.Method; <add> <add>import org.apache.velocity.context.Context; <add>import org.apache.velocity.context.InternalContextAdapter; <add>import org.apache.velocity.runtime.Runtime; <add>import org.apache.velocity.runtime.RuntimeConstants; <add>import org.apache.velocity.runtime.exception.ReferenceException; <add>import org.apache.velocity.runtime.parser.*; <add> <ide> <ide> /** <ide> * This class is responsible for handling the references in <ide> * <ide> * @author <a href="mailto:[email protected]">Jason van Zyl</a> <ide> * @author <a href="mailto:[email protected]">Geir Magnusson Jr.</a> <del> * @version $Id: ASTReference.java,v 1.18 2001/01/03 05:27:37 geirm Exp $ <add> * @author <a href="mailto:[email protected]">Christoph Reck</a> <add> * @version $Id: ASTReference.java,v 1.19 2001/01/18 05:08:18 geirm Exp $ <ide> */ <del> <del>package org.apache.velocity.runtime.parser.node; <del> <del>import java.io.Writer; <del>import java.io.IOException; <del>import java.util.Map; <del>import java.lang.reflect.Method; <del> <del>import org.apache.velocity.context.Context; <del>import org.apache.velocity.context.InternalContextAdapter; <del>import org.apache.velocity.runtime.Runtime; <del>import org.apache.velocity.runtime.RuntimeConstants; <del>import org.apache.velocity.runtime.exception.ReferenceException; <del>import org.apache.velocity.runtime.parser.*; <ide> <ide> public class ASTReference extends SimpleNode <ide> { <ide> return ( computableReference ? execute(null, context) : null ); <ide> } <ide> <add> /** <add> * Sets the value of a complex reference (something like $foo.bar) <add> * Currently used by ASTSetReference() <add> * <add> * @see ASTSetDirective <add> * <add> * @param context context object containing this reference <add> * @param value Object to set as value <add> * @return true if successful, false otherwise <add> */ <ide> public boolean setValue( InternalContextAdapter context, Object value) <ide> { <ide> /* <ide> } <ide> } <ide> <del> Object[] args = { value }; <del> Class[] params = { value.getClass() }; <del> <del> /* <del> * This catches the last phase of setting a property <del> * if we catch an exception we know that something <del> * like $provider.Monkey is not a valid reference. <del> * $provider may be in the context, but Monkey is <del> * not a method of $provider. <del> */ <add> /* <add> * We support two ways of setting the value in a #set($ref.foo = $value ) : <add> * 1) ref.setFoo( value ) <add> * 2) ref,put("foo", value ) to parallel the get() map introspection <add> */ <add> <add> String identifier = jjtGetChild(children - 1).getFirstToken().image; <ide> <ide> try <ide> { <add> /* <add> * first, we introspect for the set<identifier> setter method <add> */ <add> <add> Class[] params = { value.getClass() }; <ide> Class c = result.getClass(); <del> Method m = c.getMethod("set" + jjtGetChild(children - 1).getFirstToken().image, params); <add> Method m = c.getMethod("set" + identifier, params); <add> <add> /* <add> * and if we get here, getMethod() didn't chuck an exception... <add> */ <add> <add> Object[] args = { value }; <ide> m.invoke(result, args); <ide> } <del> catch (Exception e) <del> { <del> Runtime.error(new ReferenceException("reference set : template = " + context.getCurrentTemplateName(), this)); <add> catch (NoSuchMethodException nsme) <add> { <add> /* <add> * right now, we only support the Map interface <add> */ <add> <add> if (result instanceof Map) <add> { <add> try <add> { <add> ((Map) result).put(identifier, value); <add> } <add> catch (Exception ex) <add> { <add> Runtime.error("ASTReference Map.put : exception : " + ex <add> + " template = " + context.getCurrentTemplateName() <add> + " [" + this.getLine() + "," + this.getColumn() + "]"); <add> return false; <add> } <add> } <add> else <add> { <add> Runtime.error("ASTReference : cannot find " + identifier + " as settable property or key to Map in" <add> + " template = " + context.getCurrentTemplateName() <add> + " [" + this.getLine() + "," + this.getColumn() + "]"); <add> return false; <add> <add> } <add> } <add> catch( Exception e ) <add> { <add> /* <add> * maybe a security exception? <add> */ <add> Runtime.error("ASTReference setValue() : exception : " + e <add> + " template = " + context.getCurrentTemplateName() <add> + " [" + this.getLine() + "," + this.getColumn() + "]"); <ide> return false; <del> } <add> } <ide> <ide> return true; <ide> }
Java
mit
f9147f80e568fd1de850a9c67be19d28cadeaad2
0
aeshell/nanook,aeshell/nanook
/* * JBoss, Home of Professional Open Source Copyright 2014 Red Hat Inc. and/or its affiliates and * other contributors as indicated by the @authors tag. All rights reserved. See the copyright.txt * in the distribution for a full listing of individual contributors. * * 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.jboss.aesh.cloverxell.controller; import org.esmerilprogramming.cloverx.annotation.Controller; import org.esmerilprogramming.cloverx.annotation.Page; import org.esmerilprogramming.cloverx.http.CloverXRequest; import org.esmerilprogramming.cloverx.http.CloverXSession; /** * @author <a href="mailto:[email protected]">Helio Frota</a> */ @Controller public class CloverxellController { private static final String AESH = "aesh"; private static final String TEMPLATE = "cloverxell.ftl"; @Page(value = "", responseTemplate = TEMPLATE) public void init() throws Exception { } @Page("send") public void send(String command, String customCommand, CloverXRequest request) throws Exception { AeshHandler aesh = getAeshHandler(request); if (customCommand == null) { aesh.run(command); } else { aesh.run(customCommand); } String result = aesh.getResult(); result = result.replaceAll("@", " "); result = result + "@" + aesh.getCurrentDirectory(); request.getExchange().getResponseSender().send(result); aesh.reset(); } @Page("remove") public void remove(String commandName, CloverXRequest request) { getAeshHandler(request).remove(commandName); } protected AeshHandler getAeshHandler(CloverXRequest request) { CloverXSession session = request.getSession(); if (session.getAttribute(AESH) == null) { session.setAttribute(AESH, new AeshHandler()); } return session.getAttribute(AESH, AeshHandler.class); } }
src/main/java/org/jboss/aesh/cloverxell/controller/CloverxellController.java
/* * JBoss, Home of Professional Open Source Copyright 2014 Red Hat Inc. and/or its affiliates and * other contributors as indicated by the @authors tag. All rights reserved. See the copyright.txt * in the distribution for a full listing of individual contributors. * * 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.jboss.aesh.cloverxell.controller; import org.esmerilprogramming.cloverx.annotation.Controller; import org.esmerilprogramming.cloverx.annotation.Page; import org.esmerilprogramming.cloverx.http.CloverXRequest; import org.esmerilprogramming.cloverx.http.CloverXSession; /** * @author <a href="mailto:[email protected]">Helio Frota</a> */ @Controller public class CloverxellController { private static final String AESH = "aesh"; private static final String TEMPLATE = "cloverxell.ftl"; @Page(value = "", responseTemplate = TEMPLATE) public void init() throws Exception { } @Page("send") public void send(String command, String customCommand, CloverXRequest request) throws Exception { AeshHandler aesh = getAeshHandler(request); if (customCommand == null) { aesh.run(command); } else { aesh.run(customCommand); } String result = aesh.getResult() + "@" + aesh.getCurrentDirectory(); request.getExchange().getResponseSender().send(result); aesh.reset(); } @Page("remove") public void remove(String commandName, CloverXRequest request) { getAeshHandler(request).remove(commandName); } protected AeshHandler getAeshHandler(CloverXRequest request) { CloverXSession session = request.getSession(); if (session.getAttribute(AESH) == null) { session.setAttribute(AESH, new AeshHandler()); } return session.getAttribute(AESH, AeshHandler.class); } }
this closes #80
src/main/java/org/jboss/aesh/cloverxell/controller/CloverxellController.java
this closes #80
<ide><path>rc/main/java/org/jboss/aesh/cloverxell/controller/CloverxellController.java <ide> else { <ide> aesh.run(customCommand); <ide> } <del> String result = aesh.getResult() + "@" + aesh.getCurrentDirectory(); <add> <add> <add> String result = aesh.getResult(); <add> result = result.replaceAll("@", " "); <add> result = result + "@" + aesh.getCurrentDirectory(); <ide> request.getExchange().getResponseSender().send(result); <ide> aesh.reset(); <ide> }
Java
apache-2.0
06052bd37ed1eba37b442a6a59af6c801f2e79a9
0
ozil87/pyconjp-android,ozil87/pyconjp-android,ozil87/pyconjp-android
package jp.pycon.pyconjp2016app.Feature.Talks.List; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import io.realm.Realm; import io.realm.RealmChangeListener; import io.realm.RealmResults; import jp.pycon.pyconjp2016app.API.Client.APIClient; import jp.pycon.pyconjp2016app.App; import jp.pycon.pyconjp2016app.Feature.Talks.Adapter.RealmScheduleAdapter; import jp.pycon.pyconjp2016app.Feature.Talks.Detail.TalkDetailActivity; import jp.pycon.pyconjp2016app.Model.PyConJP.PresentationDetailEntity; import jp.pycon.pyconjp2016app.Model.Realm.RealmPresentationObject; import jp.pycon.pyconjp2016app.R; import jp.pycon.pyconjp2016app.Util.RealmUtil; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by rhoboro on 4/23/16. */ public class TalkListFragment extends Fragment { private Context mContext; private Realm realm; private RecyclerView recyclerView; private RealmResults<RealmPresentationObject> schedules; private RealmChangeListener realmListener; RealmScheduleAdapter adapter; public TalkListFragment() { } public static TalkListFragment newInstance(int position, boolean bookmark) { Bundle args = new Bundle(); args.putInt("position", position); args.putBoolean("bookmark", bookmark); TalkListFragment fragment = new TalkListFragment(); fragment.setArguments(args); return fragment; } @Override public void onAttach(Context context) { super.onAttach(context); this.mContext = context; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_talk_list, container, false); recyclerView = (RecyclerView) v.findViewById(R.id.talk_recycler_view); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.argb(15, 0, 0, 0)); final int dividerHeight = (int) (1 * getResources().getDisplayMetrics().density); recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() { @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDrawOver(c, parent, state); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); final RecyclerView.LayoutManager manager = parent.getLayoutManager(); final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i = 1; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (params.getViewLayoutPosition() == 0) { continue; } final int top = manager.getDecoratedTop(child) - params.topMargin + Math.round(ViewCompat.getTranslationY(child)); final int bottom = top + dividerHeight; c.drawRect(left, top, right, bottom, paint); } } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition(); int top = position == 0 ? 0 : dividerHeight; outRect.set(0, top, 0, 0); } }); return v; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); realm = Realm.getDefaultInstance(); setupRecycleView(); } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroyView() { super.onDestroyView(); schedules.removeChangeListener(realmListener); realm.close(); } private void setupRecycleView() { Bundle bundle = getArguments(); final boolean bookmark = bundle.getBoolean("bookmark", false); final int position = bundle.getInt("position"); schedules = bookmark ? RealmUtil.getBookmarkTalks(mContext, realm, position) : RealmUtil.getAllTalks(realm, position); adapter = new RealmScheduleAdapter(getContext(), schedules); adapter.setOnClickListener(new RealmScheduleAdapter.RealmScheduleAdapterListener() { @Override public void onClick(int pk) { TalkDetailActivity.start(mContext, pk); } }); recyclerView.setAdapter(adapter); realmListener = new RealmChangeListener() { @Override public void onChange(Object element) { adapter.notifyDataSetChanged(); } }; schedules.addChangeListener(realmListener); } }
app/src/main/java/jp/pycon/pyconjp2016app/Feature/Talks/List/TalkListFragment.java
package jp.pycon.pyconjp2016app.Feature.Talks.List; import android.content.Context; import android.content.Intent; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v4.view.ViewCompat; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import io.realm.Realm; import io.realm.RealmChangeListener; import io.realm.RealmResults; import jp.pycon.pyconjp2016app.API.Client.APIClient; import jp.pycon.pyconjp2016app.App; import jp.pycon.pyconjp2016app.Feature.Talks.Adapter.RealmScheduleAdapter; import jp.pycon.pyconjp2016app.Feature.Talks.Detail.TalkDetailActivity; import jp.pycon.pyconjp2016app.Model.PyConJP.PresentationDetailEntity; import jp.pycon.pyconjp2016app.Model.Realm.RealmPresentationObject; import jp.pycon.pyconjp2016app.R; import jp.pycon.pyconjp2016app.Util.RealmUtil; import rx.Subscriber; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by rhoboro on 4/23/16. */ public class TalkListFragment extends Fragment { private Context mContext; private Realm realm; private RecyclerView recyclerView; private RealmResults<RealmPresentationObject> schedules; private RealmChangeListener realmListener; RealmScheduleAdapter adapter; public TalkListFragment() { } public static TalkListFragment newInstance(int position, boolean bookmark) { Bundle args = new Bundle(); args.putInt("position", position); args.putBoolean("bookmark", bookmark); TalkListFragment fragment = new TalkListFragment(); fragment.setArguments(args); return fragment; } @Override public void onAttach(Context context) { super.onAttach(context); this.mContext = context; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.fragment_talk_list, container, false); recyclerView = (RecyclerView) v.findViewById(R.id.talk_recycler_view); recyclerView.setHasFixedSize(true); RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity()); recyclerView.setLayoutManager(layoutManager); final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.argb(15, 0, 0, 0)); final int dividerHeight = (int) (1 * getResources().getDisplayMetrics().density); recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() { @Override public void onDrawOver(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDrawOver(c, parent, state); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { super.onDraw(c, parent, state); final RecyclerView.LayoutManager manager = parent.getLayoutManager(); final int left = parent.getPaddingLeft(); final int right = parent.getWidth() - parent.getPaddingRight(); final int childCount = parent.getChildCount(); for (int i = 1; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams(); if (params.getViewLayoutPosition() == 0) { continue; } final int top = manager.getDecoratedTop(child) - params.topMargin + Math.round(ViewCompat.getTranslationY(child)); final int bottom = top + dividerHeight; c.drawRect(left, top, right, bottom, paint); } } @Override public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) { int position = ((RecyclerView.LayoutParams) view.getLayoutParams()).getViewLayoutPosition(); int top = position == 0 ? 0 : dividerHeight; outRect.set(0, top, 0, 0); } }); return v; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); realm = Realm.getDefaultInstance(); setupRecycleView(); } @Override public void onStart() { super.onStart(); } @Override public void onStop() { super.onStop(); } @Override public void onDestroyView() { super.onDestroyView(); schedules.removeChangeListener(realmListener); realm.close(); } private void setupRecycleView() { Bundle bundle = getArguments(); final boolean bookmark = bundle.getBoolean("bookmark", false); final int position = bundle.getInt("position"); schedules = bookmark ? RealmUtil.getBookmarkTalks(mContext, realm, position) : RealmUtil.getAllTalks(realm, position); adapter = new RealmScheduleAdapter(getContext(), schedules); adapter.setOnClickListener(new RealmScheduleAdapter.RealmScheduleAdapterListener() { @Override public void onClick(int pk) { TalkDetailActivity.start(mContext, pk); Toast.makeText(getContext(), "" + pk, Toast.LENGTH_SHORT).show(); } }); recyclerView.setAdapter(adapter); realmListener = new RealmChangeListener() { @Override public void onChange(Object element) { adapter.notifyDataSetChanged(); } }; schedules.addChangeListener(realmListener); } }
不要な処理を削除
app/src/main/java/jp/pycon/pyconjp2016app/Feature/Talks/List/TalkListFragment.java
不要な処理を削除
<ide><path>pp/src/main/java/jp/pycon/pyconjp2016app/Feature/Talks/List/TalkListFragment.java <ide> @Override <ide> public void onClick(int pk) { <ide> TalkDetailActivity.start(mContext, pk); <del> Toast.makeText(getContext(), "" + pk, Toast.LENGTH_SHORT).show(); <ide> } <ide> }); <ide> recyclerView.setAdapter(adapter); <ide> }; <ide> schedules.addChangeListener(realmListener); <ide> } <del> <ide> }
JavaScript
mit
f616a78a40a76084ca09c394252232834e9f150f
0
mwbrooks/phonegap-plugin-hashpipe,mwbrooks/phonegap-plugin-hashpipe
(function() { var Store = function() { // In order to 'just work' with the Lawnchair BlackBerryPersistentStore adaptor, // the public API must be 'get', 'getAll', 'put', 'remove', 'nuke' return { get: function(successCallback, errorCallback, key) { var successWrapper = function(value) { successCallback( (value === 'null') ? null : value ); }; PhoneGap.exec(successWrapper, errorCallback, 'Store', 'load', [key]); }, getAll: function(successCallback, errorCallback) { PhoneGap.exec(successCallback, errorCallback, 'Store', 'all', []); }, put: function(successCallback, errorCallback, key, value) { PhoneGap.exec(successCallback, errorCallback, 'Store', 'save', [key, value]); }, remove: function(successCallback, errorCallback, key) { PhoneGap.exec(successCallback, errorCallback, 'Store', 'remove', [key]); }, nuke: function(successCallback, errorCallback) { PhoneGap.exec(successCallback, errorCallback, 'Store', 'nuke', []); } }; }; PhoneGap.addConstructor(function() { // add plugin to window.plugins PhoneGap.addPlugin('store', new Store()); // register plugin on native side phonegap.PluginManager.addPlugin('Store', 'com.phonegap.plugins.Store'); // Stub the persistent storage adaptor if (!window.navigator) window.navigator = {}; window.navigator.store = window.plugins.store; }); })();
plugin/www/javascript/store.js
// // An almost blind copy & paste of store.js from phonegap/phonegap-blackberry // This will fail horribly, but at least the public functions will now exist // (function() { function Store() { this.save_success = null; this.save_error = null; this.loadAll_success = null; this.loadAll_error = null; this.load_success = null; this.load_error = null; this.remove_success = null; this.remove_error = null; this.nuke_success = null; this.nuke_error = null; } Store.prototype.getAll = function(successCallback,errorCallback) { // Wrap the success callback with a little object parses that decodes the keys and composes into a new JSON obj. // We do this because we encode all keys as they go into offline storage, so we have to decode on the way back. this.loadAll_success = function(obj){ var trueObj = {}, prop; for (prop in obj) { if (obj.hasOwnProperty(prop)) { trueObj[decodeURIComponent(prop)] = obj[prop]; } } successCallback(trueObj); }; this.loadAll_error = errorCallback; //PhoneGap.exec("store",["loadAll"]); PhoneGap.exec(this.loadAll_success, this.loadAll_error, 'Store', 'all', [ ]); }; Store.prototype.put = function(successCallback,errorCallback,key,data) { this.save_success = successCallback; this.save_error = errorCallback; // PhoneGap.exec("store",["save",encodeURIComponent(key),data]); PhoneGap.exec(this.save_success, this.save_error, 'Store', 'save', [ key, data ]); }; Store.prototype.get = function(successCallback,errorCallback,key) { this.load_success = function(value) { if (value === 'null') value = null; successCallback(value); }; this.load_error = errorCallback; // PhoneGap.exec("store",["load",encodeURIComponent(key)]); PhoneGap.exec(this.load_success, this.load_error, 'Store', 'load', [ key ]); }; Store.prototype.remove = function(successCallback, errorCallback, key) { this.remove_success = successCallback; this.remove_error = errorCallback; // PhoneGap.exec("store", ["remove",encodeURIComponent(key)]); PhoneGap.exec(this.remove_success, this.remove_error, 'Store', 'remove', [ key ]); }; Store.prototype.nuke = function(successCallback, errorCallback) { this.nuke_success = successCallback; this.nuke_error = errorCallback; // PhoneGap.exec("store", ["nuke"]); PhoneGap.exec(this.nuke_success, this.nuke_error, 'Store', 'nuke', [ ]); }; PhoneGap.addConstructor(function() { // add plugin to window.plugins PhoneGap.addPlugin('store', new Store()); // register plugin on native side phonegap.PluginManager.addPlugin('Store', 'com.phonegap.plugins.Store'); // Stub the persistent storage adaptor if (!window.navigator) window.navigator = {}; window.navigator.store = window.plugins.store; }); })();
Refactor JavaScript interface of plugin.
plugin/www/javascript/store.js
Refactor JavaScript interface of plugin.
<ide><path>lugin/www/javascript/store.js <del>// <del>// An almost blind copy & paste of store.js from phonegap/phonegap-blackberry <del>// This will fail horribly, but at least the public functions will now exist <del>// <ide> (function() { <del> function Store() { <del> this.save_success = null; <del> this.save_error = null; <del> this.loadAll_success = null; <del> this.loadAll_error = null; <del> this.load_success = null; <del> this.load_error = null; <del> this.remove_success = null; <del> this.remove_error = null; <del> this.nuke_success = null; <del> this.nuke_error = null; <del> } <del> <del> Store.prototype.getAll = function(successCallback,errorCallback) { <del> // Wrap the success callback with a little object parses that decodes the keys and composes into a new JSON obj. <del> // We do this because we encode all keys as they go into offline storage, so we have to decode on the way back. <del> this.loadAll_success = function(obj){ <del> var trueObj = {}, prop; <del> for (prop in obj) { <del> if (obj.hasOwnProperty(prop)) { <del> trueObj[decodeURIComponent(prop)] = obj[prop]; <del> } <add> var Store = function() { <add> // In order to 'just work' with the Lawnchair BlackBerryPersistentStore adaptor, <add> // the public API must be 'get', 'getAll', 'put', 'remove', 'nuke' <add> return { <add> get: function(successCallback, errorCallback, key) { <add> var successWrapper = function(value) { <add> successCallback( (value === 'null') ? null : value ); <add> }; <add> <add> PhoneGap.exec(successWrapper, errorCallback, 'Store', 'load', [key]); <add> }, <add> <add> getAll: function(successCallback, errorCallback) { <add> PhoneGap.exec(successCallback, errorCallback, 'Store', 'all', []); <add> }, <add> <add> put: function(successCallback, errorCallback, key, value) { <add> PhoneGap.exec(successCallback, errorCallback, 'Store', 'save', [key, value]); <add> }, <add> <add> remove: function(successCallback, errorCallback, key) { <add> PhoneGap.exec(successCallback, errorCallback, 'Store', 'remove', [key]); <add> }, <add> <add> nuke: function(successCallback, errorCallback) { <add> PhoneGap.exec(successCallback, errorCallback, 'Store', 'nuke', []); <ide> } <del> successCallback(trueObj); <ide> }; <del> this.loadAll_error = errorCallback; <del> //PhoneGap.exec("store",["loadAll"]); <del> PhoneGap.exec(this.loadAll_success, this.loadAll_error, 'Store', 'all', [ ]); <ide> }; <del> <del> Store.prototype.put = function(successCallback,errorCallback,key,data) { <del> this.save_success = successCallback; <del> this.save_error = errorCallback; <del> // PhoneGap.exec("store",["save",encodeURIComponent(key),data]); <del> PhoneGap.exec(this.save_success, this.save_error, 'Store', 'save', [ key, data ]); <del> }; <del> <del> Store.prototype.get = function(successCallback,errorCallback,key) { <del> this.load_success = function(value) { <del> if (value === 'null') value = null; <del> successCallback(value); <del> }; <del> <del> this.load_error = errorCallback; <del> // PhoneGap.exec("store",["load",encodeURIComponent(key)]); <del> PhoneGap.exec(this.load_success, this.load_error, 'Store', 'load', [ key ]); <del> }; <del> <del> Store.prototype.remove = function(successCallback, errorCallback, key) { <del> this.remove_success = successCallback; <del> this.remove_error = errorCallback; <del> // PhoneGap.exec("store", ["remove",encodeURIComponent(key)]); <del> PhoneGap.exec(this.remove_success, this.remove_error, 'Store', 'remove', [ key ]); <del> }; <del> <del> Store.prototype.nuke = function(successCallback, errorCallback) { <del> this.nuke_success = successCallback; <del> this.nuke_error = errorCallback; <del> // PhoneGap.exec("store", ["nuke"]); <del> PhoneGap.exec(this.nuke_success, this.nuke_error, 'Store', 'nuke', [ ]); <del> }; <del> <add> <ide> PhoneGap.addConstructor(function() { <ide> // add plugin to window.plugins <ide> PhoneGap.addPlugin('store', new Store());
Java
apache-2.0
15f4a861ac65ee9f3370e736adb5d72aa7f3e376
0
julesbond007/Android-Jigsaw-Puzzle,julesbond007/Android-Jigsaw-Puzzle
/* * Copyright (c) 2015. Jay Paulynice ([email protected]) * * 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.jigdraw.draw.dao; import com.jigdraw.draw.model.ImageEntity; import java.util.List; /** * Simple interface for {@link ImageEntity} CRUD operations * * @author Jay Paulynice ([email protected]) */ interface ImageDao { /** * Save an image entity * * @param entity the entity to create * @return the generated id */ Long create(ImageEntity entity); /** * Find entity by id * * @param id the id of the entity * @return the matching entity */ ImageEntity find(Long id); /** * Find the jigsaw tiles for the original id * * @param id the original image id * @return the jigsaw entities */ List<ImageEntity> findTiles(Long id); /** * Update the given image entity * * @param entity the entity to update * @return number of rows updated */ int update(ImageEntity entity); /** * Delete the entity by id * * @param id the id of the entity * @return number of rows deleted */ int delete(Long id); /** * Find all the original images for history * * @return list of images user created */ List<ImageEntity> getHistory(); }
app/src/main/java/com/jigdraw/draw/dao/ImageDao.java
/* * Copyright (c) 2015. Jay Paulynice ([email protected]) * * 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.jigdraw.draw.dao; import com.jigdraw.draw.model.ImageEntity; import java.util.List; /** * Simple interface for {@link ImageEntity} CRUD operations * * @author Jay Paulynice ([email protected]) */ public interface ImageDao { /** * Save an image entity * * @param entity the entity to create * @return the generated id */ Long create(ImageEntity entity); /** * Find entity by id * * @param id the id of the entity * @return the matching entity */ ImageEntity find(Long id); /** * Find the jigsaw tiles for the original id * * @param id the original image id * @return the jigsaw entities */ List<ImageEntity> findTiles(Long id); /** * Update the given image entity * * @param entity the entity to update * @return number of rows updated */ int update(ImageEntity entity); /** * Delete the entity by id * * @param id the id of the entity * @return number of rows deleted */ int delete(Long id); /** * Find all the original images for history * * @return list of images user created */ List<ImageEntity> getHistory(); }
Update ImageDao.java
app/src/main/java/com/jigdraw/draw/dao/ImageDao.java
Update ImageDao.java
<ide><path>pp/src/main/java/com/jigdraw/draw/dao/ImageDao.java <ide> * <ide> * @author Jay Paulynice ([email protected]) <ide> */ <del>public interface ImageDao { <add>interface ImageDao { <ide> /** <ide> * Save an image entity <ide> *